Version Control and Developer Tooling Questions
The everyday toolchain of software work: version control with Git (branching, merging, rebasing, conflict resolution, using git bisect to find a regression), command-line and shell proficiency for day-to-day navigation, log inspection, and troubleshooting, IDE and editor workflows, build systems and package/dependency management (npm, Maven, pip, Gradle, CocoaPods, and embedded/cross-compilation toolchains), and the growing practice of AI-assisted coding: using, reviewing, and verifying AI-generated code and tests. Deliberately generic across languages and stacks; language- and domain-specific frameworks live in their own categories. This topic covers a developer's individual command of these tools, not: writing durable shell automation and glue scripts (Shell Scripting and Automation owns that), producing, versioning, and publishing build artifacts or container images (Build Automation and Artifact Management owns that), release cadence and change governance (Release Management and Change Control owns that), or diagnosing a live production incident end to end (Performance Troubleshooting and Incident Response and the Observability topics own that).
When using Git for model and code versioning, describe best practices for handling large binary model files and datasets. Explain trade-offs between Git LFS, DVC, and storing artifacts in object storage, including how you would structure repositories and CI to keep code small while preserving reproducibility.
Sample Answer
Direct answer
Keep the Git repository itself small: commit code, configs, and small text-based metadata, and keep the actual bytes of large model files and datasets out of Git's own object store. The three common ways to do that are Git LFS, DVC, and plain object storage with a manifest, and the right choice depends on how much pipeline reproducibility and lineage tracking you need versus how simple you want the setup to be.
Structured elaboration
- Git LFS (Git Large File Storage): a Git extension that replaces a tracked large file with a small text pointer in the repository, while the actual file content lives in a separate LFS store hosted by GitHub, GitLab, or a self-hosted server. Cloning transparently downloads the real bytes for any pointer file. Setup is minimal:
git lfs track "*.pt"writes a rule to.gitattributes, and after thatgit add/git commitbehave the same as always. - DVC (Data Version Control): a tool built specifically for ML data and model versioning. It stores a small metadata file (a hash and a size) in Git for each tracked artifact, while the real file lives in a configurable remote such as S3, GCS, or Azure Blob. DVC also lets you define pipelines that record which code version, run against which data version, produced which model, giving reproducibility and lineage that Git LFS by itself does not provide.
- Object storage plus a manifest: skip a Git plugin entirely. Upload artifacts to S3/GCS with content-addressed keys (named by a checksum), and commit only a small manifest file listing artifact name, checksum, and storage URI. CI or training code reads the manifest at run time and fetches only what it needs.
Worked example
A repository layout that keeps Git itself small:
repo/
src/
configs/
requirements.txt
dvc.yaml # pipeline definition
models/checkpoint.pt.dvc # DVC pointer, a few lines of YAML
dvc add models/checkpoint.pt creates models/checkpoint.pt.dvc (hash and size only) and adds the real file to .dvc/cache and to .gitignore; dvc push uploads the real bytes to the configured remote. In CI, only the job stage that actually needs the weights, such as an integration test, runs dvc pull models/checkpoint.pt.dvc; the lint and unit-test stages never touch it, so most CI runs stay fast.
| Option | Setup complexity | Lineage / reproducibility | Best fit |
|---|---|---|---|
| Git LFS | Lowest | None beyond "this pointer maps to this file" | Small team, moderate file sizes |
| DVC | Moderate (extra tool, extra state) | Strong; tracks which code + data produced which model | ML pipelines with real branching/experimentation |
| Object storage + manifest | Moderate (you build the metadata layer) | As much as you build into the manifest | Large scale, production models, custom tooling already in place |
Trade-offs and pitfalls
Forgetting to run git lfs track before the first commit of a large file bloats the real Git history permanently, fixing it afterward means rewriting history, not just adding a rule going forward. DVC's local cache can quietly consume disk space if nobody garbage-collects it. A manifest-only approach has no automatic deduplication or cleanup unless you build it, and nothing stops someone from committing a huge file directly to Git unless you also enforce a pre-commit size check.
An AI assistant hands you distributed PyTorch training code using DDP. Walk through what you'd specifically check before trusting it: what subtle bugs or performance issues tend to hide in AI-generated distributed-training code around process setup, synchronization, dataloading, and metric aggregation.
Sample Answer
Direct answer
I review DDP (Distributed Data Parallel, PyTorch's mechanism for training the same model across multiple processes, typically one per GPU, keeping their gradients synchronized) code by walking the four places distributed bugs actually hide: process setup, synchronization inside the training loop, dataloading, and metric aggregation across ranks (a rank is one participating process in the distributed job). PyTorch is not installed in the environment I am writing this answer in, so the code below is presented for review, illustrating what I would check, not as a claimed execution trace.
Approach and code under review
def main(rank, world_size):
dist.init_process_group(backend="nccl", rank=rank, world_size=world_size)
torch.cuda.set_device(rank)
model = MyModel().to(rank)
model = DistributedDataParallel(model, device_ids=[rank])
sampler = DistributedSampler(dataset, num_replicas=world_size, rank=rank)
loader = DataLoader(dataset, sampler=sampler, batch_size=batch_size)
for epoch in range(num_epochs):
for batch in loader:
inputs, labels = batch
optimizer.zero_grad()
outputs = model(inputs.to(rank))
loss = criterion(outputs, labels.to(rank))
loss.backward()
optimizer.step()
acc = compute_accuracy(model, val_loader)
print(f"Epoch {epoch}: accuracy = {acc}")
Key points to check
Process setup
- Confirm
init_process_groupuses the right backend for the hardware (ncclfor multi-GPU is standard, not, say,gloo, which is meant for CPU or as a fallback), and that rank, world size, and a timeout are all actually wired correctly, since a missing or default timeout can leave a hung job waiting silently instead of failing loudly. - Confirm every process sets a distinct GPU via
torch.cuda.set_device(rank)before any tensors move to that device; a common AI-generated mistake is calling this after some setup already ran on the default device. - Seeds should be set per worker, but in a way that stays reproducible across runs, not literally identical across ranks if that would make every rank do the exact same random augmentation.
Synchronization inside the loop
- The model should be moved to its device and wrapped in
DistributedDataParallelexactly once, in that order (move to device, then wrap), not wrapped before the device move. - The code above is missing
sampler.set_epoch(epoch)inside the epoch loop. Without it,DistributedSamplerreuses the same shuffling order every epoch across all ranks, which quietly weakens training (the model sees the same partitioning of data in the same order every epoch instead of a fresh shuffle) without producing any error. - Watch for hidden synchronization points: calling
.item()on a GPU tensor inside the training loop, or an unnecessaryall_reduce, both force a synchronization across all ranks and can silently degrade throughput without any visible bug.
Dataloading
DistributedSampleris present here, which is correct: without it, every rank would iterate over the entire dataset independently, each seeing the exact same duplicated data.- Check whether
drop_lastis set intentionally; if the dataset size is not evenly divisible byworld_size, the last batch can differ in size across ranks, which can break assumptions elsewhere (like a fixed batch size used in metric aggregation). - Worker count and
pin_memorysettings affect throughput but do not affect correctness; they matter for performance review, not for trust.
Metric aggregation across ranks
- The code above computes
acc = compute_accuracy(model, val_loader)and prints it directly on every rank. This is a real bug: ifcompute_accuracyruns independently per rank on a differently-partitioned slice of validation data, each rank prints a different, locally-computed accuracy, none of which is the actual overall accuracy, and naively averaging those per-rank accuracies afterward is still wrong if the ranks do not have equal numbers of examples, since it is equivalent to weighting each rank's average equally rather than weighting by example count. - The fix: aggregate raw counts (correct predictions and total predictions) across ranks with
all_reducefirst, then compute the ratio once from the summed counts, and have only rank 0 print or log the final result, so the same number does not get printed once per GPU. - A concrete trace of why naive averaging is wrong: say rank 0 validates on 90 examples and gets 81 correct (0.9 accuracy), and rank 1 validates on only 10 examples and gets 5 correct (0.5 accuracy), an uneven split that happens naturally whenever the validation set doesn't divide evenly across ranks. Naively averaging the two per-rank accuracies gives (0.9 + 0.5) / 2 = 0.70. Aggregating the raw counts first gives (81 + 5) / (90 + 10) = 86 / 100 = 0.86, the actual overall accuracy. The two ranks don't have equal numbers of examples, so the naive average silently understates accuracy by 16 points here; that gap only disappears by coincidence, if every rank happens to validate on exactly the same number of examples.
- Validation should run under
model.eval()andtorch.no_grad(); the excerpt above does not show this, which is worth flagging explicitly rather than assuming it happens insidecompute_accuracy.
Edge cases and performance considerations
- Multi-node training (not just multi-GPU on one machine) needs the rendezvous (the process by which the distributed workers discover each other's network addresses and confirm everyone is present before training starts) and network configuration checked separately, since a setup that works on a single node with
ncclcan fail silently or hang across nodes if the network backend or address configuration is wrong. - Excessive communication overhead from unnecessary synchronization points, or from a batch size per GPU that is too small relative to the communication cost of each step, is a performance issue rather than a correctness one, but it is exactly the kind of thing that reads as "training is just slow" rather than surfacing as an obvious bug.
- Checkpoint saving on every rank instead of only rank 0 both wastes I/O and risks a race condition if multiple ranks write to the same path simultaneously.
The same failure category shows up beyond DDP
This exact pattern, code that quietly assumes a single-process execution model and breaks only once you actually distribute the work, shows up outside PyTorch too. An AI-proposed feature pipeline written in pandas for a dataset that will later run on Spark at 100 times the scale has the same shape of risk: pandas operations assume the whole dataset fits in memory on one machine and execute eagerly in a fixed row order, while Spark distributes data across partitions and executes lazily, so logic that depends on row order, a global sort, or an operation that silently materializes the entire dataset in memory can be correct in the small pandas prototype and either wrong or prohibitively expensive once it actually runs distributed. The check is the same in spirit as the DDP review above: read the code specifically for assumptions about running in one place, in one order, with everything visible to a single process, since that is exactly the assumption distributed execution breaks.
Trade-offs and pitfalls
None of the bugs above (missing set_epoch, per-rank metric printing, unnecessary synchronization) throw an error. Training runs to completion, a number gets printed, and everything looks fine unless you specifically know what correct DDP output should look like. That is exactly why a checklist matters more here than in single-process code: the failure signal is silence, not a crash.
An AI assistant writes model-serving code that loads serialized artifacts with pickle from disk. Why is this risky in production, how would you review the code, and what safer alternatives would you propose?
Sample Answer
Direct answer
Python's pickle module does not just store data, it stores instructions for reconstructing arbitrary Python objects, and reconstructing an object can involve calling arbitrary functions. Loading a pickle file is not "read some data," it is "run whatever code the file's author encoded into it." In a model-serving path, that turns a data-loading step into a remote code execution (RCE, an attacker's code running on your server as if it were your own) vector the moment the artifact could ever come from, or be tampered with in, a location you do not fully control.
Approach
The code under review looks innocent:
import pickle
def load_model(path: str):
with open(path, "rb") as f:
model = pickle.load(f) # executes arbitrary code embedded in the file
return model
Nothing here looks unusual, which is exactly the danger: a reviewer skimming for correctness bugs will not catch this, because the code is "correct." The risk is a property of the file format, not a bug in this function.
Why this actually executes code, demonstrated
This is illustrative but genuinely executed, not hand-written output: a class can define __reduce__ (the method pickle calls to figure out how to reconstruct an object) to return an arbitrary function and arguments instead of normal state, and unpickling calls that function.
import pickle, os
class Payload:
def __reduce__(self):
# __reduce__ tells pickle how to "reconstruct" this object; here,
# "reconstruction" means calling os.system with an arbitrary command.
return (os.system, ("echo PWNED-BY-UNPICKLING",))
data = pickle.dumps(Payload())
print("Serialized bytes look completely ordinary:", data[:40], "...", flush=True)
print("Now unpickling (this is the 'just loading a model file' step):", flush=True)
pickle.loads(data) # this is where the arbitrary command actually runs
Running this (Python 3, standard library only) prints:
Serialized bytes look completely ordinary: b'\x80\x05\x953\x00\x00\x00\x00\x00\x00\x00\x8c\x05posix\x94\x8c\x06system\x94\x93\x94\x8c\x18echo PWN' ...
Now unpickling (this is the 'just loading a model file' step):
PWNED-BY-UNPICKLING
The last line is the shell command actually executing, triggered purely by calling pickle.loads on bytes that look like ordinary binary data. A real attack would run something far less polite than echo.
How I would review the code
- Trace the full path: where is the artifact produced, where is it stored, and who or what can write to that location between training and serving?
- Confirm the artifact is versioned, and ideally signed and hash-checked, so serving code refuses to load a file that has been tampered with or does not match a known-good hash.
- Ask whether the serving process runs with least privilege (no unnecessary filesystem, network, or shell access), so that even if deserialization is exploited, the blast radius is smaller.
- Check whether the artifact ever crosses a trust boundary: was it produced entirely in-house on infrastructure you control, or could it originate from a less-trusted source, a shared bucket, an external contributor?
Safer alternatives
safetensors(a format designed specifically to store tensor weights without any code-execution risk) for model weights.- ONNX (Open Neural Network Exchange, a portable, framework-neutral inference format) when you need to serve a model without the code-execution surface of a framework-native pickle.
- Plain JSON or Parquet for non-tensor metadata and configuration.
- If custom Python objects genuinely need serializing, an explicit schema-based serializer (something that reconstructs a known, fixed set of fields rather than arbitrary objects) instead of pickle.
joblib.loadis sometimes suggested as a "safer" alternative; it is not, for this exact risk, since joblib uses pickle under the hood for arbitrary Python objects and inherits the same arbitrary-code-execution surface. It only helps with load performance, not with this specific vulnerability.
Trade-offs and edge cases to check
Signed, hash-checked artifacts add operational overhead (a signing step, a registry, key management) that a small team may resist, but the alternative is trusting every file on the serving path implicitly. Edge cases worth testing: an artifact with a valid hash but from an unexpected source, a serving process that falls back to a cached or default artifact if the primary fails to validate (make sure that fallback path is not itself less trusted), and any code path where the artifact location is derived from user input rather than a fixed, controlled configuration value.
An AI assistant generates a PyTorch training loop for you. Before you trust it and run it on real data, what would you check line by line, and what are the classic mistakes AI-generated training loops tend to make that are easy to miss on a quick read?
Sample Answer
Direct answer
I would read the loop line by line checking five specific things: device placement, gradient zeroing, the forward pass, the loss computation, and the backward/step sequence, since these are exactly where a quick read tends to skim past a subtly wrong line that still runs without error. PyTorch is not installed in the environment I am writing this answer in, so the training-loop excerpt below is illustrative for review purposes, not a claimed execution trace; I am not presenting fabricated output for it.
What I check, line by line
for epoch in range(num_epochs):
model.train()
for batch in dataloader:
inputs, labels = batch
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
- Device placement: are the model and every batch tensor moved to the same device before the forward pass? A model on GPU receiving CPU tensors (or vice versa) throws an error, but a subtler version, part of the pipeline (like a mask or an auxiliary tensor built later in the loop) never getting
.to(device), can slip past a quick read. - Gradient zeroing: does
optimizer.zero_grad()run at the start of every iteration, beforeloss.backward()? If it is missing or misplaced, gradients accumulate silently across batches instead of being computed fresh each time, and training still runs, it just learns something subtly wrong. - Forward pass: are inputs, labels, and any masks shaped the way the model expects, and is there an accidental
.cpu()call anywhere that would silently move a tensor off the GPU mid-pipeline? - Loss computation: is the loss a scalar, does it use the label format the loss function actually expects, and is any reduction (mean vs sum across the batch) intentional rather than a framework default nobody checked?
- Backward and step order: does
loss.backward()happen beforeoptimizer.step(), and is nothing calling.detach()on a tensor that still needs its gradient?
I also check for model.train() at the start of training and model.eval() plus torch.no_grad() (a context manager that disables gradient tracking, since validation does not need it and skipping it wastes memory and time) during validation, since AI-generated loops sometimes omit the mode switch entirely, which silently changes the behavior of layers like dropout and batch normalization between training and evaluation.
Classic mistakes that are easy to miss on a quick read
- Missing or misplaced
optimizer.zero_grad(), so gradients silently accumulate across batches instead of resetting each step. - No
model.eval()/model.train()switching, so dropout and batch normalization behave inconsistently between training and validation without any error being raised. - Validation code missing
torch.no_grad(), which still produces correct numbers but wastes memory and time computing gradients nobody uses. - A loss function and label shape that do not actually match (for example a multi-class setup mixing one-hot labels with a loss function that expects integer class indices), which either errors or, worse, silently computes something other than the intended loss.
Seeing the zero_grad effect concretely
PyTorch itself isn't available in this environment, but the accumulation bug doesn't actually depend on autograd internals, only on whether a number gets reset to zero between steps or not, so the same arithmetic is easy to show directly in plain Python and actually run:
def local_grad(w, target):
# dL/dw for L = (w - target) ** 2 -> 2 * (w - target)
return 2 * (w - target)
w = 0.5
targets = [1.0, 1.0, 1.0] # same target each "batch" on purpose, to isolate
# the accumulation effect from any real data change
print("With optimizer.zero_grad() called every step (correct):")
for step, y in enumerate(targets, start=1):
grad = 0.0 # zero_grad() resets the accumulator to 0 here
grad += local_grad(w, y)
print(f" step {step}: grad = {grad}")
print("With optimizer.zero_grad() missing (bug):")
grad = 0.0 # only initialized once, before the loop, never reset inside it
for step, y in enumerate(targets, start=1):
grad += local_grad(w, y) # this is what loss.backward() does to .grad
print(f" step {step}: grad = {grad}")
This was run exactly as shown and prints:
With optimizer.zero_grad() called every step (correct):
step 1: grad = -1.0
step 2: grad = -1.0
step 3: grad = -1.0
With optimizer.zero_grad() missing (bug):
step 1: grad = -1.0
step 2: grad = -2.0
step 3: grad = -3.0
w and the target are held fixed across all three steps here purely so the only thing changing is whether the accumulator resets, in a real loop w also updates every step, but the mechanism is the same one PyTorch's .grad accumulation follows: without a reset, .backward() keeps adding to whatever .grad already held, so by step 3 the optimizer would be reacting to a gradient three times too large, even though nothing about the data changed. That's the concrete shape of "training still runs, it just learns something subtly wrong."
Before running on real data
I run a single small batch through the loop first and watch whether loss decreases at all over a handful of steps on that tiny batch. That is a cheap, fast signal that the optimization path is wired correctly (gradients are flowing, the loss is actually connected to the model's parameters) before spending real time and compute on the full dataset.
Trade-offs and pitfalls
None of these mistakes throw an error, which is exactly what makes them dangerous: the loop runs to completion, the loss number exists, and everything looks fine on the surface while the model quietly learns worse than it should, or learns something that will not generalize. A training run finishing without a crash is not evidence the loop is correct.
You asked two AI tools to implement the same model evaluation utility. One solution is shorter but uses dense nested loops; the other is longer with clearer abstractions and tests. How would you decide which one to adopt?
Sample Answer
Direct answer
I would decide based on correctness, maintainability, and actual algorithmic cost for realistic data sizes, not line count. Shorter is not automatically better if it is harder to verify, and longer is not automatically better if the extra structure does not earn its keep; the deciding factors are whether each version is provably correct, how expensive it will be to change later, and whether its performance profile actually matches how the utility will be used.
Structured elaboration
Correctness first. Read both implementations against the spec and check edge cases: empty input, a single example, ties in whatever the utility is comparing. Run both on the same representative inputs and confirm they agree; if they disagree, that disagreement itself is the first thing to resolve, since one of the two is simply wrong.
Readability and future maintenance. A model evaluation utility tends to be touched again, new metrics added, edge cases discovered later, so the version with clearer abstractions usually wins if this code is going to live in the codebase rather than being thrown away after one use.
Algorithmic cost, reasoned about rather than measured. Dense nested loops over the evaluation set typically mean quadratic behavior, roughly proportional to the square of the input size, if the loops are comparing every example against every other example, versus a vectorized or hash-based approach that can often do the same comparison in roughly linear time. Whether that difference matters depends entirely on how large the real evaluation sets are: for a few hundred examples the two approaches may be indistinguishable in practice, while for a dataset with hundreds of thousands of rows a quadratic implementation can become the slowest part of an otherwise fast pipeline. I would reason about this from the algorithm's structure rather than trust a specific benchmark number from either AI tool, since a wall-clock timing claim is environment-dependent and not something I would treat as verified without running it myself on the actual target data size.
Test coverage. I trust the version with explicit tests more by default, especially for evaluation code, since a silent bug in a metric calculation is expensive: it can make a genuinely worse model look better, or vice versa, and nobody notices until much later.
Worked example
Say the utility computes pairwise similarity between predicted and true label sets for a batch of examples. The short version:
def matches(preds, labels):
count = 0
for p in preds:
for l in labels:
if p == l:
count += 1
return count
This nests one loop inside another, so its cost grows with the product of the two input sizes: for a batch of size n compared against itself, that is roughly n-squared comparisons. The longer version might instead build a set from labels once and then check membership per prediction, which drops the cost to roughly linear in the size of preds for the lookup, at the cost of readability going from "obviously what it says" (two nested loops, immediately understandable) to needing the reader to know sets give near-constant-time membership checks. For a small evaluation set (a few hundred examples), the difference is unlikely to be the bottleneck anywhere in the pipeline; for a large one, the nested-loop version is the one worth rewriting.
How I would actually decide
- Read both implementations against the spec.
- Run them on the same representative inputs and confirm they produce identical results.
- Reason about how each will scale to the evaluation sizes this will realistically see in production, and only benchmark directly on realistic data if that reasoning leaves genuine doubt.
- Prefer the version that is easier to extend, review, and verify, unless profiling on real data shows the other one is a genuine bottleneck.
Trade-offs and pitfalls
Optimizing for maintainability by default is the right instinct until it isn't: on a hot path processing millions of evaluation rows, the "obviously correct" nested-loop version can become a real cost, so this is a decision to revisit if the data volume changes, not a one-time choice. Conversely, adopting the longer, more abstract version purely because it looks more sophisticated, without verifying it is actually correct or actually needed, trades simplicity for complexity without buying anything.
Unlock Full Question Bank
Get access to all 8 Version Control and Developer Tooling interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.