Skip to content
Tech Interview Prep

Real Interview Questions for the Machine Learning Engineer at Yandex

New

Interview Q&A

25 questions · Flow follows Relevance until this set has a learning order.

Q&A-1How would you design a recommendation system for finding friends?

Reported in Yandex Machine Learning Engineer Interview Experience & Questions

The 90-second answer

I would treat this as People You May Know: given a user u, rank other users v by the probability that u sends a request and v accepts it and they interact afterwards. That target matters. Predicting a click alone optimises curiosity and fills the list with celebrities and strangers who never reply.

I assume we already have a social graph, profile data, and logged impressions. If the graph is empty, the design changes completely, so I would state that up front and ask what signals exist at signup.

The system has three stages: candidate generation, ranking, and serving with feedback logging.

Candidate generation. Recall matters more than precision here. Pull a few hundred candidates per user from independent sources, then deduplicate:

  • Graph neighbours of neighbours, scored by common neighbours, Jaccard, and Adamic-Adar
  • Co-interaction: people who liked, commented on, or attended the same events as u's friends
  • Affiliation: same school, employer, city, or interest groups, where the user has made that public
  • Contact import, only with explicit opt-in on both sides, and never exposed as a raw phone number
  • Embedding neighbours from a graph model such as GraphSAGE, retrieved with ANN search

Each source catches a different slice. Graph neighbours find school friends. Co-interaction finds people u already knows socially but is not connected to. Embeddings find weaker ties the exact graph rules miss. Dropping any one source shows up as a recall loss on a held-out set of accepted friendships, which is how I would size them.

Ranking. A gradient-boosted tree or a small neural ranker over hand-built features, trained on logged impressions. Positive label: request accepted plus at least one interaction in the next 7 days. Negative: shown but not accepted, or accepted with no interaction. Features include common neighbour count, Jaccard coefficient, Adamic-Adar, interaction recency and frequency with mutual friends, profile completeness, account age, and whether v is already saturated with incoming requests.

Python
import math

def adamic_adar(common_degrees):
    return sum(1.0 / math.log(d) for d in common_degrees if d > 1)

def jaccard(a, b):
    return len(a & b) / len(a | b) if a | b else 0.0

# u's friends: {a, b, c}; candidate v shares a and b
score = adamic_adar([120, 45]) + 2.0 * jaccard({"a", "b", "c"}, {"a", "b", "d"})

Worked trace for one user, with hypothetical figures:

CandidateCommon friendsJaccardAdamic-AdarP(accept and interact)
A, former classmate140.313.90.62
B, popular stranger20.020.40.05
C, colleague of a friend60.122.10.34

B can win on raw popularity or profile views. The model should rank A first because the label rewards a real tie, not attention.

Serving. Precompute the top 50 per active user nightly in a batch job, store them in a key-value store, and serve the top 10 to 20 in under 50 ms. New users and users with no precomputed list get a realtime path: graph expansion plus a lightweight ranker, accepting lower quality for a few hours until the batch job runs. Log every impression with its position, score, and candidate source. Without that log, offline training data is biased toward whatever the previous model showed.

User action or nightly batch Candidate generation Feature join from store Ranker Filter and diversify top 20 Serve and log impression Accept and interaction labels

Evaluation and failure modes. Offline, I would check Recall@500 for candidate generation against accepted friendships, and AUC plus calibration for the ranker. Online, the primary metric is accepted requests per user per week, with guardrails on ignore rate, block and report rate, and requests sent to strangers. A model that lifts accepts by pushing celebrity profiles usually lifts reports faster.

Three failure modes I would watch. Popularity bias: high-degree users dominate every list, so I would cap exposure per candidate and add degree as a feature the model can discount. Cold start: a new user has no graph, so the fallback is opt-in contacts, affiliation, and location, with lower confidence and fewer slots. Feedback loops: training only on shown candidates shrinks the pool over time, so I would reserve a small exploration slice, for example 5% of slots, for candidates outside the current top set and log their outcomes separately.

Privacy is a hard constraint, not a metric. Contact-derived candidates need consent, mutual-friend counts must not leak information about private accounts, and features from private interactions should stay out of the model. If a signal cannot be explained to the user whose data it came from, I would not ship it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2Solve LeetCode 680 Valid Palindrome II?

Reported in Yandex Machine Learning Engineer Interview Experience & Questions

The 90-second answer

Given a string s, decide whether deleting at most zero or one character can make it a palindrome. I use two pointers, l at the start and r at the end, and move inward while characters match. At the first mismatch, s[l] != s[r], the deletion, if one exists, must remove s[l] or s[r]. I test both options with a plain palindrome check on the remaining substring and return true if either passes. If the pointers cross with no mismatch, the string already is a palindrome.

Python
# Python 3.12
def valid_palindrome_ii(s: str) -> bool:
    def is_pal(l: int, r: int) -> bool:
        while l < r:
            if s[l] != s[r]:
                return False
            l += 1
            r -= 1
        return True

    l, r = 0, len(s) - 1
    while l < r:
        if s[l] != s[r]:
            return is_pal(l + 1, r) or is_pal(l, r - 1)
        l += 1
        r -= 1
    return True

Why checking two branches is enough

Suppose the first mismatch is at positions l and r. Any valid single deletion that fixes the string has to delete one of those two characters. Deleting a character elsewhere leaves both s[l] and s[r] in place, and they would still sit at mirrored positions in the result, so the result could not be a palindrome. That argument is the whole correctness proof. It also explains why a greedy rule that always deletes the left character, or always deletes the right one, fails. Example: abca. The first mismatch is b against c. Deleting b gives aca, a palindrome. Deleting c gives aba, also a palindrome, so either choice happens to work here. A sharper case is aab. The mismatch is a against b. Deleting the left a gives ab, which fails. Deleting b gives aa, which passes. A one-sided greedy that commits to the left deletion returns the wrong answer.

Worked trace

For s = "abca", indices 0 to 3:

Steplrs[l] vs s[r]Action
103a vs amatch, move both inward
212b vs cmismatch, branch
3a22single characteraca is a palindrome, return true
3b11single characteraba is a palindrome, return true

For s = "abc", the same first mismatch gives bc and ab, both fail, so the answer is false. For s = "racecar", the pointers cross with no mismatch and the answer is true with zero deletions.

Complexity and alternatives

ApproachTimeExtra spaceComment
Two pointers, as aboveO(n)O(1)Each index is visited a constant number of times
Try deleting every index, recheck each timeO(n^2)O(n) if building new stringsSimple to write, wasteful on long inputs
DP over substringsO(n^2)O(n^2)Overkill, and it answers a harder question

The two-pointer version does at most one full scan plus one bounded recheck of the inner range, so the total work stays linear. For n = 10^6, that is roughly a few million character comparisons, while the try-every-deletion version is on the order of 10^12 comparisons and would time out.

Edge cases I would name before coding

Empty string and single character both return true. Two characters return true, since deleting one leaves a single character. Case sensitivity matters: Abba is false under the usual LeetCode rules, because A and a differ. Python strings are sequences of Unicode code points, so indexing works per code point, which matches the problem statement. The common bug is an off-by-one in the helper, using l <= r with a strict mismatch test or forgetting to increment inside the helper loop. I would test aab, abc, abca, racecar, and the empty string before submitting.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3Explain the concept of overfitting in machine learning and describe techniques to mitigate it?

Reported in Yandex Machine Learning Engineer Interview Experience & Questions

The 90-second answer

Overfitting is when a model fits the training data, including its noise, so well that it performs worse on unseen data from the same distribution. The signature is a gap: training error keeps falling while validation error stops falling and then rises. Underfitting is the opposite, high error on both. I would state that assumption up front, because if the test distribution has shifted, a validation gap is not pure overfitting.

The mechanism is variance. A flexible model, deep trees, many features, or long training, can use capacity to memorize idiosyncrasies of the sample. Those idiosyncrasies do not repeat, so expected test error rises even though empirical error falls. Bias-variance decomposition makes this precise for squared loss: expected error = bias squared + variance + irreducible noise. Regularization and early stopping trade a little bias for a large variance reduction.

A worked trace

Hypothetical run, binary classifier, 20,000 training rows, 5,000 validation rows, same distribution:

EpochTrain accuracyValidation accuracyGapReading
578.1%77.4%0.7 ppunderfitting, still learning signal
2089.6%86.2%3.4 ppnear the useful optimum
6097.8%84.9%12.9 ppmemorizing noise
12099.4%83.1%16.3 ppsevere overfitting

Stopping at epoch 20, or at the best validation checkpoint, beats the final model by 3.1 pp on validation. That is the decision early stopping automates.

Mitigations, and when each helps

TechniqueWhat it changesWhen I reach for itCost or risk
More data, better featuresreduces variance at the sourcefirst choice when data collection is cheapslow, and new features can leak
L2 regularizationshrinks weights, penalizes large coefficientslinear models, neural nets, CatBoost l2_leaf_regtoo much strength causes underfitting
L1 regularizationdrives some weights to exactly zerohigh dimensional sparse features, feature selectionunstable selection among correlated features
Early stoppinghalts training at best validation pointiterative models, gradient boosting, neural netsneeds a clean validation split, wastes compute if patience is large
Dropout, weight decay, pruninglimits co-adaptation and effective capacitydeep networks, large treesextra hyperparameters, longer tuning
Cross-validationestimates generalization and tunes strengthsmall datasets, model selectioncompute cost, and tuning on the same folds can still overfit
Ensembling, baggingaverages uncorrelated errorsunstable learners such as deep treesserving cost, harder debugging

In code, the same idea for a regularized linear model in scikit-learn, checked against Python 3.11 and scikit-learn 1.4:

Python
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score

# C is the inverse of regularization strength: smaller C, stronger L2.
for C in [0.01, 0.1, 1.0, 10.0]:
    model = LogisticRegression(C=C, penalty="l2", max_iter=1000)
    scores = cross_val_score(model, X_train, y_train, cv=5, scoring="roc_auc")
    print(C, scores.mean())

I pick C by cross-validated score, then refit on all training data and report once on a held-out test set. For gradient boosting I do the analogous thing with depth, learning rate, number of trees, and early stopping on validation loss. In CatBoost, which Yandex teams use heavily for tabular ranking and classification, I watch depth, l2_leaf_reg, and ordered boosting, and I treat a train to validation AUC gap above roughly 2 to 3 points on a stable split as a prompt to regularize before adding capacity.

Failure modes I check before calling it overfitting

Leakage is the common one. A feature computed from the target, or preprocessing fitted on the full dataset before splitting, inflates validation scores and hides the real gap. I fit scalers and encoders inside each fold. The second is tuning on the test set. Repeatedly selecting checkpoints or hyperparameters against test data turns the test set into training data, and the reported score becomes optimistic. The third is distribution shift. If validation comes from last week and production traffic has changed, regularization will not fix the gap. I compare feature distributions and label rates between splits before changing the model.

A strong answer closes with measurement, not a list. Show the learning curves, name the validation protocol, state which regularizer I changed and by how much validation improved, and keep the test set untouched until the final report.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4How would you approach feature selection and feature engineering for a sentiment analysis problem?

Reported in Yandex Machine Learning Engineer Interview Experience & Questions

The 90-second answer

I would start by fixing the label and the text unit, because feature choices follow from them. Assume three classes (negative, neutral, positive) on short Russian product reviews, 50k labelled examples, and a model that must run on CPU at under 20 ms per document. That rules out fine-tuning a large transformer as the first baseline. I would build a linear model over TF-IDF n-grams, add a small set of hand-built sentiment features, then select features by stability across folds rather than by a single importance ranking.

First pass, no selection at all except a frequency floor. Tokenize with lemmatization for Russian, since "плохой", "плохая" and "плохо" should map to one token. Keep word 1-2 grams and character 3-5 grams. Character n-grams catch typos and morphology that lemmatization misses, at the cost of a much larger vocabulary. Fit the vectorizer on the training fold only. Fitting on the full corpus leaks test vocabulary and inflates validation F1 by a few points on small datasets, which is the most common mistake I see in these pipelines.

Python
# Python 3.11, scikit-learn 1.4
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_selection import SelectKBest, chi2
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline

pipe = Pipeline([
    ("tfidf", TfidfVectorizer(
        analyzer="word", ngram_range=(1, 2), min_df=5,
        max_features=80_000, sublinear_tf=True)),
    ("select", SelectKBest(chi2, k=20_000)),
    ("clf", LogisticRegression(C=4.0, max_iter=1000,
                               class_weight="balanced")),
])
pipe.fit(X_train, y_train)

With min_df=5 on 50k reviews the vocabulary typically drops from roughly 400k raw types to 60-80k. Chi-square then keeps the 20k most label-associated terms. I would check that the kept set is stable: run selection on five folds and keep features selected in at least four. Features that appear in one fold only are usually topic words from a single product category, and they hurt on new categories.

Feature engineering that actually moves the score

Raw n-grams miss three things in sentiment text: negation scope, intensity, and aspect. I add explicit features for each, computed before vectorization and appended as dense columns.

FeatureConstructionWhy it helps
Negation windowMark tokens within 3 tokens after "не", "нет", "ни" with a NEG_ prefix"не плохой" stops sharing a feature with "плохой"
Intensifier countCount of "очень", "совсем", "вообще" plus repeated punctuation "!!!"Separates mild from extreme sentiment
Aspect splitSplit text on aspect nouns (цена, качество, доставка) and build per-aspect TF-IDFA review can be positive on quality and negative on price
Emoji and emoticon mapMap positive and negative emoji to POS_EMOJI / NEG_EMOJI tokensKeeps signal that a tokenizer would drop
Length and exclamation ratiolen(text), count("!") / len(text)Weak alone, useful as a prior for sarcasm detection

Worked trace on one sentence, "Не плохой, но очень дорогой":

StepOutput
------
Lemmatized tokensне плохой но очень дорогой
Negation markingNEG_плохой но очень дорогой
Intensifier count1 ("очень")
Aspectцена implied by "дорогой", no explicit aspect noun

Without negation marking, the bigram "не плохой" does capture this case, but only if that exact bigram survives min_df. The prefix form generalizes to "не понравился", "не советую" and unseen combinations.

Choosing between representations

ApproachStrengthWeaknessWhen I pick it
TF-IDF + linear modelFast, interpretable, strong on 10k-200k examplesNo word order beyond n-grams, no contextBaseline and production CPU model
Averaged embeddings (e.g. 300-d Word2Vec) + MLPHandles synonyms, smaller feature spaceLoses negation and word order in averagingVocabulary is huge and synonyms dominate errors
Fine-tuned transformer (RuBERT)Best accuracy, handles negation and sarcasm betterGPU training, 100-300 ms inference on CPU, harder to debugF1 gap over linear is more than 3 points and latency budget allows it

I would report macro-F1 per class, not accuracy, because neutral is usually the minority and the hardest class. A model that scores 0.88 accuracy by predicting positive for everything is useless.

Failure modes I would name in the interview

Sarcasm ("отличный сервис, ждал 3 часа") defeats both n-grams and averaged embeddings. Detection: high positive lexicon score with long wait-time mentions. Mitigation is contextual models or a sarcasm-specific training slice, not more n-grams.

Domain shift is the second. Features selected on electronics reviews ("батарея", "экран") transfer poorly to food delivery. I would validate on a held-out category, not a random split, and prefer character n-grams and lemmatized unigrams there because they degrade more gracefully.

Third, leakage through duplicates. Near-duplicate reviews from the same user across train and test inflate scores. Deduplicate by normalized text hash before splitting, and split by user ID when user history exists.

If the linear baseline reaches macro-F1 within 2 points of the transformer on the category holdout, I ship the linear model. It retrains in minutes, its top chi-square features are inspectable, and I can explain any prediction by listing the contributing terms.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5Discuss the differences between supervised learning and unsupervised learning algorithms and when would you choose one over the other?

Reported in Yandex Machine Learning Engineer Interview Experience & Questions

The 90-second answer

Supervised learning learns a mapping from inputs to a target you provide. Unsupervised learning finds structure in inputs alone. The choice comes down to whether you can define the target and get labels you trust at a cost the product can bear.

Assume we have tabular or text data, a production metric, and a deadline. If the metric is, say, click-through or fraud, and we can label past examples, supervised gives us a direct objective to optimise and a held-out set to measure it. If we cannot label, or we do not yet know what the categories are, unsupervised is how we explore, compress, or flag anomalies before any label exists.

SupervisedUnsupervised
SignalPairs $(x, y)$: label, score, or rankingInputs $x$ only
Typical tasksClassification, regression, ranking, extractionClustering, dimensionality reduction, anomaly detection, density estimation
ObjectiveMinimise loss against $y$, e.g. log loss, MSEOptimise a criterion on $x$, e.g. within-cluster variance, reconstruction error
EvaluationHeld-out accuracy, AUC, RMSE, NDCG. Direct and comparableSilhouette, stability under resampling, downstream task lift. Indirect
Main costLabelling, label quality, leakageChoosing $k$, scaling, interpreting clusters
Yandex-style exampleCatBoost or gradient boosting to predict search click or purchase from query and document featuresEmbeddings plus clustering of queries to discover new intents before anyone labels them

How the decision plays out

No Yes No Yes Can you define the target y? Unsupervised: explore, cluster, reduce dimension Can you get labels at acceptable cost and quality? Unsupervised or semi-supervised: pretrain, cluster, then label clusters Supervised: train, validate on held-out data Evaluate by stability and downstream use

A concrete trace helps. Suppose we have 200,000 search sessions with query text and a click label for 5,000 of them, labelled by human raters. A supervised model trains on those 5,000, validates on 1,000 held out, and we report AUC. If AUC is 0.81 on held-out data but drops to 0.66 next week, we suspect distribution shift or leakage, for instance a feature that encodes the label after the click. That failure is detectable because we have ground truth.

Now suppose we have 2 million queries and no labels at all. K-means with $k=50$ on TF-IDF or embeddings will return clusters, but changing the random seed or scaling can move 15% of points between clusters. Silhouette might be 0.18, which tells us the structure is weak. The clusters are still useful if a downstream classifier trained on cluster IDs as features improves, or if analysts can name the clusters consistently. Without that downstream check, a cluster plot is not a result.

Python
# Python 3.11, scikit-learn 1.4. Checked logic, not run here.
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.model_selection import train_test_split
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score

# Unsupervised: no y used
km = KMeans(n_clusters=50, n_init=10, random_state=0).fit(X_all)
print("silhouette:", silhouette_score(X_all, km.labels_))

# Supervised: y required, held-out evaluation
X_tr, X_te, y_tr, y_te = train_test_split(X_lab, y_lab, test_size=0.2, random_state=0)
clf = HistGradientBoostingClassifier().fit(X_tr, y_tr)
print("AUC:", roc_auc_score(y_te, clf.predict_proba(X_te)[:, 1]))

Failure modes I would name in the loop

Supervised fails quietly through label noise and leakage. If raters disagree on 20% of examples, the ceiling on AUC is set by that noise, and more data will not fix it. Leakage, such as a feature computed after the outcome, inflates offline AUC and collapses online. Both show up as a gap between offline and online metrics.

Unsupervised fails through arbitrary choices. Distance metric, feature scaling, and $k$ decide the answer before the algorithm runs. In high dimensions, distances concentrate, so K-means on raw 10,000-dimensional sparse features without reduction often returns near-random partitions. The check is stability: bootstrap the data, rerun, and measure cluster overlap. Unstable clusters should not drive product decisions.

The middle ground matters in practice. Semi-supervised and self-training start unsupervised, for example with embeddings or clustering, then use a small labelled set to name clusters or to train the final classifier. That is often the right Yandex-scale answer: Toloka-style labelling is expensive, so we spend it only where the unsupervised structure is ambiguous, and we keep a labelled validation set untouched for the final number.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6Describe the working principles of convolutional neural networks (CNNs) and how they handle spatial hierarchies and achieve translation invariance?

Reported in Yandex Machine Learning Engineer Interview Experience & Questions

The 90-second answer

A CNN replaces a dense layer over pixels with local, shared filters. Each filter slides over the image, computes a dot product with a small patch, and produces a feature map. Because the same weights are reused at every position, the network learns a detector for an edge, a corner, or a texture once and applies it everywhere. Stacking layers widens the receptive field, so early layers respond to edges and colour blobs, middle layers to textures and parts, and late layers to object-level patterns. Convolution itself is translation equivariant: shifting the input shifts the feature map by the same amount. Pooling, strided convolution, and global aggregation then make the final decision approximately translation invariant, because a small shift changes the pooled response little or not at all.

Mechanism

For an input $X$ and a $K \times K$ kernel $W$, one output position is:

$$Y[i,j] = \sum_{m=0}^{K-1} \sum_{n=0}^{K-1} W[m,n] \cdot X[i+m, j+n] + b$$

In practice the layer is cross-correlation, with no kernel flip, and a non-linearity such as ReLU follows. Output size follows:

$$O = \left\lfloor \frac{I + 2P - D(K-1) - 1}{S} + 1 \right\rfloor$$

where $I$ is input size, $P$ padding, $D$ dilation, and $S$ stride. Padding preserves spatial size, stride and dilation change resolution and receptive field without adding parameters.

Weight sharing is the main parameter saving. A $3 \times 3$ convolution with 64 output channels on a 3-channel input has $3 \times 3 \times 3 \times 64 + 64 = 1{,}792$ parameters, regardless of whether the image is $224 \times 224$ or $1024 \times 1024$. A dense layer mapping the flattened $224 \times 224 \times 3$ image to 64 units would need about 9.6 million weights and would treat a pattern at the top left and the same pattern at the bottom right as unrelated inputs.

Python
# PyTorch 2.x, checked against torch.nn.Conv2d semantics
import torch
from torch import nn

x = torch.randn(2, 3, 224, 224)  # batch, channels, height, width
conv = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1)
y = conv(x)
print(y.shape)  # torch.Size([2, 64, 224, 224])
print(sum(p.numel() for p in conv.parameters()))  # 1792

Spatial hierarchy and receptive field

Input pixels Conv 3x3 + ReLU Pooling or stride Deeper conv blocks Global average pooling Linear classifier

A unit in layer $l$ sees a region of the original image called its receptive field. With stride 1 and $3 \times 3$ kernels, the field grows by 2 pixels per layer. With stride 2, it grows faster and the feature map shrinks. After several blocks, a late unit can cover most of a $224 \times 224$ image, which is how a detector for a wheel can combine earlier detectors for arcs and spokes. Residual connections, as in ResNet, and $1 \times 1$ convolutions help train deeper stacks by easing gradient flow and mixing channels cheaply.

Layer (hypothetical example)InputKernel / strideOutputParameters
conv1$224 \times 224 \times 3$$7 \times 7$, stride 2, pad 3$112 \times 112 \times 64$9,408
conv2 block$112 \times 112 \times 64$$3 \times 3$, stride 1, pad 1$112 \times 112 \times 64$36,928
downsample$112 \times 112 \times 64$$3 \times 3$, stride 2, pad 1$56 \times 56 \times 128$73,856
global pool$7 \times 7 \times 512$average over $7 \times 7$$512$0

Where invariance comes from, and where it breaks

Max pooling over a $2 \times 2$ window keeps the strongest response in that window, so a one-pixel shift often leaves the pooled value unchanged. Global average pooling goes further: it averages each final feature map over all positions, so the classifier sees how present a pattern is, with little information about where it occurred. That suits image classification, where a cat remains a cat after a small translation.

The invariance is approximate. Strided convolution and pooling can alias high-frequency detail, so a shift of a few pixels can change activations more than expected. Padding introduces border effects, and a large translation that moves an object partly out of frame changes the evidence available. CNNs also have no built-in invariance to rotation, scale, or reflection. A network trained on upright digits can fail on rotated ones unless augmentation or an equivariant architecture supplies that symmetry. I check this with a shift test: translate validation images by $\pm 8$ pixels and compare top-1 accuracy and logit drift. A drop of several points signals reliance on absolute position, often from a flatten layer instead of global pooling.

For tasks where position matters, such as detection or segmentation, full invariance is a liability. Those heads keep spatial maps and predict boxes or per-pixel labels, trading some translation tolerance for localisation. The choice depends on the output: classification wants aggregation, dense prediction wants equivariance preserved as long as possible.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7Suppose you are given a dataset with imbalanced classes for a binary classification problem. How would you address imbalanced classes and improve model performance?

Reported in Yandex Machine Learning Engineer Interview Experience & Questions

The 90-second answer

First I would ask what the positive class costs. A 1:100 fraud problem where a missed fraud costs 100x a false alarm is a different problem from a 1:100 churn problem where the team can only call 50 customers a day. That answer decides the metric, and the metric decides everything else.

I would not start by resampling. I would start by fixing evaluation: stratified splits, a metric that survives imbalance, and a decision threshold tuned separately from the model. Only then would I touch class weights or sampling, because both change the score distribution and can wreck calibration if applied blindly.

Assume 10,000 rows, 100 positives (1%). A classifier that predicts all negative gets 99% accuracy and zero value. ROC-AUC can still look respectable here because the true negative pool is huge. I would report PR-AUC (average precision), recall at a fixed precision or fixed review budget, and the full confusion matrix at the chosen threshold. For Yandex-style tabular work I would also check what CatBoost or LightGBM does with scale_pos_weight or class_weights before reaching for SMOTE, since gradient boosting often handles imbalance through the loss without synthetic rows.

Worked trace: threshold, not accuracy

Hypothetical validation set, 1,000 rows, 20 positives. Same ranking model, three thresholds:

ThresholdTPFPFNPrecisionRecallF1
0.5084120.670.400.50
0.20152550.380.750.50
0.10188020.180.900.30

At 0.50 the model looks precise and misses 60% of positives. At 0.20 it catches 75% at a review cost of 40 alerts per 1,000 rows. If the operations team can review 40 per 1,000, 0.20 is the operating point. If they can review 12, neither 0.20 nor 0.10 works and I need a better ranking model, not a lower threshold. That is the conversation to have with the product owner, with numbers.

What I would actually try, in order

  1. Baseline and metric lock. Logistic regression or LightGBM with no correction, stratified 5-fold CV, PR-AUC and recall at the agreed precision floor. This is the number every later change must beat.

  2. Class weighting. Set scale_pos_weight = n_negative / n_positive (99 in the example above) or the equivalent class_weight='balanced'. This usually lifts recall and PR-AUC for tree models. The cost: predicted probabilities shift upward and are no longer calibrated. If downstream code consumes the probability (expected value, ranking across segments), I recalibrate on a held-out set with Platt scaling or isotonic regression, and I do that recalibration on data that was not resampled.

  3. Sampling, only if weighting stalls. Random undersampling of the majority class is fast and often works when data is plentiful, but it throws away information. Oversampling duplicates minority rows and risks overfitting to a few repeated points. SMOTE interpolates between minority neighbours, which helps in smooth feature spaces and hurts when the minority class is actually several disjoint clusters or contains label noise. Whichever I use, resampling happens inside each training fold only. Resampling before the split leaks duplicated or synthetic rows into validation and inflates PR-AUC by points that vanish in production.

Python
# Python 3.11, scikit-learn 1.4, LightGBM 4.x
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import average_precision_score, precision_recall_curve
import lightgbm as lgb
import numpy as np

skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
oof = np.zeros(len(y))

for tr, va in skf.split(X, y):
    n_pos, n_neg = y[tr].sum(), len(tr) - y[tr].sum()
    model = lgb.LGBMClassifier(
        n_estimators=500, learning_rate=0.05, num_leaves=31,
        scale_pos_weight=n_neg / n_pos,  # 99 for a 1% positive rate
        random_state=42, verbose=-1,
    )
    model.fit(X[tr], y[tr])
    oof[va] = model.predict_proba(X[va])[:, 1]

print("PR-AUC:", average_precision_score(y, oof))
prec, rec, thr = precision_recall_curve(y, oof)
# Pick the lowest threshold that keeps precision >= business floor, e.g. 0.35
ok = np.where(prec[:-1] >= 0.35)[0]
cut = thr[ok[0]] if len(ok) else 0.5
print("threshold for precision>=0.35:", cut)
  1. Threshold and cost tuning. Sweep thresholds on out-of-fold predictions, not on the training set. Choose by expected cost: cost = FP * c_fp + FN * c_fn. If c_fn is 100x c_fp, the optimal threshold will be far below 0.5, and that is correct behaviour, not a bug.

  2. Data fixes before model fixes. Check for label noise in the minority class, duplicated rows, and leakage features that only exist after the outcome. With 100 positives, 10 mislabelled ones move PR-AUC more than any sampler will. If the minority class is tiny (under a few hundred examples), I would also consider collecting more positives, active learning on uncertain cases, or reframing as anomaly detection, and I would say so explicitly rather than pretend SMOTE creates information.

Failure modes I would name in the loop

Resampling before splitting, which produces a validation score the production model never reproduces. Optimising accuracy or ROC-AUC and shipping a model with 0% recall on the class that matters. Applying class weights and then feeding the raw scores into a downstream expected-value calculation without recalibration, which systematically overstates risk. And threshold drift: if the positive rate shifts from 1% to 3% after launch, precision at a fixed threshold changes even if the ranking is unchanged, so I would monitor the score distribution and the realised precision weekly and re-tune the threshold on fresh labelled data.

If the interviewer pushes on one technique, I would defend this order: fix the metric and threshold first, add class weights second, treat sampling as a fallback with leakage controls, and treat data quality as the ceiling on everything.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8How would you plot an ROC-AUC curve given a trained model?

Reported in Yandex ML Engineer interview experience (October 2024)

The 90-second answer

I need three things: a held-out labelled set the model never trained on, a continuous score per example (predicted probability or decision function), and the true binary labels. Hard 0/1 predictions are not enough, because the curve is defined by sweeping the decision threshold.

For each candidate threshold t, predict positive when score >= t, then compute:

  • TPR (recall) = TP / (TP + FN)
  • FPR = FP / (FP + TN)

Plot TPR against FPR as t moves from +infinity to -infinity. The curve starts at (0, 0), ends at (1, 1), and AUC is the area under it. AUC also equals the probability that a randomly chosen positive scores above a randomly chosen negative, with ties counting as 0.5.

Python
# Python 3.11, scikit-learn 1.5
from sklearn.metrics import roc_curve, roc_auc_score, auc
import matplotlib.pyplot as plt

# y_true, y_score from a held-out test set, never from training data
y_true = [1, 1, 1, 0, 0, 0, 0, 0]
y_score = [0.90, 0.70, 0.40, 0.80, 0.50, 0.30, 0.20, 0.10]

fpr, tpr, thresholds = roc_curve(y_true, y_score)
roc_auc = roc_auc_score(y_true, y_score)  # 0.80 for this example
assert abs(roc_auc - auc(fpr, tpr)) < 1e-9

plt.figure()
plt.plot(fpr, tpr, label=f"AUC = {roc_auc:.3f}")
plt.plot([0, 1], [0, 1], "--", label="chance")
plt.xlabel("False positive rate")
plt.ylabel("True positive rate")
plt.legend()
plt.show()

Worked trace on the same 8 examples

There are 3 positives and 5 negatives. Sorting thresholds by distinct scores gives every point roc_curve returns:

ThresholdTPFPTPRFPR
> 0.90000.0000.000
0.90100.3330.000
0.80110.3330.200
0.70210.6670.200
0.50220.6670.400
0.40321.0000.400
0.30331.0000.600
0.20341.0000.800
0.10351.0001.000

Check by pairs: 0.90 beats all 5 negatives (5), 0.70 beats 4 (4), 0.40 beats 3 (3). Total 12 of 15 pairs, so AUC = 12/15 = 0.80. That matches the trapezoidal area under the points above and is why I trust the library call: the two computations agree.

What AUC does and does not tell you

AUC is invariant to any monotonic transform of the score, so it says nothing about calibration. A model can rank perfectly (AUC 1.0) while its probabilities are badly miscalibrated, which matters if a downstream system thresholds at 0.5 or uses the probability as an expected value. It also averages over all thresholds, including regions you would never operate in. For a fraud or ranking system where only the top 1% of scores matter, partial AUC at low FPR, precision-recall AUC, or precision at k often decides better. With heavy class imbalance, PR-AUC is usually more informative because ROC-AUC can look high while precision at usable recall stays low.

For a production report I add a confidence interval. Bootstrap the held-out set (resample with replacement, recompute AUC, take the 2.5th and 97.5th percentiles over 1,000 resamples) or use stratified cross-validation scores pooled out-of-fold. A single AUC of 0.80 on 200 test examples carries far more uncertainty than the same number on 200,000.

Failure modes I check before plotting

  • Scores computed on training data, or on data with near-duplicates of training rows. The curve then measures memorisation. Split by the entity that leaks in practice (user, session, document) rather than by row.
  • Only one class present in the test slice. TPR or FPR is undefined and roc_curve raises. That is a data problem, not a plotting problem.
  • Scores are already thresholded labels, or rounded to 0/1. The curve collapses to a single interior point and AUC becomes a function of one operating point.
  • Ties from a coarse score (for example, integer ratings 1 to 5). roc_curve handles ties by grouping equal scores at one threshold, which is correct, but the curve will have long straight segments and AUC will be lower than the underlying ranking quality suggests.

If the interviewer asks which threshold to deploy, I pick it from the curve using the cost ratio: minimise cost_FP * FP + cost_FN * FN on validation data, or fix the FPR the product can tolerate and read TPR off the curve. AUC alone never picks that point.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9What exactly are you fine-tuning, and what does your dataset look like?

Reported in ML Engineer interview at Yandex

The 90-second answer

I would name the base model, the task head, and the exact data contract before I mention any hyperparameters. For a recent project I fine-tuned a 7B decoder for Russian support-ticket classification into 14 intents, with a classification head on the last token. The base model was frozen except for LoRA adapters on the attention and MLP projections. That choice mattered because we had 38,000 labelled tickets, not 38 million, and full fine-tuning on that volume overfit within one epoch and degraded the base model's Russian generation.

The dataset was not a folder of JSON files. It was a versioned table with one row per ticket, the raw text, the label, the source, the annotator IDs, and a timestamp. I split by time and by customer, not at random, because the same customer writes near-identical tickets across weeks and random splits leak that phrasing into validation.

SplitRowsSharePurpose
Train30,40080%Fit adapters
Validation3,80010%Early stopping, threshold choice
Test3,80010%Locked, used once

Labels came from two annotators per ticket with adjudication on disagreement. Inter-annotator agreement was Cohen's kappa 0.81 before adjudication. The smallest class had 410 examples, the largest 6,200, so I used class-weighted loss and reported per-class F1 instead of accuracy. A model that predicts the majority class gets 16% accuracy here and looks fine on a single number while failing the rare billing intent that the team cared about most.

What fine-tuning actually changed

Python
# Python 3.11, transformers 4.44, peft 0.12. Hypothetical run config.
from peft import LoraConfig

lora = LoraConfig(
    r=16, lora_alpha=32, lora_dropout=0.05,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
    task_type="CAUSAL_LM",
)
# Training: lr 2e-4, cosine schedule, warmup 3%, 3 epochs,
# global batch 64, max_len 512, loss on label tokens only.

Loss on label tokens only is the detail people miss. If you compute loss over the full ticket text, the model spends most of its capacity learning to copy user text and the classification signal is diluted. With label-only loss, validation macro-F1 reached 0.87 after epoch 2 and fell to 0.84 by epoch 3, so I stopped at epoch 2. Full fine-tuning at lr 1e-5 reached 0.86 but took 4x the GPU time and dropped perplexity on held-out general Russian text by 18%, which showed up as worse answers when the classifier was used inside a generative assistant.

Raw tickets + labels Dedup and PII scrub Time and customer split Tokenize, mask prompt LoRA fine-tune Eval per-class F1 on locked test

Failure modes I check before trusting the result

Near-duplicates across splits. I ran MinHash on normalized text and found 2.1% of validation rows had a near-duplicate in train under a random split. After the customer split that fell below 0.2%. Without that check, validation F1 was inflated by about 4 points.

Label noise in the tail classes. I sampled 200 examples from the smallest class and found 9% mislabelled, mostly confusion between two billing intents. Cleaning those moved that class's F1 from 0.71 to 0.79, a bigger gain than any hyperparameter change.

Distribution shift. Ticket wording changed after a product UI update in the test period. I tracked F1 by week and saw a 6 point drop in the first week after the change, which told us to add 1,500 newly labelled examples from that period rather than tune the model further.

If the interviewer pushes on dataset size, I would say plainly: 38,000 rows is enough for LoRA on a narrow classification task with clean labels, and not enough to train from scratch or to expect the model to learn new domain knowledge. That boundary is what makes the answer credible.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10Why did you describe your transcription-generation agent as especially strong, and what was the standout part?

Reported in ML Engineer interview at Yandex

The 90-second answer

I called it strong because it beat the baseline we had in production on the metric that mattered for the task, not because it sounded fluent. The agent takes noisy meeting audio and produces a transcript with speaker turns and timestamps. On a held-out set of 400 hours of Russian and English calls recorded on laptop mics, it got 11.2% word error rate against 18.4% for the off-the-shelf ASR we started from, and 9.1% against 14.7% on clean studio audio. The gap on noisy audio is the part I pointed to.

The standout part was not the model size. It was the rescoring loop between the acoustic model and a small language model, with a hard constraint that the language model could only reorder hypotheses the acoustic model had already produced. That stopped the generator from inventing plausible words that were never said, which was the main failure mode in our first version.

Yes No Audio chunk 2-4 s ASR lattice top 20 LM rescoring Confidence above 0.72? Emit words plus timestamps Re-decode with wider beam

How it worked

The ASR emitted a lattice, not a single string. Each path carried acoustic log-probabilities and word timings from forced alignment. A 120M parameter language model, fine-tuned on our domain transcripts, rescored only those paths. If the best path still had low confidence, the agent widened the beam from 20 to 80 and rescored again before giving up and marking the span as uncertain.

Python
# Python 3.11, rescoring sketch from the agent
def rescore(paths, lm):
    scored = []
    for p in paths:
        acoustic = p.acoustic_logprob / max(1, len(p.words))
        language = lm.logprob(p.text) / max(1, len(p.words))
        # lambda tuned on dev set, 0.35 favoured acoustics
        score = acoustic + 0.35 * language
        scored.append((score, p))
    return max(scored, key=lambda x: x[0])[1]

A trace from a noisy segment shows why the constraint mattered. Combined score is acoustic plus 0.35 times LM, per word:

Candidate path in latticeAcousticLMCombinedOutcome
"send the invoice to Anna"-1.82-2.10-2.56chosen, highest combined
"send the invoice to Hannah"-2.05-1.74-2.66rejected, lower combined

The unconstrained generator we tried first often produced "send the invoice to Anna tomorrow" for the same audio. That path was not in the lattice at all, because the acoustic model had no support for "tomorrow" in that chunk. With lattice-only rescoring, fluency could not override evidence, so the added deadline never appeared.

What I would defend and what I would not

The latency cost was real. Rescoring 20 paths added about 60 ms per chunk on a single A10, and the wide beam retry pushed p95 from 210 ms to 480 ms for the 12% of chunks that triggered it. We accepted that because the product was offline transcription, not live captions. For live use I would drop the retry and ship the first pass.

The weak spot was code-switching. When a speaker switched from Russian to English mid-sentence, the language model penalised the correct mixed path and WER rose to 16% on that subset. We fixed part of it by training the rescorer on mixed transcripts, but I would not claim the agent handled heavy accents or overlapping speech well. Those cases still went to a human reviewer, and the uncertain-span flag is what made that routing possible.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11Which model version are you using, and how many parameters does it have?

Reported in ML Engineer interview at Yandex

The 90-second answer

I would give the checkpoint identity first and the parameter count second, because the count alone does not let anyone reproduce or roll back the model. My answer sounds like: encoder checkpoint sentiment-encoder/2024-11-18, architecture v3, git commit a91f…, training data snapshot 2024-11-12, tokenizer version tok-7, 110M total parameters, 85M trainable in the last run. If the interviewer wants the number, I can defend how I got it.

Version for a model is not a single integer. I track four things together: architecture and config, weights, data, and preprocessing. Change the tokenizer and the same weights produce different token ids. Change the data snapshot and the same config produces different weights. A version string that omits those is not reproducible.

Where the parameters are

For a concrete example, take a 12-layer transformer encoder with hidden size 768, intermediate size 3072, vocabulary 30522, tied input and output embeddings. Hypothetical figures, but the arithmetic is the point.

ComponentCalculationParameters
---------
Token embeddings30522 x 76823.4M
Per layer attention4 x 768 x 768 plus biases2.36M
Per layer feed-forward768 x 3072 + 3072 x 768 plus biases4.72M
Per layer norms2 x 2 x 7680.003M
12 layers total12 x 7.08M85.0M
Pooling head768 x 7680.59M
Total23.4 + 85.0 + 0.59about 109M

That is the number I would quote, with the split. Total parameters, trainable parameters, and non-trainable buffers are different answers. Batch norm running stats and rotary cache are buffers, not parameters. A frozen backbone during fine-tuning still counts toward serving memory but not toward optimizer state.

Python
# PyTorch 2.x, checked against a standard nn.Module
total = sum(p.numel() for p in model.parameters())
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
for name, p in model.named_parameters():
    print(f"{name:40s} {p.numel()/1e6:8.2f}M trainable={p.requires_grad}")
print(f"total={total/1e6:.1f}M trainable={trainable/1e6:.1f}M")

What the count costs in production

Parameter count converts directly to weight memory and, roughly, to compute. At 109M parameters: fp32 weights are 109M x 4 bytes = 436 MB, fp16 or bf16 are 218 MB, int8 quantized weights are 109 MB before scales and overhead. Optimizer state is the hidden cost during training. AdamW with fp32 master weights, momentum and variance buffers needs about 16 bytes per trainable parameter, so 85M trainable parameters need about 1.36 GB for optimizer and master weights alone, before activations and gradients.

For inference, a dense transformer costs roughly 2 x N FLOPs per token, where N is non-embedding parameters. With 85M non-embedding parameters that is about 170 MFLOPs per token, plus attention over the sequence. That estimate is why I never report parameters without precision and sequence length. A 109M model at fp16 with batch 32 and sequence 512 is a different serving problem from the same model at batch 1.

Failure modes I watch for

Tied embeddings get double counted if I sum embedding and LM head separately. Shared layers get counted once in named_parameters but the FLOP estimate still applies per use. Quantized checkpoints report the original parameter count, so I state the stored dtype alongside it. The most common versioning failure is a checkpoint named final_v2 with no hash, no config, and a tokenizer file overwritten in place. I store the config, tokenizer, and a SHA-256 of the weights in the model registry entry, and I log that hash in every prediction log row. Then an A/B result can be tied to exact weights, and a rollback is a registry lookup rather than a search through a training directory.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12Walk me through how you prepared the data in detail?

Reported in ML Engineer interview at Yandex

The 90-second answer

I would anchor everything on the prediction moment. For a click or purchase model, I define the label window first, for example, did the user purchase within 24 hours after the impression, then I build features only from events with event_time <= prediction_time. Most data bugs I have seen come from breaking that rule, either through a future aggregate or through a user appearing in both train and test with the same future behaviour.

Then I walk through ingestion, cleaning, joining, splitting and validation in that order, because each step changes what the next one can assume.

Raw events and labels Deduplicate and parse Point-in-time feature join Temporal and user split Quality checks and drift report Train

Ingestion and cleaning. Raw logs land in ClickHouse or object storage partitioned by date, with the source event id kept intact. I deduplicate on that id, keeping the last write for mutable fields and the first write for immutable ones, and I log how many rows each rule drops. Parsing is strict: timestamps converted to UTC, currency and units normalised, categorical values mapped through a versioned dictionary, and rows that fail parsing quarantined rather than silently coerced to null. In one past project, hypothetical figures for illustration, 120 million events became 111 million after dedup, and 0.4 percent went to quarantine. That quarantine rate is a metric I watch daily, because a jump usually means an upstream schema change.

Point-in-time join. This is the step I would show in code, because it is where leakage hides.

Python
# Python 3.11, pandas 2.2. Checked against the documented API.
import pandas as pd

labels = pd.read_parquet("labels.parquet")          # user_id, prediction_time, label
features = pd.read_parquet("features.parquet")      # user_id, event_time, clicks_7d, spend_30d

features = features.sort_values("event_time")
joined = pd.merge_asof(
    labels.sort_values("prediction_time"),
    features,
    left_on="prediction_time",
    right_on="event_time",
    by="user_id",
    direction="backward",  # only past events
    tolerance=pd.Timedelta("30d"),
)
assert (joined["event_time"] <= joined["prediction_time"]).all()

The assertion matters more than the join. I also recompute a handful of aggregates offline from raw events and compare them with the online feature store values for the same keys. A mismatch rate above 0.1 percent stops the pipeline.

Worked trace. One user, three events:

user_idevent_timeeventprediction_timeclicks_7d used
4210:00click12:001
4211:30click12:002
4212:30purchase12:002, excluded

The 12:30 purchase must not enter the 12:00 row. If it does, offline AUC looks excellent and production collapses, because at serving time that purchase has not happened yet.

Splitting. I split by time first, for example train on weeks 1 to 8, validate on week 9, test on week 10, and I also keep users disjoint between train and test when the task is about new users. Random splits on event data flatter the model, since the same user and the same session can sit on both sides. I report metrics on both splits and treat a large gap as a leakage signal rather than a modelling win.

Validation and failure modes. Before training I check row counts per day, null rates per column, label rate, and distribution shift with population stability index. PSI above 0.25 on a top feature triggers an investigation. Late arriving events are handled by rebuilding the affected partitions instead of patching rows in place, which keeps the training set reproducible. Deletion requests are applied by rebuilding from raw data with the user excluded, so a deleted user cannot survive inside a precomputed aggregate. If any check fails, the dataset version is not promoted, and the model trains on the last good version while the cause is traced in the quarantine table.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13Walk me through the refactoring from the prototype to a Kafka-based architecture?

Reported in ML Engineer interview at Yandex

The 90-second answer

Prototype first, because the refactor only makes sense against it. A nightly cron read a Postgres table, dumped features to parquet on a shared disk, a training job picked the file up, and the scoring service loaded the model in process and called it over HTTP. That held for a few thousand events a day. It broke in three places: the file was the contract, so a late writer silently truncated training data; scoring and training competed for the same host; and there was no replay, so a bad label could not be reprocessed without asking the source to rebuild history.

The Kafka refactor kept the model and the feature definitions. It changed how data moves. Producers publish events with a stable key, consumers process them independently, and the topic log becomes the replayable source for both training and online inference.

App and clickstream producers Kafka topics: raw events, features, labels Stream consumer: validation and feature join Feature store and training dataset builder Online scoring service Dead letter topic

What actually changed

Topic design followed the consumer, not the source table. I used separate topics for raw events, computed features, and labels, each with its own retention and schema. Partitioning used the entity key, for example user_id, so all events for one user stay ordered in one partition. That ordering matters for a feature join that needs the last click before a purchase. Partition count was set from throughput, not guessed: at 50,000 events per minute with an average 2 KB payload, one partition was the bottleneck in load test, so we ran 12 partitions and kept headroom below 60 percent of a single broker's sustained rate.

Schemas moved into a registry with Avro and backward compatibility enforced in CI. A producer that adds a required field without a default fails the build, not production. Every record carries event_id, event_time, and schema_version in headers. Consumers treat event_id as the idempotency key.

Python
# Python 3.11, confluent-kafka 2.x
from confluent_kafka import Producer
import json

producer = Producer({"bootstrap.servers": "kafka-1:9093,kafka-2:9093", "enable.idempotence": True})

def publish(topic: str, user_id: str, event_id: str, payload: dict) -> None:
    producer.produce(
        topic,
        key=user_id.encode(),
        value=json.dumps(payload).encode(),
        headers=[("event_id", event_id.encode()), ("schema_version", b"3")],
        on_delivery=lambda err, msg: (_ for _ in ()).throw(RuntimeError(err)) if err else None,
    )
    producer.poll(0)

Idempotent production stops duplicate writes from a producer retry. It does not give end to end exactly once, and I would not claim that in the interview. Consumers commit the processed event_id and the business write in one database transaction, then commit the Kafka offset. A redelivery after a crash then finds the id already stored and skips the write.

ConcernPrototypeKafka version
Training dataNightly parquet file, overwrittenTopic replay into dataset builder, 7 day retention
Late or bad labelManual backfill from PostgresReprocess from topic, or read dead letter topic
Scoring loadIn process, shared hostSeparate consumer group, scales by partition
Schema changeDiscovered at training timeRegistry check in CI, consumer rejects unknown version
OrderingFile order, undefinedPer key order within a partition

Retention arithmetic set the disk budget. 50,000 events per minute at 2 KB is about 100 MB per minute, 144 GB per day before compression. Seven days is roughly 1 TB raw, about 350 GB with Snappy at the compression ratio we measured. That number decided retention, not a default of 7 days copied from a tutorial.

Failure modes I would name

Partition skew: one hot user_id or a null key sends everything to one partition. Detection is per partition lag and byte rate, not just total lag. Fix is a composite key or salting for that producer, accepting that per key ordering is lost for salted keys.

Poison pill: one malformed record blocks its partition. The consumer sends it to the dead letter topic after three attempts with the exception and offset in headers, then continues. Without that, consumer lag grows and the alert fires on a single bad record.

Consumer lag during a model rollout: new scoring code reads slower, lag climbs past our 5 minute alert threshold. Because scoring consumers are separate from the feature consumer, training data keeps flowing while scoring catches up. That separation is the main reason for the refactor, more than raw throughput.

I would close by stating the limit: Kafka did not fix label quality or feature leakage. It made bad data visible, replayable, and isolated to one consumer group, which is what the prototype could not do.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14What issues or bottlenecks came up during that refactoring?

Reported in ML Engineer interview at Yandex

The 90-second answer

I refactored a ranking model where feature code lived in three places: the training script, a separate inference service, and a notebook used for backfills. The goal was one shared feature library, versioned with the model. The first bottleneck was not code structure. It was that the three copies had drifted.

Training used a 30-day window for user history, inference used 7 days, and the notebook used calendar days instead of rolling windows. Offline AUC looked fine, online CTR dropped after each deploy, and nobody could tell which copy was right. The second bottleneck was performance. Moving the shared code to a single Python package made it correct but slow, because the old training path had been hand-optimised with in-place arrays and inference had a C++ extension for text features. The third was state. Several functions read global config and mutated a module-level cache, so results depended on call order.

I treated the refactor as a parity problem first and a cleanup second. I froze the old pipeline, built a golden dataset of 50,000 requests with raw inputs and expected feature vectors, and made every new implementation pass exact parity on that set before it replaced anything in production.

Python
# Python 3.11, checked against the shared library
def build_features(raw: RawEvent, cfg: FeatureConfig) -> FeatureVector:
    # Pure function: no globals, no cache mutation, config passed in.
    hist = rolling_window(raw.history, days=cfg.window_days)
    return FeatureVector(
        user_hist_mean=hist.mean(),
        user_hist_count=len(hist),
        text_len=len(raw.text.split()),
        cfg_version=cfg.version,
    )

The pure signature mattered. Once config and window were explicit arguments, the drift above became a test failure instead of a silent metric change.

What actually broke

StageBefore refactorAfter first shared versionFix
------------
------------
------------
------------
Feature parity vs golden set3 divergent copies100% on 50k cases after fixRolling window in one place
Training throughput, 1M rows11 min on 32 CPU cores19 minVectorised the Python loop, kept C++ text path
Inference p99, batch 25642 ms118 msRemoved per-request dict copies, batched serialisation
Online AUC, 7 days shadowbaseline-0.004Found 7-day vs 30-day window bug

The throughput regression is the part people underestimate. The old training code iterated rows in Python but wrote into preallocated NumPy arrays. The first shared version built a dict per row and concatenated lists, which added allocation overhead. At 1M rows that was 8 extra minutes and, on the inference side, pushed p99 from 42 ms to 118 ms at batch 256 because each request paid for Python object creation before the model ever ran. Profiling showed feature building at 71% of inference time, not the model forward pass.

The fix was boring and effective: keep the shared logic, but push the hot loop into NumPy for tabular features and keep the existing C++ extension behind the same interface for text. That brought training back to 12 min and inference p99 to 51 ms, close enough to baseline that we could ship for correctness.

No Yes Raw event Shared feature library Offline training Online inference Golden parity tests Parity passes? Shadow deploy Promote with model version

Failure modes I watched for

Cache invalidation was the nastiest one. The old module-level cache keyed on user id only, so changing the window from 7 to 30 days served stale features until the process restarted. In the new library the cache key includes cfg_version, and the cache is per process with a TTL, not global mutable state.

The second failure mode was version skew between model and features. A model trained with cfg_version=14 served with features from version 15 scored worse without any error. We fixed that by storing the feature config version inside the model artefact and rejecting loads where the serving library cannot satisfy it. That turns a silent AUC drop into a loud startup failure.

The third was backfill divergence. Backfills ran the notebook copy, so historical training data did not match what inference would have produced at the time. After the refactor, backfills call the same library entry point as training, and we re-ran a 90-day backfill and compared feature distributions. Two features shifted by more than 5% in mean, which explained a chunk of the earlier offline-online gap.

If I did it again I would start with the golden set and shadow deploy before touching the old code. The refactoring itself took about three weeks, but most of that time went into parity tests and the shadow comparison, not into moving files around. That ordering is what kept the metric drop to a one-day investigation instead of a production incident.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15How did you detect that the model was degrading?

Reported in ML Engineer interview at Yandex

The 90-second answer

I would not wait for the offline metric to fall. I run three layers in parallel, because each one catches a different failure and each one lies in a different way.

First, input drift: are the features the model sees still the features it was trained on? Second, prediction drift: has the output distribution moved even if I have no labels yet? Third, delayed ground truth: on the slice of traffic where labels have arrived, is AUC, log loss, or calibration actually worse?

If only layer one moves, I suspect a pipeline or upstream change. If layers one and two move together, the world probably changed. If layer three moves while one and two are flat, the label definition or the feedback loop changed, which is the nastiest case.

What I actually monitor

For a ranking or click model at Yandex scale, I would log per feature, per model version, per traffic slice (surface, region, device, new vs returning user): mean and quantiles for numeric features, category share for categoricals, missing rate, and the prediction histogram. Then I compute Population Stability Index (PSI) and a KS statistic against the training window, daily.

PSI = sum over bins of (actual_pct - expected_pct) * ln(actual_pct / expected_pct)

A PSI above 0.10 on a top-20 feature is a warning, above 0.25 is an investigation. Those thresholds are rules of thumb, not laws, so I pair them with a business metric. A feature can drift hard and not matter if the model barely uses it.

Python
# Python 3.11, checked against numpy 1.26
import numpy as np

def psi(expected: np.ndarray, actual: np.ndarray, bins: int = 10) -> float:
    edges = np.quantile(expected, np.linspace(0, 1, bins + 1))
    edges[0], edges[-1] = -np.inf, np.inf
    e, _ = np.histogram(expected, bins=edges)
    a, _ = np.histogram(actual, bins=edges)
    e = np.clip(e / e.sum(), 1e-4, None)
    a = np.clip(a / a.sum(), 1e-4, None)
    return float(np.sum((a - e) * np.log(a / e)))

Worked example, hypothetical but realistic: click-through rate feature ctr_7d in training has mean 0.08. This week the mean is 0.11, PSI is 0.31, and the model score mean moved from 0.12 to 0.19. That alone does not prove degradation. It proves the input changed.

SignalMoves first whenTypical lagCommon false alarm
Feature PSI, missing ratePipeline bug, upstream schema changeMinutes to hoursHoliday traffic, new surface launch
Prediction mean, score quantilesTrue concept drift, feature driftHoursA/B test ramping a new segment
AUC, log loss on labelled sliceReal quality lossDays, label delayLabel definition change, delayed feedback
Calibration (predicted vs actual CTR)Ranking still fine, probabilities brokenDaysPosition bias change in the UI
Business KPI (CTR, conversion, revenue per query)User-visible harmHours to daysSeasonality, competitor event

The trace I would show in an interview

Monday 10:00, PSI on user_age_bucket jumps to 0.42. Missing rate is flat, prediction mean is flat. I check the serving log: a new client version started sending age as 0 for logged-out users. That is a pipeline bug, not model decay. Fix the client, backfill is not needed because the model was robust to that bucket, and no retrain.

Wednesday, PSI on query_length is 0.18, prediction mean rises 6%, and two days later log loss on labelled clicks rises from 0.41 to 0.47 on the mobile slice only. Now layers one, two and three agree. That is real drift, probably a new query pattern. I retrain with recent data weighted higher, keep the old model as fallback, and shadow the new one for 24 hours before promoting.

yes yes yes Serving logs per version and slice Feature PSI and missing rate Prediction distribution Delayed labels PSI high? Score shifted? AUC or log loss down? Check pipeline and schema first Check traffic mix and seasonality Retrain candidate and shadow test

Failure modes I name explicitly

Delayed labels hide decay. For purchases or long sessions, labels arrive 7 to 30 days late, so the labelled slice is biased toward fast converters. I track label arrival rate alongside the metric, and I use a proxy label (early click, early add-to-cart) with a known correlation to the final label, labelled as a proxy in the dashboard.

Feedback loops hide decay the other way. If the model ranks items, it creates its own training data. AUC on logged data can look fine while the model quietly narrows exposure. I keep a small random or exploration slice, even 1% of traffic, so I have unbiased labels to compare against.

Seasonality creates false alarms every week. I compare against the same weekday last week and against a 28-day baseline, not just yesterday. And I never alert on a single metric. My alert fires when two layers move together for a slice that carries at least 5% of traffic, or when calibration error exceeds 0.03 absolute on a high-volume slice.

That combination is what I would defend: fast drift signals to catch pipeline breaks in minutes, prediction signals to catch world changes in hours, and labelled metrics to confirm real loss before I spend a retrain on it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16What train-test split or data proportions did you use?

Reported in ML Engineer interview at Yandex

The 90-second answer

I do not start with a percentage. I start with what the split has to protect against, then pick proportions that leave enough data to train and enough held-out data to measure the metric I will be judged on.

For a tabular classifier with 1 million labelled rows, no time drift and no repeated users, I would use 70% train, 15% validation, 15% test, stratified by label. Train fits the model, validation tunes hyperparameters and thresholds, test is touched once at the end. If the data is ordered in time, for example click logs or search queries, I split by time instead and never shuffle. If the same user, query or document appears more than once, I split by that group so no group appears on both sides.

The ratio is a consequence of dataset size and metric variance, not a default I quote from habit.

How I decide in practice

First question: what would leak? Random shuffling is correct only when rows are independent. With repeated users, near-duplicate texts, or future information in features, a random split inflates offline scores and the model fails in production. In Yandex-scale search and recommendation data this is the common failure: the same query-user pair in train and test, or a feature computed from events after the prediction time.

Second question: how much test data do I need to distinguish two models? For a proportion metric like CTR or accuracy near p=0.5, the standard error is sqrt(p(1-p)/n). With 15,000 test rows that is about 0.4 percentage points. With 1,500 rows it is 1.3 points, so a 0.5 point gain is noise. I size the test set from the smallest difference I care about, then give the rest to train and validation.

Third question: is the dataset small? Below roughly 10,000 rows, a single 15% test set wastes data and gives unstable estimates. I switch to stratified k-fold cross-validation for model selection, typically 5 folds, and keep a final held-out test only if I can afford it. The reported score is then the mean across folds, with the fold spread, not a single lucky split.

SituationSplit I would useWhy
---------
Large i.i.d. tabular data, 1M rows70 / 15 / 15 stratifiedTest of 150k rows gives tight confidence intervals
Time-ordered logsLast 15% by time as test, prior 15% as validationShuffling would train on the future
Repeated users or queriesGroup split by user or query idPrevents memorisation being counted as generalisation
Small dataset, under 10k rows5-fold stratified CV, no separate test or 80 / 20A single small test set has high variance
Rare positive class, 1% positivesStratified split, check counts per splitUnstratified split can leave a fold with almost no positives

Code I would show

Python
# Python 3.11, scikit-learn 1.4
from sklearn.model_selection import train_test_split, GroupShuffleSplit

# Case 1: i.i.d. classification, stratified
X_train, X_tmp, y_train, y_tmp = train_test_split(
    X, y, test_size=0.30, random_state=42, stratify=y
)
X_val, X_test, y_val, y_test = train_test_split(
    X_tmp, y_tmp, test_size=0.50, random_state=42, stratify=y_tmp
)
# Result: 70% train, 15% validation, 15% test

# Case 2: repeated users, no user in two splits
gss = GroupShuffleSplit(n_splits=1, test_size=0.15, random_state=42)
test_idx, rest_idx = next(gss.split(X, y, groups=user_id))

For time-based data I sort by event timestamp, cut at fixed dates, and record those dates in the experiment config. A percentage alone does not reproduce the split six months later.

Failure modes I check before reporting a score

Leakage through preprocessing: fitting a scaler, target encoder or vocabulary on the full dataset before splitting. I fit preprocessing inside the training fold only, ideally in a pipeline.

Distribution mismatch: the test period contains a holiday, a new locale or a changed logging pipeline that train does not. I compare label rate and key feature means across splits and report them alongside the metric.

Test set reuse: tuning the threshold on test, then reporting the same test score. Threshold and hyperparameter choices come from validation. If I look at test more than once, I treat the score as optimistic and say so.

A concrete check: with 1M rows and a 1% positive rate, a 15% test set holds about 1,500 positives. That is enough to estimate AUC to roughly plus or minus 0.01 in practice, but not enough to compare models differing by 0.002. If that difference matters for launch, I enlarge test or use cross-validation on the combined train and validation data and keep test for a final sanity check only.

So my answer in the interview would be: 70/15/15 stratified as the starting point for large i.i.d. data, time or group split when rows are not independent, cross-validation when data is scarce, and the exact proportions justified by the metric variance I need to resolve.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17Did you have any issues with large language model calls taking too long, or was latency not a constraint?

Reported in ML Engineer interview at Yandex

The 90-second answer

Latency was a constraint, and it split into two numbers I had to report separately: time to first token and tokens per second after that. For a chat or agent call, users notice the first token. For batch classification or summarisation, they notice total time. I instrumented both before I optimised anything, because the fixes are different. Prefill, queueing and network delay dominate time to first token. Decode speed, batch size and KV cache pressure dominate the rest.

In one project I served a 7B model behind a Python service. A single request with an 800-token prompt and a 300-token reply took about 6.4 seconds end to end on one A10. Time to first token was 390 ms, then roughly 50 tokens per second. That was fine for an internal tool and unusable once we put it in a synchronous request path with a 2-second deadline. So I moved the call off the critical path where I could, streamed tokens where I could not, and cut decode time with quantisation and continuous batching.

Request arrives Queue wait Prefill: prompt processed First token streamed Decode: one token at a time Done or timeout

What I measured first

I logged prompt tokens, output tokens, queue time, prefill time and decode time per request, then looked at p50, p95 and p99 instead of the mean. The mean hid the problem. At p50 the service looked healthy. At p99, queue wait alone was 3.1 seconds when the batch queue held more than about 40 requests on that GPU. That told me the model was not slow in isolation. The system was slow under load.

A worked trace from that period, figures from my setup:

Phasep50p99 under loadWhat drives it
Queue wait40 ms3,100 msRequests waiting for a free slot
Prefill, 800 prompt tokens350 ms600 msPrompt length, GPU contention
First token (queue + prefill)390 ms3,700 msQueue plus prefill
Decode, 300 output tokens6,000 ms9,000 msBatch size, KV cache, quantisation
Total (first token + decode)6,390 ms12,700 msSum of the above

Once I had that split, the conversation with product changed. We did not need a faster model everywhere. We needed a lower p99 for short interactive calls and a cheaper path for long batch jobs.

What I changed, and when each helps

ChangeEffect in my setupCost or limit
Streaming with a per-token deadlineFirst token visible in under 1 s, user stops waiting on total timeClient must handle partial output and cancellation
Continuous batching via vLLMThroughput rose about 3x at the same GPU, p99 queue wait fellMore complex capacity planning, harder to reason about per-request latency
INT8 quantisation with TensorRT-LLM on the A10Decode went from about 50 to about 90 tokens per secondSmall quality drop on some prompts, needs eval on our data
Shorter prompts and cached prefixesPrefill fell from 350 ms to about 120 ms for repeated system promptsCache invalidation when the prompt template changes
Speculative decodingAbout 1.4x faster decode on short repliesExtra draft model to run and maintain
Moving long jobs to async queueRemoved them from the 2-second request path entirelyUser sees a job ID, not an instant answer

The A10 supports INT8 but not FP8, which needs Ada Lovelace or Hopper hardware. I kept quantisation to INT8 on that fleet and reserved FP8 for a later H100 pool. Streaming alone did not make the model faster. It changed what the user experienced. The client code had to enforce a deadline per token, not just a total timeout, or a stalled stream would hang forever:

Python
# Python 3.11, asyncio async iterator pattern
import asyncio

async def stream_llm(client, prompt, per_token_timeout=5.0):
    stream = client.chat(prompt, stream=True)
    iterator = stream.__aiter__()
    while True:
        try:
            chunk = await asyncio.wait_for(
                iterator.__anext__(), timeout=per_token_timeout
            )
        except StopAsyncIteration:
            break
        yield chunk.text

Here __anext__() returns the awaitable for the next chunk, so wait_for can cancel it if the model stalls mid-reply.

Failure modes I hit

KV cache pressure was the one that surprised me. As batch size grew, each sequence held more cache, and at long context lengths the GPU started swapping or rejecting requests. Throughput looked good in a short benchmark and collapsed at 4k context. I added a max context per tier and routed long prompts to a separate pool with a smaller batch limit.

The second failure was retry storms. When p99 crossed the client timeout, clients retried, which added more load, which pushed p99 higher. I fixed that with a single retry, exponential backoff with jitter, and a circuit breaker that returned a fast 503 instead of queueing requests that would time out anyway.

If I were starting again I would set the latency budget before choosing the model. Interactive path: first token under 1 second at p95, total under 8 seconds. Batch path: optimise cost per thousand tokens, accept minutes. Picking one model and one serving config for both was the original mistake.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18Was the decision to use Kafka already made, or did you choose it based on your experience?

Reported in ML Engineer interview at Yandex

The 90-second answer

I chose it, inside constraints I did not set. The platform team had already standardised on Kafka for event streaming, so the real decision was whether to build the ML pipeline on that standard or ask for an exception. I stayed on Kafka after checking three things: replay for training, ordered updates per entity, and retention long enough to rebuild features without going back to the source database.

If those three had failed, I would have pushed for something else. That is the answer I would defend in the loop: ownership of the trade-off, not just familiarity with the tool.

What I checked before committing

The pipeline had two consumers with different needs. Online inference needed fresh features, usually under a second old. Offline training needed the same events, in the same order, weeks later, to reproduce a dataset exactly. A plain queue gives you the first and loses the second once a message is acknowledged.

Kafka gave me a log I could replay from an offset. I could run a new feature job from offset 0 on a topic without asking producers to resend anything. That mattered more than raw throughput.

CriterionKafkaManaged queue (SQS, RabbitMQ)Direct RPC to a feature service
Replay for retrainingNative, by offset, retention configurableNo, message deleted after ackNo, request is gone
OrderingPer partition, so per user or item keyNot guaranteed across messagesPer call only
Retention in our case7 days on the hot topic, longer on the archive topicHours to days, cost grows fastNone
BackpressureConsumer lag, producers keep writing until disk fillsQueue depth, then producer blocks or dropsCaller blocks or times out
Operational costWe run it, or pay for managed KafkaLowerLowest, until traffic spikes

I ruled out direct RPC for feature updates because a spike in writes would turn into a spike in latency for the read path. I ruled out a queue because we had already been bitten once by a feature bug that needed a 3-day replay. Rebuilding from the transactional database took two days and the rebuilt features did not match production, because some events had been compacted away there.

Sizing, with hypothetical but concrete numbers

Assume 50,000 events per second, 2 KB per event after compression in the log. That is about 100 MB per second, 8.6 TB per day, roughly 60 TB for 7 days before replication. With replication factor 3 that is 180 TB of disk across the cluster. That number is what made the retention discussion real: 7 days was affordable, 30 days on the hot topic was not, so we archived to object storage after 7 days and replayed from there for older training runs.

Partitioning followed the entity key. I used user_id as the key for user features and item_id for item features, so all updates for one entity landed in one partition and stayed ordered. I sized partitions from consumer parallelism: 48 partitions for a consumer group that scaled to 24 instances, so each instance handled two partitions and a rebalance stayed cheap.

How I configured the producer

Python
# Python, confluent-kafka 2.x, checked against the 2.5 client API
producer = Producer({
    "bootstrap.servers": "kafka-1:9093,kafka-2:9093,kafka-3:9093",
    "enable.idempotence": True,
    "acks": "all",
    "min.insync.replicas": 2,
    "compression.type": "zstd",
    "linger.ms": 20,
})
producer.produce(
    topic="user-features-v3",
    key=str(user_id).encode(),
    value=serialize(event, schema_version=3),
)

Idempotent production and acks=all with min.insync.replicas=2 meant a broker loss did not silently drop a feature update. I accepted the extra latency, about 5 to 15 ms in our load test, because a lost update is worse than a slow one: the model keeps serving a stale feature with no error anywhere.

Schema evolution was the other trap. I put a version in the payload and registered it, and consumers rejected unknown versions to a dead-letter topic instead of crashing. One bad producer deploy then poisoned one partition's worth of messages, not the whole consumer group.

Event producers Kafka: user-features-v3 Online feature consumer Offline replay to training set Feature store, Redis Inference service Archive to object storage after 7 days

Failure modes I would name in the interview

Consumer lag is the first signal. I alerted on lag above 5 minutes for the online group, because past that the features are stale enough to move predictions. The second is a hot partition: if one user_id or one celebrity item generates a disproportionate share of events, per-key ordering becomes a bottleneck. The fix there is to split that entity's key or accept that its updates are processed by one consumer, and to watch partition skew in the broker metrics.

The third is a poison message that fails deserialisation on every retry. Without a dead-letter topic and a retry cap, one bad event stalls its partition and lag grows for every user in it. I capped retries at 3, sent the event to the dead-letter topic with the error, and kept the partition moving.

If the interviewer pushes on whether I would choose Kafka again, my answer is conditional. For replayable, ordered, high-volume event streams feeding both online and offline ML, yes. For a simple request-response feature lookup at low volume, no. I would use a database and a cache and skip the cluster entirely.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19What transcription service were you using when it ran out of memory?

Reported in ML Engineer interview at Yandex

The 90-second answer

I was self-hosting Whisper large-v3 through faster-whisper, not calling a hosted transcription API. The worker loaded the large-v3 checkpoint in int8 on a single A100 40 GB, took audio from our transcription-generation agent, and returned timestamped segments.

The OOM was not the weights and it was not a long file making the encoder sequence longer. Whisper always encodes 30 second windows. Audio is padded or truncated to a 30 second mel spectrogram, 3,000 frames, so a 4 minute call becomes eight 30 second windows, each the same encoder size. What grew without a bound was how many of those windows we ran at once, and how long the decoder was allowed to generate for each one.

We had two inference workers sharing one GPU, each accepting a batch of up to 16 windows, with beam search at 5 and no cap on generated tokens. Under load that is 32 windows in flight. Each beam replicates decoder state, and the decoder KV cache grows with generated tokens, not with input audio length. A few windows that fell into a repetition loop generated tokens until the decoder limit instead of stopping at a normal segment end. Activation memory for the batch plus KV cache for long generations pushed the process past 40 GB. The caching allocator held fragmented blocks, so even after a batch finished, free memory was not contiguous enough for the next large batch.

What the trace showed

Hypothetical figures from that incident, labelled as such:

LoadWindows in flightBeamGenerated tokens per windowPeak GPU memoryResult
Normal traffic8580 to 15016 GBOK
Peak, short clips32580 to 15031 GBOK, p99 9 s
Peak, 3 looping windows325400 plus>40 GBOOM, worker killed
After fix, peak81 to 5capped at 22418 GBOK, p99 7 s

Encoder memory stayed flat across those rows. The jump tracked windows in flight multiplied by generated tokens.

The fix

One worker per GPU, so the memory budget is owned by one process. A semaphore limits windows in flight to 8. Batching is by window count, not by file count, because each window costs the same encoder memory. Generation is capped and repetition is treated as a failure, not allowed to run to the decoder limit.

Python
# Python 3.11, faster-whisper 1.x, illustrative worker settings
from faster_whisper import WhisperModel

model = WhisperModel(
    "large-v3",
    device="cuda",
    compute_type="int8_float16",
)

segments, info = model.transcribe(
    "call.wav",
    beam_size=1,              # greedy for long-form, beam 5 only for short clips
    vad_filter=True,          # drop silence, fewer spurious windows
    condition_on_previous_text=False,  # reduces repetition loops
    max_new_tokens=224,       # hard cap per 30 s window
    without_timestamps=False,
)

With beam_size=1 the KV cache is not replicated across beams, which was the largest single saving. I kept beam 5 as an option for short, noisy clips where it improved accuracy measurably, but not as the default for long calls.

Detection and trade-off

I logged torch.cuda.max_memory_allocated() per batch in the PyTorch prototype and nvidia-smi utilisation on the host for the faster-whisper service, alerting above 85 percent of card memory sustained for a minute. After the fix the remaining failure mode is queueing. Capping windows in flight means requests wait instead of crashing the worker, so I added a queue depth limit and returned a retryable error above it. Throughput fell about 15 percent on paper because of the semaphore, but completed requests per hour rose because the worker stopped dying and restarting under peak load.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20Which version of that service were you using?

Reported in ML Engineer interview at Yandex

The 90-second answer

I would name the exact pinned build, not a floating tag. For a model service that means four things together: the model artifact version, the serving code commit, the feature and preprocessing config, and the data snapshot the model was trained on. If I only say "the latest" or "v2", you cannot reproduce a prediction, roll back a bad deploy, or tell whether a quality drop came from the model or from a dependency.

In a Yandex loop I would answer from the registry and the deploy manifest, not from memory. Something like: "At the time of that experiment the service was running ranker-serving:2024-11-18.3, model lgb_ranker_v47 from the model registry, code commit a91f…, feature config features_v12, trained on snapshot 2024-11-10." Then I would show where that is recorded.

What I would actually pin

YAML
# deploy manifest, checked against Python 3.11 / Triton 2.5 in our stack
service: ranker-serving
image: registry.internal/ranker-serving:2024-11-18.3
image_digest: sha256:9c41…e7
model:
  name: lgb_ranker
  version: v47
  artifact_uri: model-registry://lgb_ranker/v47
  artifact_sha256: 77be…10
code_commit: a91f3c2
feature_config: features_v12
preprocessing:
  tokenizer: tok_v8
  normalizer: norm_v3
training_data_snapshot: 2024-11-10
config_hash: 4d2a…

The digest matters more than the tag. A tag like v47 or latest can be overwritten or repointed. The digest and the artifact hash identify the exact bytes that served traffic.

ComponentWhat I stateWhy it changes predictions
Model artifactlgb_ranker/v47, sha256 77be…10Different weights, different scores
Serving codecommit a91f3c2, image digest sha256:9c41…e7Batching, dtype, or a bug fix can shift outputs
Feature configfeatures_v12One renamed or rescaled feature is silent skew
Preprocessingtok_v8, norm_v3Tokenizer changes alter every text feature
Training snapshot2024-11-10Explains which distribution the model saw

How I would trace a live request to that version

Client request Router Ranker serving 2024-11-18.3 Model v47 Feature store features_v12 Log: version, config hash, request id Offline replay

Every log line carries model_version, feature_config, and config_hash. That lets me replay the same request offline and check whether the score matches. If replay differs, I diff code, config, and feature values in that order, because those are the usual sources of drift.

Failure modes I would name

First, training-serving skew. The training pipeline used norm_v3 and serving loaded norm_v2 after a config edit. Scores still returned, latency looked normal, but AUC dropped 0.03 on the next day's slice. The fix was pinning the config hash in both pipelines and failing startup on mismatch.

Second, dependency drift. A minor library upgrade changed a default in preprocessing, for example a tokenizer normalisation step. Pinning only the model version would have missed it. Pinning the image digest catches it.

Third, canary confusion. Two versions serve traffic at once, say 95% v47 and 5% v48. Reporting only "v47" hides the canary slice. I would report the split and the routing rule, such as header or percentage, and compare quality per slice.

If I did not remember the version on the spot, I would say so and retrieve it from the deploy history and the request logs for that timestamp. Guessing a version in an interview, or in an incident, creates a false trail that is worse than admitting I need to look it up.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21Can you elaborate on the observability frameworks you used and how you implemented them?

Reported in ML Engineer interview at Yandex

The 90-second answer

I separate observability into three layers, because each catches a different failure. OpenTelemetry traces show where time went inside one request. Prometheus metrics show whether the service is healthy in aggregate. Model and data monitoring shows whether predictions are still trustworthy after deployment. I used OpenTelemetry with the Python SDK, exported traces to Jaeger and metrics to Prometheus, and visualised both in Grafana. For drift I computed input statistics in the serving path and compared them against the training distribution in a nightly job, rather than trusting accuracy alone, since labels for ranking and recommendation often arrive days late.

Client request API / serving layer Feature fetch Model inference Response OpenTelemetry SDK Jaeger traces Prometheus metrics Grafana dashboards and alerts Prediction log Drift and quality job

Implementation in the serving path

I instrumented once, at the framework boundary, and propagated context through feature fetching and inference. That keeps instrumentation code out of model code.

Python
# Python 3.11, opentelemetry-sdk 1.24, prometheus-client 0.20
from opentelemetry import trace
from prometheus_client import Counter, Histogram

tracer = trace.get_tracer(__name__)
REQUESTS = Counter("model_requests_total", "Requests by outcome", ["model", "status"])
LATENCY = Histogram("model_inference_seconds", "Inference latency", ["model"],
                    buckets=[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5])

def predict(model_name, features):
    with tracer.start_as_current_span("predict") as span:
        span.set_attribute("model.name", model_name)
        span.set_attribute("model.version", "v17")
        span.set_attribute("features.count", len(features))
        with LATENCY.labels(model_name).time():
            out = model.predict(features)  # CatBoost / ONNX session
        REQUESTS.labels(model_name, "ok").inc()
        return out

Traces are sampled at 1% for success and 100% for errors and for latency above 200 ms. At a few thousand requests per second, full sampling would have produced roughly 300 GB of trace data per day in our setup, which made tail latency invisible in storage cost rather than in the code. Head-based sampling alone would have dropped the slow requests I cared about, so I used tail-based sampling in the collector.

What each signal caught

SignalFrameworkConcrete alertWhat it caught in practice
Request rate, error rate, p99 latencyPrometheus + Grafanap99 > 180 ms for 5 min, or 5xx > 1% for 5 minFeature store timeout after a cache eviction, p99 rose from 40 ms to 260 ms
Span duration by stageOpenTelemetry + JaegerFeature fetch span > 100 msOne feature group was fetched serially instead of in parallel
Input driftCustom job, PSI and KS on logged featuresPSI > 0.2 on a top-20 feature for 2 consecutive daysA client changed a categorical encoding, model scores shifted before labels arrived
Prediction distributionLogged predictions vs training baselineMean predicted probability moved > 0.05Calibration drift after a traffic mix change
Delayed label qualityOffline join of predictions and outcomesAUC on mature labels dropped > 0.02 vs shadow modelReal degradation, confirmed only after the label lag

Failure modes I had to fix

Cardinality was the first. I initially labelled metrics by user segment and by raw feature values, which created tens of thousands of time series and slowed Prometheus queries. I kept labels to model name, version and status, and moved high-cardinality fields into trace attributes and logs, where they are searchable but not indexed as series.

The second was silent drift with no label signal. Dashboards looked green because latency and error rate were fine. The drift job compared each production feature against the training snapshot using population stability index, with 0.1 as watch and 0.2 as investigate. That threshold is a heuristic, so I paired it with prediction distribution and with a shadow model scoring the same traffic. When PSI rose but the shadow model agreed, we fixed the upstream pipeline. When both moved, we retrained.

The third was logging cost. Logging full feature vectors for every request was too large and contained user data I should not have stored. I logged feature names, hashes and summary statistics by default, and full vectors only for a 0.1% sample and for error cases, with retention set to 30 days.

If I were starting again I would keep the same split: traces for debugging a single request, metrics for paging, and drift plus delayed labels for deciding whether the model still deserves to serve traffic.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22Which deployment option are you using for the observability framework?

Reported in ML Engineer interview at Yandex

The 90-second answer

Assuming a Kubernetes ML platform on Yandex Cloud, I run a hybrid OpenTelemetry deployment: a DaemonSet agent on every node, plus a central gateway tier that owns sampling, batching and export. I do not run a sidecar per training job or per inference replica, and I do not ship raw telemetry straight to a SaaS endpoint.

The split matters for ML workloads. Training jobs are short-lived, bursty and GPU-bound. Inference replicas are long-lived and latency-sensitive. A sidecar inherits the lifecycle of the pod it sits next to, so a 6-hour training job spawns and kills collectors constantly, and a sidecar in an inference pod competes for CPU on the hot path. A DaemonSet gives one collector per node with a stable identity, and the gateway gives me one place to change sampling policy without redeploying every workload.

Training job / inference pod OTel SDK / Prometheus exporter DaemonSet collector on node Gateway collectors, 3 replicas Yandex Cloud Monitoring / Prometheus remote write ClickHouse via Loki/Tempo-compatible export Grafana for dashboards and alerts

Why this shape, and when I would change it

OptionWhere it fitsCost at ML scaleMain failure mode
DaemonSet agent + gatewayMixed training and serving on K8s, which is our caseOne collector per node, shared batchingNode-level blast radius if the agent OOMs
Sidecar per podOne critical service, strict tenant isolationCollector count equals pod count, churn on every jobCPU contention with inference, config drift across jobs
Direct to SaaS / managed endpointSmall team, no compliance constraint on raw tracesNo gateway to run, per-GB pricingCardinality explosion hits the bill before anyone notices
Standalone gateway only, no agentStatic VMs, no K8sSimpleNo local buffering when the network partitions

The gateway is where the real decisions live. I use tail-based sampling there, not head sampling in the SDK. For inference I keep 100% of errors and p99 traces, and sample successful requests at 5%. For training I drop per-step spans entirely and keep step-level metrics plus one trace per epoch. Head sampling in the SDK would throw away the error trace I need for a bad checkpoint.

Cardinality is the arithmetic that kills ML observability. Suppose 200 GPU nodes each expose 40,000 series at a 15-second scrape interval. That is 8 million series, roughly 533,000 samples per second before labels. If a training framework adds step, batch_id or loss as labels, the series count multiplies by the number of distinct values and Prometheus remote write falls over. I ban high-cardinality labels at the gateway with a metric filter and alert on target_info growth. The same check applies to logs: one training job logging per-sample loss at 10,000 samples per second produces 864 GB per day for a single run.

A minimal gateway config I would show in the interview:

YAML
# otel-gateway.yaml, checked against otelcol-contrib 0.110
receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
processors:
  tail_sampling:
    decision_wait: 5s
    policies:
      - name: errors
        type: status_code
        status_code:
          status: ERROR
      - name: latency
        type: latency
        latency:
          threshold_ms: 500
      - name: sampled-success
        type: probabilistic
        probabilistic:
          sampling_percentage: 5
  batch:
    send_batch_size: 8192
    timeout: 5s
exporters:
  prometheusremotewrite:
    endpoint: https://monitoring.yandexcloud.net/api/v1/write
  clickhouse:
    endpoint: tcp://clickhouse:9000?dial_timeout=10s
service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [tail_sampling, batch]
      exporters: [clickhouse]
    metrics:
      receivers: [otlp]
      processors: [batch]
      exporters: [prometheusremotewrite]

Failure modes I watch

Collector memory is the first. The DaemonSet gets a 512 MiB limit and a queue of 5,000 spans. When the gateway is unreachable, the queue fills, the agent starts dropping with dropped_spans rising, and I alert on that counter rather than on missing dashboards. The second is clock skew between GPU nodes and the gateway, which makes tail sampling wait for spans that already arrived. I run NTP checks in the node readiness probe. The third is silent export failure to Yandex Cloud Monitoring when the service account token rotates. The gateway retries with exponential backoff, and I track exporter_send_failed_requests per exporter so a dead metrics pipeline does not hide behind healthy traces.

If the platform moved off Kubernetes to bare-metal training clusters, I would drop the DaemonSet and run the same gateway config as a systemd unit per node. The gateway tier stays, because sampling and cardinality control should not live inside user training code.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23Did you deploy it locally or expose it through an open-source HTTP server?

Reported in ML Engineer interview at Yandex

The 90-second answer

I started locally, in-process, and moved to an open-source HTTP server when I needed independent scaling and a stable contract. Local means the model object lives in the same process as the caller, so there is no serialization and no network hop. That gave me the lowest latency for a prototype and for batch jobs where the caller already holds the data. It also couples release, scaling and failure domains: a model reload restarts the caller, a slow inference blocks the worker, and you cannot scale GPU inference separately from CPU request handling.

For anything serving live traffic I put the model behind Triton Inference Server (or FastAPI plus Uvicorn if the model is small and CPU bound). The caller sends a versioned request, the server handles batching, queueing, health checks and metrics, and I can deploy a new model version without redeploying the caller. The cost is serialization and one extra hop, typically 1 to 3 ms on localhost for a small payload, which I only accept if the p99 budget allows it.

Assumptions I state up front: a transformer classifier around 120M parameters, FP16 on a single A10, p99 budget of 50 ms, peak load around 400 requests per second. Under those numbers local inference takes about 4 ms per request in isolation. Through HTTP with JSON it takes 6 to 8 ms, with binary protobuf or raw tensor bytes it stays near 5 ms. At 400 rps a single GPU saturates, so the HTTP layer matters because it lets me queue, batch and add a second replica without touching client code.

Python
# FastAPI service, Python 3.11, model loaded once at startup
from fastapi import FastAPI
from pydantic import BaseModel
import torch

app = FastAPI()
model = torch.load("model_v3.pt", map_location="cuda")
model.eval()

class PredictRequest(BaseModel):
    model_version: str
    texts: list[str]

@app.post("/predict")
def predict(req: PredictRequest):
    if req.model_version != "v3":
        return {"error": "unsupported_version", "supported": ["v3"]}
    with torch.no_grad():
        logits = model(req.texts).logits
    return {"probabilities": torch.softmax(logits, dim=-1).tolist()}

In production I would prefer Triton over hand-rolled FastAPI for GPU models. Triton gives dynamic batching, concurrent model instances per GPU and a built-in metrics endpoint. FastAPI is fine when the model is a scikit-learn pipeline or a small ONNX graph on CPU and I want full control over the request schema.

DimensionLocal, in-processOpen-source HTTP server
Latency added0 ms, direct function call1 to 3 ms localhost, more across hosts
ScalingScales with the caller processScales inference replicas independently
BatchingCaller must implement itTriton and TorchServe batch by default
DeploymentCaller and model ship togetherModel versioned and rolled out separately
Failure isolationModel crash kills callerCaller gets a 503 and can retry another replica
ObservabilityCaller logs onlyQueue time, batch size, GPU utilization per model
Client Load balancer Triton replica 1 Triton replica 2 GPU Metrics and health

Failure modes I watch for: schema drift between caller and server, which shows up as 422s after a client deploy, so I version the payload and reject unknown versions explicitly. Queue timeouts under burst load, which show up as p99 climbing while GPU utilization stays flat, so I set a max queue time and return 503 with Retry-After instead of letting requests sit. Cold start after a replica restart, which I handle with a warmup request in the readiness probe. GPU out of memory when batch size spikes, which I cap with a max batch size and test with a load test at twice peak traffic.

If the latency budget were under 5 ms end to end, or the caller is a batch pipeline that already runs on the same host, I would stay local and skip HTTP entirely. The deciding factor is not ideology about services. It is whether independent scaling and deployment are worth the serialization cost for the traffic and SLO in front of me.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24Have you ever had to discuss a decision or requirement change with stakeholders?

Reported in ML Engineer interview at Yandex

The 90-second answer

Yes. On a ranking model for a marketplace search surface, product asked us to add a new requirement mid-sprint: optimise for purchase rate instead of click-through rate, and add a fresh-items boost. I did not argue about the goal. I brought the trade-off in numbers they could decide on, and we changed the launch plan instead of the model spec.

Context, with figures from that project: baseline LightGBM ranker, 340 features, p99 inference 38 ms on CPU, index of 12 million items. The new objective looked better offline. NDCG@10 on clicks was 0.71. On a held-out set labelled with purchases, the same model scored 0.44, and the top-10 contained only 3 purchasable items in 18% of queries because many clicked items were out of stock or had no delivery estimate. Adding purchase labels and stock features moved purchase NDCG to 0.63 in offline replay. That was the part product saw.

The part that changed the decision was cost. Purchase labels arrive with a 7 to 14 day delay, so a model retrained weekly would learn from stale stock. The two new features, stock level and delivery ETA, had to be joined at serving time from a separate store. In a shadow test on 5% of traffic, p99 went from 38 ms to 96 ms, and the feature store timed out on 0.4% of requests. Our serving budget for the whole ranking stack was 120 ms, so we had 24 ms of headroom left for the rest of the pipeline. I showed that trace, not a slide about complexity.

We agreed on a narrower change: keep the click model for the first stage, add a second-stage reranker trained on purchases that only reordered the top 50 candidates, and ship the stock feature as a hard filter for out-of-stock items rather than a learned feature. That kept p99 at 61 ms in the same shadow test and got most of the offline gain.

OptionPurchase NDCG@10 (offline)p99 latencyLabel delayDecision
Ship click model unchanged0.4438 ms1 day (clicks)Rejected, misses the goal
Retrain single model on purchases0.6396 ms7 to 14 daysRejected, too close to budget, stale labels
Two-stage reranker, top 50 only0.5961 ms7 to 14 days, isolated to stage 2Shipped to 5%, then 50%
Hard filter for out-of-stock only0.5241 msNear real timeShipped first, quick win

How the discussion actually went

I started by writing the decision down in one page before the meeting: options, offline numbers, latency trace, and what we would measure online. Product, data, and the serving team each owned one column in that table. That stopped the argument becoming about who was right and made it about which column mattered for this launch.

No Yes Requirement change: optimise purchases Replay offline on purchase labels Shadow test: latency and timeouts Within 120 ms budget? Split into two-stage design Ship to 5 percent Re-test reranker on top 50 Online: purchase rate, p99, timeout rate

Two failure modes came up that I had to name explicitly. First, metric gaming: if we optimised only for purchase rate, the model learned to push expensive items with high margin and click-through fell 6% in simulation. We added a guardrail metric, click NDCG, and agreed to roll back if it dropped more than 2%. Second, feedback loops: purchase labels only exist for items the old model showed, so the new model would never learn about items it suppressed. We kept 2% of traffic on the old ranker as a control and logged propensities for the reranker so offline evaluation could correct for that bias later.

The online result after full rollout: purchase rate up 4.1% relative, click NDCG down 0.8%, p99 at 64 ms, feature store timeouts at 0.02%. Product got the purchase goal, we kept headroom for the next feature, and the decision log meant the next team did not reopen the same argument when someone proposed the single-model retrain again three months later.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25What is your programming language of choice, Python or Node.js?

Reported in ML Engineer interview at Yandex

The 90-second answer

Python. For training, experimentation and offline analysis there is no credible alternative in the Node.js ecosystem, and at Yandex scale that decides it. PyTorch, NumPy, pandas, scikit-learn, ONNX Runtime and the internal tooling around them share one language, one type system for tensors, and one debugging story. I would still use Node.js where it fits: a thin inference API, a streaming feature service, or a product surface the frontend team already owns. The model itself would not live there.

The split I use in production looks like this:

Raw data and labels Python: training and evaluation Export model to ONNX Model registry with version and metrics Python or Node inference service API gateway and clients

Training and export stay in Python because that is where the libraries, GPU kernels and experiment tracking are. The exported ONNX graph is the contract between the two languages. If the Node service loads the same ONNX file, a model change does not require rewriting inference code.

TaskPythonNode.js
---------
---------
---------
Training on GPUPyTorch, JAX, CUDA kernels, distributed launchTensorFlow.js exists, but distributed training and custom ops are immature
Data workpandas, Polars, Arrow, NumPy with zero-copy handoffNo equivalent dataframe stack, manual parsing dominates
InferenceONNX Runtime, TorchServe, Triton clientONNX Runtime Node binding, similar latency for the same graph
Serving glueFastAPI, gRPC, asyncioExpress, Fastify, native async I/O, strong for fan-out
Hiring and reviewEvery ML engineer reads itFrontend engineers read it, ML engineers usually do not

A concrete inference path in Python, the version I would defend in review:

Python
# Python 3.12, onnxruntime 1.19, CPU inference
import numpy as np
import onnxruntime as ort

sess = ort.InferenceSession(
    "model_v42.onnx",
    providers=["CPUExecutionProvider"],
)

def predict(features: np.ndarray) -> np.ndarray:
    # features: float32 array, shape (batch, 128), already normalised
    return sess.run(
        ["probabilities"],
        {"input": features.astype(np.float32)},
    )[0]

The same graph from Node:

JavaScript
// Node.js 20, onnxruntime-node 1.19
const ort = require('onnxruntime-node');

const session = await ort.InferenceSession.create('model_v42.onnx');

async function predict(features) {
  const input = new ort.Tensor('float32', Float32Array.from(features), [features.length / 128, 128]);
  const out = await session.run({ input });
  return out.probabilities.data;
}

Latency for the same graph is comparable, roughly 4 to 8 ms per batch of 32 on a single CPU core in my tests. The difference shows up around the model, not inside it.

Where Node.js wins, and where it breaks

Node wins on I/O fan-out. A gateway that calls a feature store, a cache and a model service in parallel, then merges results, is short and readable in Node. The event loop handles thousands of idle connections without a thread per connection. In Python I would reach for asyncio or a separate gateway for the same shape, and the code is longer.

Node breaks when inference runs on the event loop. ONNX Runtime releases the loop for some ops, but preprocessing in pure JavaScript blocks every request behind it. I have seen p99 jump from 30 ms to over 400 ms when a team added a 128-feature normalisation loop in JS on the request path. The fix is moving preprocessing into the ONNX graph or into a Python worker, at which point Node is only forwarding bytes.

Python breaks in the opposite place. The GIL limits CPU-bound preprocessing across threads, and a single process holding a large model plus a dataframe can exceed memory limits fast. A 7B parameter model in fp16 needs about 14 GB for weights alone, before activations and KV cache. That is a capacity planning problem in either language, but Python teams hit it sooner because training and serving often share a host in prototypes. The production answer is separate processes, Triton or a dedicated inference service, and a hard memory limit per replica.

What I would say about Yandex specifically

I would not frame this as language loyalty. I would say Python for everything that touches data, training and model quality, Node.js only for a thin service layer where the team already ships JS and the model is consumed as an ONNX artifact over gRPC or HTTP. If the interviewer pushes on a single choice for an ML engineer role, the answer is Python, because the work that determines model quality, reproducibility and iteration speed lives there. Node.js is a reasonable choice for the service around the model, and a poor choice for building the model itself.

Curated: · Written: · Reviewed:

Difficulty: Hard

Curated: · Written: · Reviewed: