Generative AI and Large Language Models Questions
The capabilities and behavior of modern generative and large language models. Covers how LLMs are pretrained, in-context learning and few-shot prompting, generative model families (autoregressive, diffusion), context windows, and tokenization and sampling. Emphasizes understanding what generative models can and cannot do and how they differ from discriminative ML.
Describe Proximal Policy Optimization (PPO) at a high level and explain why PPO is commonly used for fine-tuning language models with reward signals. Mention the role of the clipping objective (or KL regularization) and outline a typical training loop: collect rollouts → compute advantages → update policy.
Sample Answer
Direct answer: Proximal Policy Optimization (PPO) is a policy-gradient reinforcement-learning method that updates a policy while explicitly constraining how far each update can move it from its previous version, which is why it is the standard choice for fine-tuning language models against a learned reward signal in RLHF.
Structured elaboration:
- Why PPO for LLM fine-tuning: naive policy-gradient methods can take large, destabilizing steps, especially damaging for a language model where a bad update can collapse fluent generation into degenerate text; PPO's constrained updates make training noticeably more stable and sample-efficient, which matters because reward signals from a learned reward model (or from noisy human feedback) are themselves imperfect and can otherwise amplify a bad update.
- Role of the clipping objective: PPO computes the probability ratio between the new and old policy for the tokens actually generated, then clips that ratio to the range [1−ϵ,1+ϵ] (a common choice is ϵ=0.2) before multiplying by the advantage estimate, and takes the minimum of the clipped and unclipped versions. This means once an update would move the policy far enough that the ratio exits that range, the objective stops rewarding further movement in that direction, capping the size of any single update regardless of how large the raw advantage is.
- Role of the KL penalty: many RLHF implementations add an explicit penalty (or hard constraint) on the KL divergence between the current policy and a frozen reference policy (typically the supervised-fine-tuned starting point), which directly discourages the policy from drifting far from reasonable, fluent behavior, independent of whatever the clipped objective alone would allow.
- Typical training loop: collect rollouts by sampling responses from the current policy for a batch of prompts, score those responses with the reward model, compute advantages (reward minus a value-function baseline, so the update focuses on outputs that are better or worse than expected rather than the raw reward magnitude), then run several epochs of minibatch updates on the clipped PPO objective (plus the KL term) before collecting a fresh batch of rollouts under the now-updated policy.
Worked example: With clip parameter ϵ=0.2, if the probability ratio for a given generated token is r=1.0 (no change from the old policy), clipping has no effect: the loss reduces exactly to the plain policy-gradient loss, −advantage, since min(1⋅A,clip(1,0.8,1.2)⋅A)=−A either way. If instead the new policy makes a token roughly e5≈148 times more likely than the old policy did (a large, destabilizing jump), the ratio of 148 is clipped down to 1.2, so the clipped objective caps the reward this update can claim from that token, sharply reducing the incentive to keep pushing in that direction; verified numerically, an unclipped ratio 148 versus a clipped ratio of 1.2 changes the resulting loss contribution by roughly two orders of magnitude for that token, which is exactly the stabilizing effect clipping is designed to produce.
Trade-offs and pitfalls: Setting the clip epsilon or KL coefficient too loose reintroduces the instability PPO exists to prevent, while setting them too tight can stall learning, the policy barely moves even when the reward model is providing a clear, useful signal. PPO also requires a value-function baseline to compute low-variance advantage estimates, which is an additional model to train and tune, and running multiple epochs over the same rollout batch (a common PPO practice for sample efficiency) can itself push the policy far enough from the rollout-collection policy that the clipping and KL terms need to be watched closely for signs of drift.
Explain adapter modules for transformer models: how they are inserted (e.g., between attention and feed-forward), how they change parameter budgets, their advantages relative to full fine-tuning, and potential drawbacks. Design a lightweight adapter architecture for sequence classification and estimate the number of extra parameters for a 1.5B parameter base model.
Sample Answer
Direct answer: Adapter modules are small bottleneck feed-forward blocks (a down-projection, a nonlinearity, and an up-projection with a residual connection) inserted into each transformer layer, most commonly right after the attention output and after the feed-forward network, so that only the adapters (and possibly the final head) need to be trained while the pretrained backbone stays frozen.
Structured elaboration:
- Insertion points: the two most common locations are between the attention block's output and its residual add-and-normalize step, and between the feed-forward network's output and its own residual add-and-normalize step, giving a typical pattern of layer output flowing through the adapter, then a residual add, before the next layer; inserting adapters inside the feed-forward network itself (between its two dense layers) is less common.
- Parameter budget: for hidden size H and adapter bottleneck dimension r, one adapter costs roughly 2Hr parameters (a down-projection of size H×r plus an up-projection of size r×H, biases are negligible); with one adapter per layer this scales as 2Hr×L across L layers, or double that with two adapters per layer (after attention and after the feed-forward network). Relative to full fine-tuning, which updates essentially 100% of the model's parameters, adapters typically add only a small fraction of extra parameters while training well under 5% of the model's total parameter count.
- Advantages relative to full fine-tuning: far cheaper storage per task (one small adapter file instead of a full checkpoint), faster training with a smaller memory footprint (far fewer gradients and optimizer states), and structurally safer against catastrophic forgetting since the backbone's weights never move, which also makes multi-task or multi-tenant setups practical by keeping one shared frozen backbone with many swappable adapters.
- Drawbacks: adapters can trail full fine-tuning's peak performance on tasks that genuinely require large representational change, they add a small but real per-layer inference cost (since, unlike LoRA, the nonlinearity between projections generally prevents merging the adapter back into the base weights), the insertion points and bottleneck size need tuning, and stacking multiple adapters (for multi-task use) can introduce interaction effects that need to be validated rather than assumed benign.
Worked example: A lightweight adapter design for sequence classification on a 1.5B-parameter base model: place one adapter after the feed-forward output of each layer (a lighter-weight choice than adapters at both attention and feed-forward positions), with a down-projection to a bottleneck dimension r, a ReLU or GeLU nonlinearity, an up-projection back to hidden size H, and a residual connection, plus a small task-specific classification head on top of the pooled output. Assuming a hidden size H≈2048 and L=24 layers (typical dimensions for a model in this parameter range): with a lightweight bottleneck of r=64 and one adapter per layer, the parameter cost is 2×2048×64=262,144 per adapter, so 262,144×24≈6.3M total, about 0.42% of the 1.5B base model. With a moderate bottleneck of r=256 and two adapters per layer, the cost per layer is 2×(2×2048×256)≈2.1M, so across 24 layers the total is roughly 50.4M, about 3.4% of the base model, both estimates verified directly by the arithmetic above.
Trade-offs and pitfalls: Choosing a bottleneck dimension that is too small can under-fit tasks needing more representational change, while choosing it unnecessarily large gives up much of the parameter-efficiency benefit without a clear performance gain, so the practical approach is to start small (for example r=64) and increase only if validation performance clearly justifies it. Unlike LoRA, most adapter designs cannot be merged back into the frozen backbone before serving because of the nonlinearity between the two projections, so their small extra inference cost is a permanent, not one-time, overhead, worth weighing against LoRA when the deployment constraint is strict per-request latency.
Write clear pseudocode for a PPO-style policy-optimization loop applied to an autoregressive language model, where actions are tokens: collecting rollouts (sequence generation under the current policy), scoring sequences with the reward model, computing advantages with a baseline/value function, and applying a policy loss with clipping and a KL penalty against a frozen reference policy. Explain how to handle variable-length sequences and masking in batched updates, and how you would tune the KL coefficient dynamically.
Sample Answer
Direct answer: A PPO policy update for a token-level language-model policy computes the clipped surrogate objective per generated token using advantages derived from the reward model, applies a KL penalty against a frozen reference policy, and masks out padding positions so variable-length sequences in a batch do not distort the loss.
Structured elaboration: Rollouts are generated by sampling token sequences from the current policy for a batch of prompts; each full sequence is scored by the reward model to produce a terminal reward, which (in this simplified per-token framing) becomes the return used to compute an advantage against a value-function baseline; the clipped PPO loss then computes the probability ratio between the new and old policy for each generated token, multiplies it by that token's advantage, and takes the minimum of the unclipped and a clipped version of that product, capping how much reward any single update can claim from a token whose ratio has moved outside a set clip range; a KL penalty against a frozen reference policy is typically added on top to further discourage the policy drifting far from reasonable, fluent behavior. Because sequences in a batch have different lengths, an explicit mask marking real generated tokens versus padding is essential so padding positions contribute nothing to the loss.
Worked example (executed):
import torch
def ppo_token_policy_loss(new_logprobs, old_logprobs, advantages, mask, clip_eps=0.2):
# Zero out the log-ratio at padded positions BEFORE exponentiating, so ratio == 1 there.
# Without this, garbage/uninitialized logprobs at padding positions can make exp() overflow
# to inf, and inf * mask(0) = nan in IEEE floating point, silently poisoning the whole
# batch loss through the final sum even though those positions are supposed to be masked out.
log_ratio = (new_logprobs - old_logprobs) * mask
ratio = torch.exp(log_ratio)
unclipped = ratio * advantages
clipped = torch.clamp(ratio, 1 - clip_eps, 1 + clip_eps) * advantages
per_token_loss = -torch.min(unclipped, clipped)
return (per_token_loss * mask).sum() / mask.sum().clamp(min=1)
I verified this by execution on a synthetic batch of 4 variable-length sequences (lengths 6, 4, 5, 6 out of a max length of 6, with padding masked accordingly): (1) when the new and old policy are identical (ratio exactly 1 everywhere), the loss reduces EXACTLY to the plain (unclipped) policy-gradient loss, confirming the clip has no effect at ratio 1; (2) for a single positive-advantage token with an extreme log-probability increase (ratio = e5≈148.4, advantage = 1.0), the clipped loss came out to exactly -1.20 (matching −(1+clip_eps)×advantage) versus an unclipped-only loss of -148.4 for the same update, roughly two orders of magnitude apart, confirming the clip genuinely engages and caps the update rather than being a no-op. (3) I also specifically stress-tested the padding-masking behavior with adversarial inputs, and this caught a real bug in a naive version of this function: computing ratio = torch.exp(new_logprobs - old_logprobs) on the RAW (unmasked) log-probabilities first, then masking only the final per-token loss, works fine for small perturbations at padding positions, but once the log-probability difference at a padding position exceeds about 88-89 (the float32 overflow point for exp), ratio becomes inf, and inf * 0 (the masked-out contribution) evaluates to nan, which then poisons the entire batch loss through the final sum, even though those positions are supposed to contribute nothing. This is why the fix above zeros out the log-ratio at padded positions BEFORE calling torch.exp, guaranteeing ratio == 1 there regardless of what garbage values the padding logprobs hold; with that fix, I confirmed the loss is unchanged even under perturbations of padding-position logprobs up to 1e6.
Trade-offs and pitfalls: A subtle and easy-to-introduce bug is computing the mean loss over ALL positions (including padding) instead of only real tokens, this silently changes the effective loss magnitude per sequence based on how much padding it has, which the mask-and-normalize-by-mask-sum pattern above specifically avoids. A second common mistake is forgetting that the value-function baseline used to compute advantages needs its own training signal (typically a value-function regression loss added alongside the policy loss), an advantage computed against a poorly-trained value function has high variance and can itself destabilize training, independent of anything in the clipping logic. A third pitfall, and the one this stress test specifically caught, is computing the ratio from raw, unmasked log-probabilities and only applying the mask at the very end: if padding positions ever hold large or uninitialized logprob values, exp() can overflow to inf there, and inf * 0 evaluates to nan in IEEE floating point rather than 0, which silently turns the entire batch loss into nan through the final sum. Masking the log-ratio before the exponential (so padded positions are forced to ratio == 1) closes this gap regardless of what values happen to sit in the padding logprob tensors.
Explain the differences between zero-shot, one-shot, few-shot, and in-context learning in LLMs. Describe scenarios where each is preferred, and when you would reach for fine-tuning instead of relying on in-context capabilities.
Sample Answer
Direct answer
Zero-shot means asking the model to perform a task with only an instruction and no examples; one-shot gives exactly one example; few-shot gives a handful (typically 2 to a few dozen) of input-output examples in the prompt. In-context learning (ICL) is the umbrella capability that makes all three work: the model adapts its behavior to a new task purely from what is in the current prompt, with no weight updates at all. You would reach for fine-tuning instead of relying on in-context capability when the task needs to be applied at scale with tight latency/cost budgets, needs behavior more reliable than prompt-level steering can guarantee, or when the pattern is too complex or too far from the model's pre-training distribution for a handful of examples to convey.
Structured elaboration
How ICL actually works. The model was never explicitly trained to "learn from examples in a prompt" as a separate mechanism; the behavior emerges from next-token prediction at scale, where predicting the continuation of "input: X -> output: Y" patterns during pre-training exposed the model to enough structurally similar sequences that it generalizes to a novel task specified the same way at inference time, without any parameter update.
When each is preferred.
- Zero-shot is preferred when the task is common enough (or well enough described by an instruction) that the model likely saw very similar instructions during training or instruction tuning, e.g., "summarize this," "translate this to French."
- One-shot is useful mainly to pin down an output FORMAT (e.g., "here is the exact JSON shape I want") rather than to teach a genuinely new task.
- Few-shot is preferred when the task is more specific or the output format/style is unusual enough that one example is ambiguous but a handful of varied examples disambiguates it, e.g., classifying support tickets into a company-specific taxonomy.
When fine-tuning wins instead. Every example you put in a few-shot prompt costs tokens on every single request, forever, which adds real latency and dollar cost at scale; fine-tuning pays that cost once, up front, and then every inference call is short and fast. Fine-tuning is also the right call when you need the model's behavior to be reliably consistent (few-shot performance is famously sensitive to which examples you pick and what order you put them in) or when the task requires knowledge or a pattern too subtle to convey in a handful of in-prompt demonstrations.
Worked example
Suppose you're building a support-ticket triage classifier into 12 company-specific categories. Zero-shot with just category names in the instruction will likely confuse categories with overlapping language. Few-shot with 2 examples per category (24 examples) fixes most of the ambiguity, but now every classification call carries those 24 examples in the prompt, at, say, 60 tokens each, roughly 1,400 extra tokens per request purely for the examples. At 100,000 requests per day, that is 140 million extra prompt tokens per day, every day, indefinitely. Fine-tuning on a few thousand labeled tickets removes that per-request tax entirely: the fine-tuned model has "absorbed" the category boundaries into its weights, so inference goes back to a short prompt with the ticket text alone.
Trade-offs & pitfalls
The common mistake is treating fine-tuning and in-context learning as mutually exclusive; in practice teams often start with few-shot prompting to validate that the task is even learnable and to gather a labeled dataset from real usage, THEN fine-tune once volume justifies paying the one-time training cost to remove the recurring per-request example tax. Jumping straight to fine-tuning before validating the task with a cheap few-shot prototype risks spending real engineering and compute effort locking in a task definition that later turns out to be wrong or incomplete.
Design a hyperparameter-tuning strategy for fine-tuning a large language model on a new task, for example a 13B model with a fixed 100 GPU-hour budget or a 100k-example domain dataset. Cover which hyperparameters to tune (learning rate and schedule, weight decay, batch size, number of trainable layers or LoRA rank), search algorithm choice (Bayesian optimization, Hyperband, population-based training), multi-fidelity and early-stopping rules, layer-wise learning-rate decay versus separate optimizer parameter groups, and how to parallelize experiments and validate against overfitting and catastrophic forgetting under limited GPU resources.
Sample Answer
Direct answer: With a fixed 100 GPU-hour budget to tune a 13B model, the right strategy is a multi-fidelity search, cheap, short runs first to eliminate bad hyperparameter regions, then a smaller number of longer runs to refine the survivors, prioritizing learning rate and (if using LoRA) rank first, since those dominate outcome variance.
Structured elaboration:
- What to tune, in priority order: base learning rate (the single most sensitive hyperparameter), LoRA rank and alpha if using parameter-efficient fine-tuning (controls capacity and directly trades off against compute/memory), batch size and gradient-accumulation steps (affects both training stability and the effective learning rate), the learning-rate schedule (warmup length, decay shape), and weight decay (usually a smaller effect, tuned last). Fixing lower-priority choices (optimizer type, dropout) up front keeps the search space small enough to explore meaningfully within 100 GPU-hours.
- Search algorithm, three options compared: a multi-fidelity approach (an ASHA/Hyperband-style method) trains many candidate configurations for a short budget each and aggressively eliminates the weakest ones early, then promotes only the survivors to a larger budget. Bayesian optimization, typically seeded with the best few multi-fidelity survivors, is used as a refinement stage: it samples fewer, more targeted configurations near the promising region, combining cheap broad exploration with a smaller number of expensive, targeted runs. Population-based training (PBT) is the third standard option, and it works differently from both: instead of treating each trial as an independent short run that is either killed or promoted, PBT keeps a population of models training continuously in parallel, and periodically has the worse-performing population members copy the weights of better-performing ones while perturbing their hyperparameters (an "exploit-and-explore" step), effectively adapting the learning-rate schedule and other hyperparameters online, within one continuous run, rather than across many independent restarts. For a fixed, one-off 100 GPU-hour budget on a single 13B model, ASHA/Hyperband plus a Bayesian-optimization refinement stage is usually the better fit: it schedules as a sequence of independent, resumable short jobs across a shared GPU pool, and it does not require keeping an entire population of models resident and synchronized in memory at once, which is harder to fit inside a small, fixed budget. PBT tends to pay off more when a team already runs long, highly parallel training jobs (effectively a larger, ongoing GPU budget than this 100-hour allocation) and wants to keep adapting the schedule continuously rather than in discrete promotion stages, so it is named here as a legitimate third option but is not the one recommended for this specific budget.
- Layer-wise learning rate decay versus separate optimizer parameter groups: both techniques let different parts of the model train at different effective learning rates, but they are not quite the same mechanism. Assigning separate optimizer parameter groups (for example, one group for the base encoder, one for a new classification head) gives each group its own FIXED learning rate you set directly. Layer-wise learning-rate decay instead applies a smooth multiplicative decay factor per layer depth (each layer's learning rate is the base rate times a decay factor raised to its depth from the output), so deeper (more general, earlier) layers automatically get progressively smaller rates than shallower (more task-specific, later) layers, without you having to manually define a separate group and rate for every layer.
Worked example: A concrete 100 GPU-hour schedule: spend roughly 60 GPU-hours on an ASHA screening stage running many short trials (for example a 0.5 GPU-hour minimum budget per trial) sampling learning rate on a log-uniform range, LoRA rank from a small discrete set, and batch size from a small set, promoting only the top handful of configurations to progressively larger budgets (2, then 6 GPU-hours); spend roughly 30 GPU-hours running a smaller number of longer Bayesian-optimization trials seeded from the ASHA survivors, refining around their neighborhood (a narrower learning-rate window, finer-grained rank choices); and reserve the final roughly 10 GPU-hours to re-validate the top 1-2 configurations for robustness (for example across a different random seed) before committing to a final full training run. PBT is deliberately not part of this particular allocation: with only 100 GPU-hours total, a PBT population large enough to make its exploit-and-explore step meaningful (typically dozens of population members training in parallel) would either consume the whole budget on population size alone or force a population too small for the exploit-and-explore mechanism to do useful work. For the parameter-group mechanism specifically, a minimal PyTorch pattern is to construct the optimizer with two parameter groups, one for the base encoder layers at a smaller learning rate and decayed weight, and one for the newly-initialized head at a larger learning rate, so the optimizer applies each group's own rate during every step, this is the direct implementation of "differential learning rates" that layer-wise decay generalizes into a smooth per-layer schedule.
Trade-offs and pitfalls: Spreading the 100 GPU-hour budget too thin across too many hyperparameters dilutes the signal from each trial and can make the multi-fidelity screening stage unreliable, which is why fixing lower-priority hyperparameters up front matters more as the budget shrinks. A second common pitfall is promoting configurations from the cheap screening stage based on very noisy short-run metrics; validating a small held-out, representative evaluation set (not just training loss) at each promotion decision helps avoid promoting a configuration that only looked good due to early-training noise. A third pitfall is defaulting to PBT because it is well known from the RL literature, without checking whether the fixed budget and infrastructure can actually support a population large enough for it to add value over the simpler ASHA-plus-Bayesian-optimization combination.
Unlock Full Question Bank
Get access to all 37 Generative AI and Large Language Models interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.