Reinforcement learning and decision making
Named in 20% of 2253 senior postings · 27 review cards
Learning to act from reward rather than from labels: Markov decision processes, value-based and policy-gradient methods, imitation from demonstrations, reward design, planning with a model, and the operations-research toolkit for decisions under constraints. One in five postings names something in this area, but it is concentrated: reinforcement learning is named in 42% of research engineer postings against 16% overall, mostly by labs that post-train language models with RL and by robotics and autonomy companies. It is tested in research and ML depth rounds (derive the policy gradient, explain PPO), in coding rounds (GAE, a clipped loss) and in design rounds that ask whether RL is the right tool at all.
What the postings ask for
Share of postings that name each skill, overall and by track.
| Skill | All postings | MLE | AI eng | Research eng | Cards |
|---|---|---|---|---|---|
| Reinforcement learning | 19% | 6% | 42% | 14 | |
| Operations research and combinatorial optimization | 3% | 6% | 3% | 3 | |
| Planning, search and sequential decision making | 7% | 2% | 2% | 3 | |
| Reward design and credit assignment | 2% | 0% | 6% | 4 | |
| Imitation learning and behaviour cloning | 2% | 0% | 2% | 3 |
In the postings’ words
Extensive experience with GenAI, Agentic AI, natural language processing, deep learning and deep reinforcement learning, or computer vision in a production environment
Understanding of AI security (e.g., prompt injection, tool and skill supply chain risks), safety, and responsible AI practices.
GEICO · Sr. Staff AI Engineer, AI Agent Platform (Agent & Evaluation Harness)
Hold a MSc in Reinforcement Learning, Robotics, Automation and Control, or a closely related field, with a strong focus on sequential decision-making and autonomous systems.
Have worked where evaluation meets training (reward models, preference data, RLHF, DPO or similar) and know that whatever you optimize for is what the model learns
Develop post-training approaches, including supervised fine-tuning, imitation learning, reinforcement learning, and related methods, to improve real-world robot capabilities.
The senior bar
What separates a senior answer from a mid-level one in this area.
- Decides first whether the problem needs RL at all, or whether supervised learning, a contextual bandit or a solver would do, and says what RL would cost in samples, reward design and evaluation.
- Derives the policy gradient and the advantage form from memory and explains every variance-reduction step as a bias-variance trade.
- Knows the implementation details that decide whether PPO or an off-policy method works (advantage normalisation, truncation versus termination, target networks, KL monitoring) and debugs from diagnostics, not from the return curve alone.
- Treats the reward as a specification that the agent will exploit, and checks learned behaviour by watching episodes and by metrics the reward does not contain.
- Separates what demonstrations can give (a fast start, safe behaviour near the data) from what they cannot (recovery from states the expert never visited).
- Can formulate an allocation or scheduling problem as a linear or integer program and say when a solver beats a learned policy.
Skills, checklists and questions
Tick an item when you can explain it without notes; ticks are saved in this browser. Open a question to see the answer.
Reinforcement learning 16% of postings
- Define an MDP, the value and action-value functions and write both Bellman equations
- Explain on-policy versus off-policy learning and the deadly triad
- Derive the policy gradient with a baseline and say why the baseline adds no bias
- Write generalized advantage estimation and explain what its two discount parameters trade
- Explain the PPO clipped objective and five implementation details that matter in practice
- Say why offline RL fails with a naive off-policy algorithm and name three families of fixes
- Give a debugging order for an agent whose return does not improve
coreconceptMLE AI RE Define a Markov decision process and the value functions, and write the Bellman equations. What does the Markov assumption buy you, and what do you do when it does not hold?
An MDP is \((\mathcal S, \mathcal A, P, r, \gamma)\): states, actions, transition kernel \(P(s' \mid s, a)\), reward \(r(s, a)\) and discount \(\gamma \in [0, 1)\). A policy \(\pi(a \mid s)\) induces
\[V^\pi(s) = \mathbb E_\pi\Big[\sum_{t \ge 0} \gamma^t r_t \,\Big|\, s_0 = s\Big], \qquad Q^\pi(s, a) = r(s, a) + \gamma\, \mathbb E_{s' \sim P}\big[V^\pi(s')\big].\]
Bellman expectation equation: \(V^\pi(s) = \sum_a \pi(a \mid s)\, Q^\pi(s, a)\). Bellman optimality equation:
\[Q^*(s, a) = r(s, a) + \gamma\, \mathbb E_{s'}\big[\max_{a'} Q^*(s', a')\big],\]
and the greedy policy with respect to \(Q^*\) is optimal. The advantage \(A^\pi = Q^\pi - V^\pi\) says how much better an action is than the policy’s average.
The Markov property (the next state and reward depend only on the current state and action) is what makes these recursions valid: the value of a state does not depend on how you got there, so one function of the state is enough and dynamic programming applies.
When the agent sees only an observation, the problem is a POMDP. Practical fixes are to build a state that is closer to Markov: stack recent frames, feed the history to a recurrent or transformer policy, or maintain a belief state. Symptoms of a non-Markov state are a value function that cannot fit and behaviour that oscillates in states that look identical to the agent.
Follow-ups
- Why must \(\gamma\) be below 1 in a continuing task, and what replaces it in the average-reward setting?
- Is a chat conversation with a language model an MDP? What is the state?
corecodingMLE RE Implement value iteration for a tabular MDP in NumPy and return the greedy policy. Why does it converge, and how many iterations do you need?
import numpy as np
def value_iteration(P, R, gamma=0.99, tol=1e-8, max_iter=10_000):
"""P: [S, A, S] transition probabilities, R: [S, A] expected rewards."""
V = np.zeros(P.shape[0])
for _ in range(max_iter):
Q = R + gamma * (P @ V) # [S, A]
V_new = Q.max(axis=1)
done = np.max(np.abs(V_new - V)) < tol
V = V_new
if done:
break
Q = R + gamma * (P @ V)
return V, Q.argmax(axis=1)Convergence: the Bellman optimality operator \(T\) is a \(\gamma\)-contraction in the max norm, \(\lVert TV - TU \rVert_\infty \le \gamma \lVert V - U \rVert_\infty\), so it has a unique fixed point \(V^*\) and \(\lVert V_k - V^* \rVert_\infty \le \gamma^k \lVert V_0 - V^* \rVert_\infty\). Reaching error \(\epsilon\) takes about \(\log(1/\epsilon) / (1 - \gamma)\) sweeps, each costing \(O(S^2 A)\). If successive iterates differ by less than \(\delta\), the result is within \(\gamma \delta / (1 - \gamma)\) of \(V^*\).
What an interviewer checks: the max is over actions and the expectation over next states (not the reverse); terminal states have zero outgoing value; the greedy policy is extracted from \(Q\), not from \(V\) alone. Policy iteration is the alternative: exact evaluation by solving a linear system (\(O(S^3)\)) and then greedy improvement, with far fewer but more expensive iterations.
Follow-ups
- How does the iteration count change when \(\gamma\) goes from 0.9 to 0.999?
- What breaks when you replace the table by a neural network and the sweep by sampled updates?
coreconceptMLE RE What is the difference between on-policy and off-policy learning? Use SARSA and Q-learning as the example, and explain the deadly triad.
Both learn \(Q\) by temporal-difference updates; they differ in the target.
- SARSA (on-policy): \(Q(s,a) \leftarrow Q(s,a) + \alpha\,[r + \gamma Q(s', a') - Q(s,a)]\) with \(a'\) the action the behaviour policy actually takes next. It learns the value of the policy it is following, exploration included.
- Q-learning (off-policy): the target is \(r + \gamma \max_{a'} Q(s', a')\). It learns the value of the greedy policy whatever policy generated the data.
Consequences. Off-policy methods can learn from a replay buffer, from old policies or from another agent’s data, which is why they are sample efficient. On-policy methods need fresh data after every update but optimise the thing they measure. The classic illustration is cliff walking: SARSA with \(\epsilon\)-greedy learns the safer path because it accounts for its own random steps, while Q-learning learns the edge path that is optimal only without exploration.
The deadly triad: function approximation, bootstrapping (targets built from the current estimate) and off-policy data together can make value estimates diverge. Any two are safe in theory. Practical methods keep all three and add stabilisers: target networks, double estimators, replay with limited staleness, and clipped or conservative targets.
Follow-ups
- Is PPO on-policy? It reuses each batch for several epochs.
- What is expected SARSA and when does it equal Q-learning?
seniorconceptMLE RE Why did deep Q-learning need a replay buffer and a target network, and what does Double DQN fix?
Naive Q-learning with a network regresses \(Q_\theta(s,a)\) onto \(r + \gamma \max_{a'} Q_\theta(s', a')\). Two things break supervised-learning assumptions.
- Correlated, non-stationary data. Consecutive transitions are highly correlated and their distribution shifts as the policy changes. A replay buffer samples past transitions uniformly, which decorrelates minibatches and reuses each transition many times.
- Moving targets. The target depends on the parameters being updated, so each step chases itself. A target network \(Q_{\bar\theta}\), copied every few thousand steps or updated by Polyak averaging, holds the target fixed for a while.
Overestimation. The max over noisy estimates is biased upward: \(\mathbb E[\max_a \hat Q(s,a)] \ge \max_a \mathbb E[\hat Q(s,a)]\), and bootstrapping propagates the bias. Double DQN decouples selection from evaluation:
\[y = r + \gamma\, Q_{\bar\theta}\big(s', \arg\max_{a'} Q_\theta(s', a')\big).\]
Continuous-control methods use the same idea as clipped double Q (the minimum of two critics).
Details that matter in an implementation: bootstrap with zero only on true termination and not on a time-limit truncation; use a Huber loss or clip gradients because TD errors are heavy-tailed; start learning only after the buffer has some data. Later additions (prioritised replay, dueling heads, n-step targets, distributional values) are incremental on top of these.
Follow-ups
- What goes wrong if the target network is updated every step?
- Why does prioritised replay need importance-sampling weights?
corederivationMLE RE Derive the policy gradient. Why can you subtract a baseline, and why does only the reward-to-go multiply each log-probability?
Objective: \(J(\theta) = \mathbb E_{\tau \sim p_\theta}[R(\tau)]\) with \(p_\theta(\tau) = \rho(s_0) \prod_t \pi_\theta(a_t \mid s_t)\, P(s_{t+1} \mid s_t, a_t)\).
Log-derivative trick. \(\nabla_\theta p_\theta = p_\theta \nabla_\theta \log p_\theta\), so
\[\nabla_\theta J = \mathbb E_\tau\big[R(\tau)\, \nabla_\theta \log p_\theta(\tau)\big] = \mathbb E_\tau\Big[R(\tau) \sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t)\Big],\]
because the initial-state and dynamics terms do not depend on \(\theta\). No model of the environment is needed and the reward need not be differentiable.
Causality. An action at time \(t\) cannot affect rewards before \(t\); those terms have zero expectation, so \(R(\tau)\) can be replaced by the reward-to-go \(G_t = \sum_{t' \ge t} \gamma^{t'-t} r_{t'}\).
Baseline. For any \(b(s)\) that does not depend on the action,
\[\mathbb E_{a \sim \pi_\theta}\big[\nabla_\theta \log \pi_\theta(a \mid s)\, b(s)\big] = b(s)\, \nabla_\theta \sum_a \pi_\theta(a \mid s) = b(s)\, \nabla_\theta 1 = 0,\]
so subtracting it leaves the gradient unbiased and, with \(b = V^\pi\), cuts variance sharply. The result is
\[\nabla_\theta J = \mathbb E\Big[\sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t)\, A^\pi(s_t, a_t)\Big].\]
The estimator is unbiased only for data sampled from the current \(\pi_\theta\), which is why vanilla policy gradient is on-policy and uses each batch once.
Follow-ups
- What changes in the derivation for a deterministic policy?
- Where does the variance come from, and which terms of the estimator reduce it?
seniorderivationMLE REasked at TikTok What is generalized advantage estimation? Write it down and explain what lambda trades off.
The policy gradient needs an estimate of \(A^\pi(s_t, a_t)\). Two extremes:
- Monte Carlo: \(G_t - V(s_t)\). Unbiased, high variance because it sums many random rewards.
- One-step TD: \(\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t)\). Low variance, biased whenever \(V\) is wrong.
The \(n\)-step estimator \(\hat A_t^{(n)} = \sum_{l=0}^{n-1} \gamma^l r_{t+l} + \gamma^n V(s_{t+n}) - V(s_t)\) interpolates, and it telescopes into a sum of TD errors, \(\hat A_t^{(n)} = \sum_{l=0}^{n-1} \gamma^l \delta_{t+l}\). GAE is the exponentially weighted average of all of them with weights \((1 - \lambda)\lambda^{n-1}\):
\[\hat A_t^{\mathrm{GAE}(\gamma, \lambda)} = \sum_{l \ge 0} (\gamma \lambda)^l\, \delta_{t+l}, \qquad \hat A_t = \delta_t + \gamma \lambda\, \hat A_{t+1}.\]
\(\lambda = 0\) gives one-step TD and \(\lambda = 1\) gives Monte Carlo with a baseline. Lower \(\lambda\) trusts the critic more: less variance, more bias. Values of 0.9 to 0.97 with \(\gamma\) near 0.99 are the usual starting point. The value target is \(\hat A_t + V(s_t)\).
\(\gamma\) plays a similar role: even in an undiscounted task, using \(\gamma < 1\) in the estimator reduces variance by ignoring far-future rewards at the price of bias.
Follow-ups
- Early in training the critic is poor. Would you raise or lower \(\lambda\)?
- How do you handle an episode that was cut off by a time limit?
Reported in interviews (candidate reports on third-party sites, not verified)
- TikTok, Software Engineer, Jan 2026: RL policy types and modern policy-gradient methods (TRPO, PPO, GAE) (PracHub)
seniorcodingMLE RE Implement GAE for a batch of parallel environments in PyTorch, handling episode boundaries. What are the usual bugs?
import torch
@torch.no_grad()
def gae(rewards, values, dones, last_value, gamma=0.99, lam=0.95):
"""rewards, values, dones: [T, N]; last_value: [N] is V(s_T).
dones[t] = 1 if the episode terminated at step t."""
T = rewards.shape[0]
adv = torch.zeros_like(rewards)
next_adv = torch.zeros_like(last_value)
next_value = last_value
for t in reversed(range(T)):
nonterminal = 1.0 - dones[t]
delta = rewards[t] + gamma * next_value * nonterminal - values[t]
next_adv = delta + gamma * lam * nonterminal * next_adv
adv[t] = next_adv
next_value = values[t]
returns = adv + values
return adv, returnsPitfalls an interviewer looks for:
- Boundary mask. Both the bootstrap value and the running advantage must be zeroed across a termination, otherwise credit leaks between episodes.
- Truncation is not termination. If the episode ended on a time limit, the state still has value: bootstrap from \(V\) of the final observation instead of zero. Treating truncation as termination biases values down and matters a lot in long-horizon tasks.
- Off-by-one.
dones[t]must refer to the transition out of stept; many environment wrappers report it one step later. - Gradients. Advantages and returns are targets, so compute them without gradient.
- Normalisation. Advantages are usually standardised per minibatch for the policy loss; returns are not.
Follow-ups
- Rewrite it without the Python loop. Is that worth doing?
- What changes with a recurrent policy?
seniorcodingMLE REasked at TikTok Explain the PPO clipped objective and write the loss in PyTorch. Which implementation details decide whether it works?
PPO wants several gradient epochs from each on-policy batch without moving the policy so far that the batch stops being representative. With the ratio \(r_t(\theta) = \pi_\theta(a_t \mid s_t) / \pi_{\text{old}}(a_t \mid s_t)\):
\[L^{\text{CLIP}} = \mathbb E_t\Big[\min\big(r_t \hat A_t,\ \operatorname{clip}(r_t, 1 - \epsilon, 1 + \epsilon)\, \hat A_t\big)\Big].\]
The min makes it a pessimistic bound: the objective gains nothing from pushing the ratio beyond the interval in the direction that helps, but still penalises moves that hurt. It is a first-order stand-in for TRPO’s KL trust region.
def ppo_loss(logp_new, logp_old, adv, values, returns, entropy,
clip=0.2, vf_coef=0.5, ent_coef=0.01):
adv = (adv - adv.mean()) / (adv.std() + 1e-8)
ratio = (logp_new - logp_old).exp()
surr = torch.min(ratio * adv, ratio.clamp(1 - clip, 1 + clip) * adv)
policy_loss = -surr.mean()
value_loss = 0.5 * (values - returns).pow(2).mean()
loss = policy_loss + vf_coef * value_loss - ent_coef * entropy.mean()
approx_kl = (logp_old - logp_new).mean()
return loss, approx_klDetails that matter as much as the objective: GAE with advantage normalisation; logp_old, advantages and returns fixed during the epochs; stopping the epochs early when the approximate KL exceeds a threshold (around 0.01 to 0.03); learning-rate annealing; gradient clipping; observation and reward normalisation; correct truncation handling. Clipping alone does not bound the KL, so monitor it and the fraction of clipped samples.
Follow-ups
- The approximate KL spikes after the second epoch. What do you change?
- How is this loss used when the policy is a language model generating a sequence of tokens?
Reported in interviews (candidate reports on third-party sites, not verified)
- TikTok, Software Engineer, Jan 2026: RL policy types and modern policy-gradient methods (TRPO, PPO, GAE) (PracHub)
seniortrade-offMLE RE PPO or an off-policy actor-critic such as SAC? How do you choose?
Choose by what is scarce: environment samples or engineering and wall-clock time.
PPO (on-policy). Uses each batch for a few epochs and then discards it. Sample hungry, but simple, robust to hyperparameters, works for discrete and continuous actions, and scales almost linearly with parallel environments. It is the default when a fast simulator exists (thousands of environments on a GPU) and for fine-tuning large policies where stability matters more than sample count.
SAC, TD3, DQN family (off-policy). Reuse every transition many times through a replay buffer, so they need often an order of magnitude fewer environment steps. SAC maximises reward plus entropy, \(J = \mathbb E[\sum_t r_t + \alpha\, \mathcal H(\pi(\cdot \mid s_t))]\), with twin critics and a tuned temperature. The price is the deadly triad: more moving parts, sensitivity to the update-to-data ratio, and value overestimation. They are the default when samples are expensive, as with real robots or slow simulators.
Other deciding factors:
- Existing logged or demonstration data can seed an off-policy buffer but not PPO.
- Very large or structured action spaces (token sequences) favour policy-gradient methods.
- A learned critic for long token sequences is hard, which is one reason language-model RL often uses policy-gradient methods with simple baselines.
State the choice as a hypothesis and check it with a small run of each on the real task.
Follow-ups
- Your simulator runs at 100 000 steps per second. Does sample efficiency still matter?
- What is the update-to-data ratio and what happens when it is too high?
seniorconceptMLE RE How do RL agents explore, and what do you do when the reward is so sparse that random exploration never finds it?
Exploration methods, roughly in order of sophistication:
- Undirected noise. \(\epsilon\)-greedy, Boltzmann sampling, Gaussian action noise, or an entropy bonus that keeps a stochastic policy from collapsing. Cheap, and enough when reward is dense.
- Optimism. Optimistic initial values, upper confidence bounds, count-based bonuses \(\propto 1/\sqrt{N(s)}\), with pseudo-counts or hashing for large state spaces.
- Posterior sampling. Act greedily under a sampled value function (bootstrapped ensembles approximate this); gives temporally consistent exploration.
- Intrinsic motivation. Reward prediction error or novelty, for example random network distillation. Prediction-error curiosity is attracted to irreducible noise (the “noisy TV” problem), which is why novelty measured on a fixed random target works better than forward-model error.
When the reward is too sparse for any of these, change the problem rather than the noise:
- Demonstrations, to seed the policy or the replay buffer.
- A curriculum from easy start states or short horizons, or resets to states near the goal.
- Potential-based shaping from a distance or progress measure.
- Hindsight relabelling for goal-conditioned tasks.
- Hierarchy or skills learned beforehand.
In products the constraint is usually safety and cost, not novelty: exploration is bounded to a small traffic share, to reversible actions, and logged with propensities so that it can be reused offline.
Follow-ups
- Why does an entropy bonus alone fail on a hard-exploration task?
- How would you explore safely on a physical system?
seniorconceptMLE RE What is offline RL, why does a standard off-policy algorithm fail on a fixed dataset, and what are the main fixes?
Offline RL learns a policy from a fixed log of transitions with no further interaction. It matters wherever exploration is costly or unsafe: recommendation logs, medical or industrial records, robot datasets.
Why naive off-policy learning fails. The Bellman target takes \(\max_{a'} Q(s', a')\) over all actions, including ones the dataset never contains. The network’s values there are arbitrary extrapolations, the max picks the largest errors, and bootstrapping spreads them. Online, the agent would try those actions and be corrected; offline, nothing corrects them. The learned policy then leaves the data distribution.
Families of fixes.
- Policy constraint: keep the policy close to the behaviour policy (BCQ, TD3+BC, a KL or behaviour-cloning term).
- Value pessimism: push down Q-values for actions outside the data (CQL) or subtract an uncertainty penalty from an ensemble.
- In-sample learning: never query unseen actions; IQL fits an expectile of the value from dataset actions only, then extracts a policy by advantage-weighted regression.
- Sequence modelling: condition a behaviour-cloning model on the return to go.
What a senior answer adds: how much the result depends on the data. With narrow expert data, behaviour cloning is a strong baseline and often wins; offline RL helps when the data is broad and suboptimal, so that good trajectories can be stitched from parts. Evaluation is the hard part, since off-policy evaluation is itself unreliable; plan a guarded online test.
Follow-ups
- How would you tell from the dataset alone whether offline RL can beat behaviour cloning?
- What changes when you may collect a small amount of online data afterwards?
seniordebuggingMLE RE Your RL agent’s return is flat after many hours of training. How do you debug it?
RL fails silently, so work from the cheapest certainty outwards.
- Environment and reward. Step it by hand or with a scripted policy. Can a known good policy get reward? Are observations in a sane range, is the reward scale reasonable (returns of order 1 to 100), are terminations and time limits reported correctly?
- A problem the code must solve. Run the same code on a small known task (a classic control problem or a shortened version of your task). If that fails, the bug is in the algorithm code, not in the difficulty of the task.
- Diagnostics instead of the return curve.
- Policy entropy: collapsed to zero early means premature convergence; never decreasing means the policy is not learning.
- Approximate KL and clip fraction per update: zero means the step is too small or advantages are zero; large means the step is too big.
- Value explained variance: near zero or negative means the critic is useless, so advantages are noise.
- Gradient norms and the advantage distribution.
- Usual culprits. Advantages not normalised, observations not normalised, truncation treated as termination, done flags off by one, old log-probabilities recomputed after the update, wrong action scaling or clipping, reward that is too sparse for the exploration used, a learning rate tuned on another task.
- Variance. Run at least three to five seeds before concluding anything; one flat seed is common.
Finally, watch episodes. Many “not learning” cases are an agent that learned an unintended behaviour the reward allows.
Follow-ups
- The return rises and then collapses. What does that suggest?
- Which of these diagnostics would you alert on in an automated training pipeline?
coretrade-offMLE AI RE A team wants to “use RL” for a product decision problem. How do you decide whether RL is the right tool?
Ask what structure the problem really has, and take the simplest formulation that fits.
- Supervised learning if the right action is known for past cases, or if the outcome of each action can be predicted and then optimised directly (predict, then choose).
- Contextual bandit if you choose an action, see a reward for that action only, and the action does not change what you see next. Most ranking, pricing and notification decisions are treated this way.
- Full RL only if actions have delayed consequences through the state: today’s action changes tomorrow’s options. Examples are control, games, multi-step agents, inventory and long-term user value.
- A solver if the objective and constraints are known and the uncertainty is small.
What full RL costs: far more data than supervised learning; a simulator or a safe way to explore; a reward that will be exploited wherever it differs from intent; evaluation that requires either online runs or unreliable off-policy estimates; and unstable training with seed variance.
So the bar is: sequential structure that a myopic policy demonstrably loses on, a measurable long-horizon objective, and either a faithful simulator or logged data with enough coverage plus a guarded online test. A strong answer proposes a baseline (a heuristic, a myopic model or a bandit) and states the gap RL would have to close to pay for itself.
Follow-ups
- How would you show that the myopic policy leaves value on the table before building anything?
- Where does fine-tuning a language model with a reward fit in this picture?
seniorderivationRE MLEasked at Anthropic, Google Explain importance sampling as it is used when a language model is fine-tuned with a policy-gradient method: what the ratio corrects, why its variance grows with sequence length, and what clipping does. Then name the bugs you would look for in a training step that computes these ratios.
What it corrects. Samples were generated by one policy, \(\mu\) (the model when the batch was sampled), and the gradient is wanted for another, \(\pi_\theta\) (the model after some updates). For any \(f\),
\[\mathbb{E}_{x \sim \pi_\theta}[f(x)] = \mathbb{E}_{x \sim \mu}\!\left[\frac{\pi_\theta(x)}{\mu(x)} f(x)\right],\]
provided \(\mu(x) > 0\) wherever \(\pi_\theta(x) > 0\). Reusing a batch for several gradient steps is exactly this situation.
Why variance explodes with length. For a sequence the ratio is a product over tokens, \(\prod_t \pi_\theta(x_t \mid x_{<t}) / \mu(x_t \mid x_{<t})\), so its log is a sum. If each token’s log-ratio has standard deviation \(\sigma\), the variance of the product grows like \(e^{T\sigma^2} - 1\). With \(\sigma = 0.1\): 0.11 at 10 tokens, 1.7 at 100, and about 22,000 at 1,000. The effective sample size, \((\sum w)^2 / \sum w^2\), falls to 37% of the batch at 100 tokens and to a few thousandths of a percent at 1,000: a handful of samples carry the whole estimate.
What practice does instead.
- Per-token ratios in a surrogate objective, not the full product. This is biased (it ignores how earlier tokens change the state distribution) and has bounded variance when the policies stay close.
- Clipping, as in PPO: \(\min\big(r_t A,\ \mathrm{clip}(r_t, 1-\epsilon, 1+\epsilon)\, A\big)\). When a change would improve the objective beyond the clip range, the gradient is zero; changes that make things worse are still penalised. It is a pessimistic bound, and it removes the incentive to move far from \(\mu\) on one batch.
- A KL penalty or early stop when the measured divergence from \(\mu\) exceeds a threshold, and few epochs per batch.
- Self-normalised weights (divide by \(\sum w\)): biased, much lower variance.
import torch
def clipped_pg_loss(new_logp, old_logp, adv, mask, clip=0.2):
"""new_logp, old_logp: (B, T) log-probs of the sampled tokens; adv: (B, 1); mask: (B, T) bool."""
ratio = torch.exp(new_logp - old_logp.detach()) # old is a constant
adv = adv.detach()
surr = torch.minimum(ratio * adv, ratio.clamp(1 - clip, 1 + clip) * adv)
mask = mask.to(surr.dtype)
return -(surr * mask).sum() / mask.sum().clamp_min(1)At ratio 1 its gradient equals the plain policy gradient, a useful unit test.
Bugs to look for.
old_logprecomputed from the current model, or not detached: the ratio is always 1 or carries gradient it should not.old_logpnot from the distribution that was actually sampled. If generation used a temperature or nucleus truncation, \(\mu\) is that modified distribution, and truncation also breaks the support condition.- Ratios from probabilities instead of log-probabilities: underflow on long sequences.
- Padding or prompt tokens included in the sum or the mean.
- Advantage with gradient attached, with the wrong sign, or normalised over the wrong group (across prompts when the baseline is per prompt).
- Dropout active when scoring, so “old” and “new” differ with identical weights.
- A mismatch between per-token ratios and a per-sequence clip, or the reverse.
Diagnostics to log every step: mean and maximum ratio, clip fraction, approximate KL to \(\mu\), and effective sample size. A clip fraction near zero means the update is too timid; near one, the batch is stale.
Follow-ups
- Why is the clipped objective asymmetric in the sign of the advantage?
- You want to reuse samples from three checkpoints ago. What would you need to store, and when is it hopeless?
- How does a per-prompt baseline change the variance, and does it introduce bias?
Reported in interviews (candidate reports on third-party sites, not verified)
Operations research and combinatorial optimization 4% of postings
- Formulate assignment, knapsack and scheduling problems as linear or integer programs
- Explain LP relaxation, branch and bound and what the optimality gap tells you
- Choose among an exact solver, a heuristic and a learned policy for a given latency and scale
- Combine a forecast with an optimiser and say where prediction error hurts the decision
coreconceptMLE AI Formulate assigning n tasks to n workers at minimum cost as an optimisation problem. When is it easy, and what makes it a hard integer program?
Variables \(x_{ij} \in \{0, 1\}\), 1 if worker \(i\) takes task \(j\), with cost \(c_{ij}\):
\[\min \sum_{i,j} c_{ij} x_{ij} \quad \text{s.t.} \quad \sum_j x_{ij} = 1\ \ \forall i, \qquad \sum_i x_{ij} = 1\ \ \forall j.\]
Why this one is easy. The constraint matrix is totally unimodular, so the linear relaxation (\(0 \le x_{ij} \le 1\)) has integral vertices and an LP solver returns a valid assignment. Specialised algorithms are faster still: the Hungarian algorithm in \(O(n^3)\), or min-cost flow.
What makes it hard. Side constraints break that structure: a worker’s capacity over several tasks measured in hours (generalised assignment), precedence or time windows (scheduling, routing), or fixed costs for using a resource. Then it is a mixed-integer program, NP-hard in general.
How solvers handle it. Branch and bound: solve the LP relaxation, which gives a lower bound; if a variable is fractional, branch on it and recurse, pruning branches whose bound is worse than the best integer solution found. Cutting planes tighten the relaxation. The solver reports the optimality gap between the best solution and the best bound, so you can stop at 1% with a guarantee.
Modelling skill is choosing a formulation with a tight relaxation and knowing the standard shapes: knapsack, set cover, flow, assignment, scheduling with big-M or time-indexed variables.
Follow-ups
- How do you model “at most 3 of these 10 tasks may run in parallel”?
- Your solver has not closed the gap after an hour. What are your options?
seniortrade-offMLE AI For a recurring combinatorial decision (matching, routing, scheduling), when do you use an exact solver, a heuristic, or a learned policy?
Decide by problem size, time budget, how often the problem structure changes and how much a suboptimal decision costs.
Exact solver (LP, MIP, constraint programming). Use when the objective and constraints can be written down, the instance solves within the time budget, and guarantees or auditability matter. Strengths: an optimality gap, hard constraints respected by construction, and a new business rule is one more constraint. It is the right default up to surprisingly large sizes for LPs and well-structured MIPs.
Heuristics and metaheuristics (greedy with local search, large-neighbourhood search, simulated annealing). Use when instances are too large or the deadline is milliseconds to seconds. No guarantee, but predictable runtime and usually within a few percent on routing-type problems. Often combined with a solver for subproblems.
Learned policy (RL or imitation of a solver). Worth it when the same distribution of instances recurs millions of times, the decision must be made in milliseconds, and either the objective is hard to write down (long-term effects, stochastic arrivals) or a solver is too slow. Costs: no feasibility guarantee without a repair step, poor generalisation to changed constraints, and training infrastructure.
Common hybrids: ML predicts the uncertain inputs (demand, travel time) and a solver decides; a learned model warm-starts or guides branching; RL sets a few parameters of a solver-based policy. A senior answer starts from the solver baseline and asks what measured gap or latency constraint justifies anything more complex.
Follow-ups
- How would you guarantee feasibility for a learned policy’s output?
- The business adds a new hard constraint every month. How does that change your choice?
seniordesignMLE AI Design the decision system that assigns incoming delivery orders to couriers in real time. Where does ML end and optimisation begin?
Objective and constraints. Minimise expected delivery lateness and courier cost, subject to capacity, pickup-before-dropoff, maximum detour and fairness limits. Agree on one scalar objective with explicit weights, since this is where the product trade-off lives.
Predict. ML supplies the uncertain inputs: travel time between points, food preparation or pickup readiness, courier acceptance probability, and demand per zone for the next 15 to 60 minutes. Calibration matters more than ranking, because the optimiser consumes the numbers.
Decide. Batch orders in a rolling window (for example every 10 to 30 seconds) and solve a matching between open orders (or bundles) and couriers. With one order per courier it is an assignment problem solved exactly in milliseconds; bundling makes it a routing problem handled by candidate generation plus a MIP or local search under a time limit. Waiting longer improves the match and costs latency, so the window is a tuned parameter.
Look ahead. Pure myopic matching ignores future orders. Add the value of courier position, estimated from the demand forecast or learned as a value function over (zone, time), to the matching cost. This is where RL-style thinking pays without replacing the solver.
Evaluate. A simulator replaying historical days for offline iteration, then switchback experiments by zone and time, because orders and couriers interfere and a user-level A/B test is biased.
Failure handling. A greedy fallback when the solver times out, and monitoring of forecast error because decision quality degrades with it.
Follow-ups
- Why can a more accurate travel-time model make decisions worse?
- How would you train the forecasts for decision quality instead of prediction error?
Planning, search and sequential decision making 4% of postings
- Walk through the four phases of Monte Carlo tree search and write the UCT rule
- Explain how AlphaZero-style search uses a policy prior and a value network
- Compare model-free RL, Dyna-style methods and model-predictive control under model error
- State when A* is optimal and how beam search trades optimality for cost
seniorconceptMLE RE Explain Monte Carlo tree search and how AlphaZero-style methods combine it with neural networks.
MCTS builds a search tree incrementally, spending simulations where they are most informative. Each simulation has four phases:
- Selection. From the root, descend by a rule that balances value and uncertainty. UCT picks \(\arg\max_a\ \bar Q(s, a) + c \sqrt{\ln N(s) / N(s, a)}\).
- Expansion. Add a child for an untried action at the leaf.
- Evaluation. Estimate the leaf’s value, classically by a random rollout to the end.
- Backup. Update visit counts and mean values along the path.
After the budget is spent, act by the root’s visit counts. It is an anytime algorithm and needs only a simulator, not a heuristic.
AlphaZero replaces the hand-made parts with a network \(f_\theta(s) = (p, v)\):
- The value head \(v\) replaces rollouts at the leaf.
- The policy head gives a prior that focuses selection (PUCT): \(\arg\max_a\ Q(s, a) + c\, P(s, a)\, \sqrt{N(s)} / (1 + N(s, a))\).
- Training closes the loop: self-play games are generated with search, the policy is trained toward the search’s visit distribution and the value toward the game outcome. Search is a policy-improvement operator and the network distils it.
MuZero additionally learns the model, searching in a latent space.
Limits: it needs a model that can be stepped from arbitrary states, the cost per move is hundreds of network evaluations, and plain MCTS handles large branching factors, stochasticity and hidden information poorly without extensions.
Follow-ups
- Why act by visit count and not by the highest mean value?
- How would you use search at inference time with a language model, and what plays the role of the value function?
seniortrade-offMLE RE Model-based or model-free RL? What does a learned model buy you and where does it fail?
Model-free methods learn a policy or value function directly from experience. They are simple and asymptotically strong but need many samples, because every bit of knowledge about the dynamics must be rediscovered through reward.
Model-based methods learn \(\hat P(s' \mid s, a)\) and \(\hat r\) and use them in one of three ways:
- Planning at decision time: model-predictive control. Sample or optimise action sequences under the model (random shooting, the cross-entropy method), execute the first action, replan.
- Generating training data: Dyna-style methods mix real transitions with short model rollouts to train a model-free learner.
- Learning in imagination: train the policy entirely inside a latent world model.
What it buys: sample efficiency (often an order of magnitude), reuse of the model when the reward changes, and constraint handling at planning time.
Where it fails: compounding model error. A one-step error of \(\epsilon\) grows with rollout length, and a planner actively seeks the states where the model is wrongly optimistic. Mitigations are short rollouts branched from real states, ensembles with a penalty on disagreement, latent models trained on multi-step prediction, and replanning at every step so errors do not accumulate in execution.
Rules of thumb: prefer model-based when real samples are expensive and the dynamics are smooth and learnable (many robotics and process-control problems); prefer model-free when a fast, exact simulator exists or the dynamics are harder to model than the policy is to learn.
Follow-ups
- Why does a planner exploit model error more than a random policy would?
- A perfect simulator is available. Is there still a reason to learn a model?
coreconceptMLE AI RE Compare greedy search, beam search and A*. When is each optimal, and where do they show up in ML systems?
All three search a graph of partial solutions; they differ in what they keep.
- Greedy keeps one candidate and extends it by the locally best step. \(O(d)\) expansions for depth \(d\), no optimality guarantee.
- Beam search keeps the best \(k\) partial candidates at each depth. Cost \(O(k\, b\, d)\) for branching factor \(b\). Not optimal, since the best full solution can fall off the beam early, and not monotone in \(k\) for the downstream metric: in sequence generation a wider beam finds higher-probability outputs that are often shorter and blander, which is why length normalisation is needed.
- A* expands the node with the lowest \(f(n) = g(n) + h(n)\), cost so far plus a heuristic estimate of cost to go. It returns an optimal path if \(h\) is admissible (never overestimates); with a consistent heuristic no node is re-expanded. With \(h = 0\) it is Dijkstra. The better the heuristic, the fewer expansions; memory is the usual limit.
Where they appear:
- Decoding in sequence models and constrained generation (beam search over tokens or over valid identifiers).
- Motion and route planning (A* and its variants on grids and road graphs).
- Approximate nearest-neighbour search on graphs is a best-first search with a bounded candidate list.
- Agents that plan over actions: best-first or beam search over partial plans, with a learned value as the heuristic.
The general pattern: a learned model supplies the scores or heuristic, and the search supplies lookahead and hard constraints the model cannot guarantee.
Follow-ups
- Give a case where beam width 5 returns a worse result than greedy.
- What makes a heuristic admissible but useless?
Reward design and credit assignment 2% of postings
- State potential-based shaping and prove it preserves the optimal policy
- Give examples of specification gaming and a process that catches it before deployment
- Explain credit assignment with n-step returns, eligibility traces and hindsight relabelling
- Relate the discount factor to an effective horizon and to the control frequency
seniorderivationMLE RE What is potential-based reward shaping, and why does it leave the optimal policy unchanged?
Shaping adds a term \(F\) to the reward to give the agent denser feedback. Arbitrary shaping changes what is optimal: reward “progress” and the agent may learn to oscillate to collect it repeatedly. Potential-based shaping (Ng, Harada and Russell, 1999) restricts \(F\) to the difference of a potential \(\Phi\) over states:
\[F(s, a, s') = \gamma\, \Phi(s') - \Phi(s).\]
Why it is safe. Along any trajectory the shaping terms telescope:
\[\sum_{t \ge 0} \gamma^t \big(\gamma \Phi(s_{t+1}) - \Phi(s_t)\big) = -\Phi(s_0),\]
assuming the discounted potential vanishes at the end (bounded \(\Phi\) with \(\gamma < 1\), or \(\Phi = 0\) at terminal states). So every policy’s return from \(s_0\) shifts by the same constant. Equivalently \(Q'^*(s, a) = Q^*(s, a) - \Phi(s)\): the shift does not depend on the action, so the \(\arg\max\) is unchanged. The result is also necessary in the sense that, without knowledge of the dynamics, only potential-based shaping guarantees invariance.
What makes a good potential. The ideal is \(\Phi = V^*\), which makes the one-step greedy action optimal; in practice use a rough estimate of progress, such as negative distance to the goal. Any cycle in state space collects zero net shaping, which is exactly what prevents the oscillation exploit.
Caveats: the terminal potential must be zero in episodic tasks, and shaping changes learning speed and exploration, so a bad potential can still slow learning even though the optimum is preserved.
Follow-ups
- Give a shaping reward that is not potential-based and the behaviour it produces.
- How does shaping interact with a learned value function’s initialisation?
seniordesignMLE AI REasked at Google Agents exploit their reward. How do you design a reward, and what process catches specification gaming before it ships?
Treat the reward as a specification that an optimiser will satisfy literally. Wherever it differs from what you want, a strong enough learner finds the difference: collecting a progress bonus in a loop, exploiting a simulator bug, satisfying a test by special-casing it, or maximising a learned judge’s score with text the judge likes rather than a correct answer.
Design principles.
- Reward the outcome, not the proxy for it. Prefer a sparse, verifiable task result and add density through potential-based shaping, not through extra terms.
- Make constraints explicit as penalties or hard terminations (safety, cost, time), and check that no behaviour earns more by violating them.
- Keep the reward bounded and on a known scale; unbounded terms dominate.
- If the reward is a learned model, assume it is exploitable: use ensembles, cap its contribution, refresh it on policy outputs and hold out a separate judge for evaluation only.
Process.
- Before training, ask what the laziest policy that scores well would do, and red-team the reward on paper.
- During training, watch episodes at every checkpoint and track metrics that are not in the reward (task success by an independent check, constraint violations, diversity). Divergence between reward and those metrics is the signal.
- Evaluate on held-out tasks and with a grader the policy was never trained against.
- Keep the reward function versioned with the run, so a change in behaviour can be traced.
A reward that needed many patches is usually the wrong formulation; step back to the outcome.
Follow-ups
- Reward rises steadily while held-out task success is flat. What do you check?
- How does this apply when the reward is another model’s judgement?
Reported in interviews (candidate reports on third-party sites, not verified)
- Google, Machine Learning Engineer, Aug 2026: Reward hacking in LLM post-training and how to detect and prevent it (PracHub)
seniorconceptMLE RE What is the credit assignment problem, and which mechanisms address it?
Credit assignment asks which of many earlier actions caused a reward that arrives later. With a sparse terminal reward and horizon \(T\), a Monte Carlo policy gradient multiplies every action’s log-probability by the same noisy return, so the signal for any one action is weak and the variance grows with \(T\).
Mechanisms:
- Value functions. A critic turns a delayed reward into an immediate signal: the TD error \(r + \gamma V(s') - V(s)\) says whether a step made things better or worse than expected. This is the main tool.
- n-step returns and eligibility traces. TD(\(\lambda\)) and GAE spread a TD error back over recent steps with decaying weight, trading bias for variance.
- Baselines and advantages. Subtracting what was expected isolates the effect of the chosen action.
- Hindsight relabelling. In goal-conditioned tasks, relabel a failed trajectory with the goal it actually reached, so every trajectory carries signal.
- Shaping and subgoals. Potential-based shaping or hierarchical decomposition shortens the distance between an action and its feedback.
- Structural credit assignment. Across agents or modules, counterfactual baselines (what would the team reward have been without this agent’s action) separate contributions.
For long token sequences with one end-of-episode score, the same problem appears: all tokens share one reward. Per-step critics are hard to train there, so practice leans on group or batch baselines, many samples per prompt and shorter effective horizons.
Follow-ups
- Why does a lower discount factor make credit assignment easier and the solution worse?
- How would you assign credit among the steps of a multi-step agent that failed its task?
coretrade-offMLE RE What does the discount factor do, and how do you choose it?
\(\gamma\) has two roles that are often conflated.
- Problem definition. It encodes how much the future matters. Rewards \(k\) steps ahead are weighted by \(\gamma^k\), giving an effective horizon of about \(1 / (1 - \gamma)\) steps: 100 steps at \(\gamma = 0.99\), 1000 at \(0.999\).
- Algorithmic knob. A lower \(\gamma\) shortens the horizon the estimator must cover, which lowers the variance of returns and speeds value propagation, at the price of bias toward myopic behaviour. Many tasks whose true objective is undiscounted are trained with \(\gamma < 1\) for this reason.
Choosing it:
- Work in time, not steps. If the control frequency doubles, the same horizon in seconds needs \(\gamma\) closer to 1: \(\gamma_{\text{new}} = \gamma_{\text{old}}^{1/2}\). Forgetting this is a common cause of a policy that became short-sighted after a change of step rate.
- The horizon must cover the delay between the decisive action and its reward. If the payoff arrives 500 steps later, \(\gamma = 0.99\) weights it by \(0.99^{500} \approx 0.007\).
- Very high \(\gamma\) makes values large (\(r_{\max} / (1 - \gamma)\)) and learning slow and unstable; normalise returns or value targets.
For episodic tasks with a clear terminal outcome, \(\gamma\) near 1 with GAE’s \(\lambda\) controlling variance is usually better than a low \(\gamma\). For continuing tasks, the average-reward formulation avoids the choice altogether.
Follow-ups
- What happens to the optimal policy when \(\gamma\) is 0?
- Why can a time-limit bug look like a discount problem?
Imitation learning and behaviour cloning 1% of postings
- Explain why behaviour cloning error compounds over the horizon and how DAgger removes the quadratic term
- Distinguish behaviour cloning, inverse RL and adversarial imitation by what each needs and returns
- Handle multimodal and suboptimal demonstrations
- Evaluate an imitation policy in closed loop instead of by held-out action error
coreconceptMLE RE Why does behaviour cloning degrade over long horizons, and how does DAgger fix it?
Behaviour cloning is supervised learning of \(\pi(a \mid s)\) on expert state-action pairs. Training states come from the expert’s distribution, but at test time the states come from the learner’s own actions. A small mistake moves the agent to a state the expert rarely visited, where the policy is worse, which causes a larger mistake. This is covariate shift created by the policy itself.
The standard result (Ross and Bagnell): if the policy errs with probability \(\epsilon\) per step on the expert’s distribution, the expected cost over horizon \(T\) can grow as \(O(\epsilon T^2)\), not \(O(\epsilon T)\), because after the first error the agent may be off-distribution for the rest of the episode.
DAgger closes the loop: run the current policy, ask the expert for the correct action in the states the policy visited, aggregate those labels into the dataset and retrain. The training distribution converges to the learner’s own state distribution, and the bound becomes \(O(\epsilon T)\).
Its cost is an expert who can be queried on arbitrary states, which is easy for a scripted or planning expert and awkward for humans. Alternatives that need no queries: inject noise during demonstration collection so the data contains recoveries, augment with synthetic perturbations and corrective labels, predict chunks of actions to shorten the effective horizon, or fine-tune with RL after cloning.
Follow-ups
- Held-out action error is low but closed-loop success is poor. Why?
- How would you collect DAgger labels from a human driver safely?
seniorconceptMLE RE Compare behaviour cloning, inverse RL and adversarial imitation. What does each need and when would you go beyond behaviour cloning?
| Method | Learns | Needs | Weakness |
|---|---|---|---|
| Behaviour cloning | Policy by supervised learning | Demonstrations only | Compounding error off the data |
| Inverse RL | A reward that explains the expert, then a policy | Demonstrations plus environment interaction or a model | Expensive (RL in the inner loop); reward is not unique |
| Adversarial imitation (GAIL) | Policy whose state-action distribution matches the expert’s | Demonstrations plus interaction | GAN-style instability; sample hungry |
Inverse RL is ill-posed: many rewards, including a constant, make the expert optimal. Maximum-entropy IRL resolves this by choosing the reward under which the expert’s trajectories are exponentially more likely the higher their return. Its advantage is that a reward transfers to new dynamics or embodiments where a cloned policy does not.
GAIL skips the explicit reward: a discriminator separates expert from policy state-action pairs and its output is used as the reward for a policy-gradient learner. It matches the occupancy measure and so corrects compounding error, at the price of environment interaction.
Go beyond behaviour cloning when: the horizon is long and recoveries are missing from the data; the demonstrations are suboptimal and you want to exceed them (offline RL or advantage-weighted cloning with a reward); or the dynamics at deployment differ from the demonstrations. Stay with cloning when data is plentiful, covers recoveries and interaction is expensive. That describes most large-scale robot and driving policies today.
Follow-ups
- Why is the constant reward a solution to inverse RL, and how does the maximum-entropy formulation rule it out?
- What does advantage-weighted regression do with suboptimal demonstrations?
seniordesignMLE RE You have a large log of human operators doing a multi-step task and a simulator of medium fidelity. Design the pipeline that turns this into a deployable policy.
1. Data. Segment the log into episodes with outcomes, filter out failed or idle segments, and check coverage: which states and recoveries are present. Split by operator and by time so the evaluation does not leak.
2. Clone first. Train a behaviour-cloning policy. Human data is multimodal (two valid ways to do the same step), and a regression head averages the modes into an invalid action, so use a categorical head over discretised actions, a mixture, or a generative action head. Give the policy enough history to be Markov, but watch for causal confusion: with history the model can learn to copy the previous action instead of reading the observation.
3. Evaluate in closed loop. Held-out action error does not predict task success. Use the simulator for success rate, time to complete and safety violations, with scenario sets for rare cases.
4. Improve past the demonstrations. Fine-tune with RL in the simulator, starting from the cloned policy and keeping a cloning or KL term so the policy stays near human-like behaviour where the simulator is wrong. Randomise simulator parameters to cover the fidelity gap. Use a sparse task reward plus constraints rather than an elaborate shaped reward.
5. Deploy with guards. Shadow mode against operators, then assisted mode with human takeover. Log interventions; they are DAgger labels for the next round.
The main risks to name: simulator exploits, loss of human-like safety margins during fine-tuning, and evaluation scenarios that under-represent the tail.
Follow-ups
- How do you decide the weight of the cloning term during RL fine-tuning?
- Which metric would stop a rollout?