Category: Build & Trace

  • CD0030 Gini Split From Scratch

    Mode B · Build & Trace 30 Min NumPy + sklearn 4 NumPy Blanks

    Quant research teams that fit gradient-boosted trees on market features spend most of their training time inside one routine, the per-feature split search, which open-source learners such as Microsoft’s LightGBM rebuild around histograms for speed. This screen (reported by candidates from several quant and applied-AI loops) asks you to write the exact version of that routine by hand. You implement best_split for one continuous feature in NumPy, and no tree library may be called inside the function.

    The column x has shape (m,) and the labels y are integers in \{0, \ldots, C - 1\}. Your function returns the threshold t (left child: x \leq t) and its expected information gain under the Gini criterion 1 - \sum_c p_c^2, or (None, 0.0) when no split exists. The interviewer grades three things. Candidates must be midpoints of sorted unique values rather than observed values. The scan must stay at O(m \log m) with no Python loop over classes. Degenerate columns must be handled honestly.

    Complete the 4 missing operations in the skeleton below and trace the array shape after each line. Then verify your routine against a hand-computed two-threshold fixture and cross-check the threshold and gain with a depth-1 sklearn.tree.DecisionTreeClassifier on a toy dataset.

    Skeleton Code (Fill Blanks 1-4):

    01  import numpy as np
    02
    03
    04  def gini(counts: np.ndarray) -> np.ndarray:
    05      """Gini impurity from class counts of shape (..., C)."""
    06      # TODO (Blank 2): 1 - sum_c p_c^2 over the class axis only,
    07      #                 vectorized over any leading axes (no class loop)
    08      impurity = ...
    09      return impurity
    10
    11
    12  def best_split(x, y, n_classes, min_samples_split=2):
    13      """Best Gini threshold for one feature (left child: x <= threshold).
    14      Returns (threshold, gain), or (None, 0.0) when no split exists."""
    15      m = len(x)
    16      # TODO (Blank 1): candidate thresholds, shape (K,), ascending
    17      candidates = ...
    18      # TODO (Blank 4): guard contract, return (None, 0.0) when this node
    19      #                 or this column cannot be split
    20      ...
    21      order = np.argsort(x, kind="stable")
    22      x_sorted, y_sorted = x[order], y[order]                     # (m,)
    23      parent_counts = np.bincount(y_sorted, minlength=n_classes)  # (C,)
    24      parent_gini = gini(parent_counts)
    25      # TODO (Blank 3): weighted Gini gain of all K candidates in one
    26      #                 vectorized pass (no Python loop), shape (K,);
    27      #                 best = argmax index, ties go to the lowest threshold
    28      gains = ...
    29      best = ...
    30      return float(candidates[best]), float(gains[best])
    Operator contract for best_split: input columns x and y of shape (m,) flow through a question-marked candidate step, a provided argsort, a question-marked Gini gain step, and a question-marked argmax step to an output pair of threshold and gain; below, boxes list the guard contract, the O(m log m) budget, and the two test oracles

    Figure 1: the input and output contract is fixed and the sort is provided, while the question-marked steps between them are yours to write in plain NumPy.

    Interactive NumPy Workspace: Switch to the split-screen workspace to fill Blanks 1-4 in the live editor and run the fixture and sklearn checks.

    Open in Colab ↗
    Progressive Hints (Free · Zero Spoilers)
    1Inspection Checklist (Where to Look)

    (1) Candidate Set: A useful threshold must change the partition. Count how many distinct partitions x <= t can produce, and make sure no candidate leaves a child empty.
    (2) Impurity on Counts: The helper receives class counts, both as one (C,) row and as a (K, C) table. Reduce over the class axis only.
    (3) Scan Budget: Count how many full passes over the m rows your scan makes. The budget is one sort plus a constant number of linear passes, with no Python loop.
    (4) Degenerate Inputs: List the inputs for which no honest threshold exists, and return (None, 0.0) for them before anything divides or indexes.

    2Visual Review Map (Figure 2)
    Shape trace for best_split: the top row marks the target shape of Blank 1 as (K,) and a question-marked Blank 4 early exit before the provided sort and the parent class counts of shape (C,); the bottom row shows question-marked target shapes for child counts (K, C), child Gini (K,), gains (K,), the best index, and the output pair

    Figure 2: The shape trace a strong candidate narrates aloud. Every blank shows the target shapes it must produce; writing the operations that reach them is the exercise.

    3Interviewer Nudge & Line Focus

    Pin the input shape, output shape, and failure inputs of each blank before writing the NumPy call:

    Blank 1 (Candidate Thresholds): For x = [2, 2, 5, 9], which thresholds produce genuinely different partitions under x <= t, and how many are there? If you used t = 9, what size would the right child have when you later divide by it?
    Blank 2 (Gini on Counts): The helper is called once with (C,) for the parent and once per side with (K, C) for every candidate. Which axis must each row be normalized over, and what does a reduction without an axis argument return for the table case?
    Blank 3 (One-Pass Scan): After sorting, which rows belong to the left child of the k-th candidate? If you had running class counts down the sorted order, how would you read off every left child at once, and how would you get the right child without rescanning? When two gains tie to the last bit, which index does your selection return?
    Blank 4 (Guard Contract): List every input where the scan would index an empty array or reduce over zero candidates, plus the input where every gain is exactly 0. In which order must the checks run so none of them can itself raise?
    Answer
    Login to view more content
  • CD0027 AUC-ROC From Scratch

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • CD0025 MLP Backprop From Scratch

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • CD0022 Softmax Cross-Entropy

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • CD0014 Masked Self-Attention

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • CD0013 KNN Array Query

    Mode B · Build & Trace 30 Min NumPy 4 Array Blanks

    A Google data-quality job runs two measurement pipelines that log integer readings of the same quantity — a source-attribution task reported from a Google AI/ML coding round in November 2025. Source A is a tightly calibrated sensor, while source B is a cheap sensor with a much wider spread. A stream of new readings arrives without provenance, and for each one you must decide which source more likely produced it. Naive nearest-distance reasoning picks the wrong source, so the brief asks you to handle ties explicitly and to compare at least two assignment strategies.

    You receive A of shape (n_A,), B of shape (n_B,), and queries of shape (Q,), all integer arrays whose dtype is not guaranteed to be signed. Label 0 means source A and label 1 means source B. You may use NumPy only: scikit-learn neighbors, scipy.spatial.distance.cdist, and a Python loop over queries are all off limits. The batched driver returns four arrays of shape (Q,): the kNN labels, the kNN vote margin (share of B votes minus share of A votes, in absolute value, so it lies in [0, 1]), the z-score labels, and the z-score gap |z_A - z_B|.

    Complete the 4 missing pieces in the skeleton below and trace the exact array shape after each line. Then argue which strategy is more defensible when one source is much noisier than the other, and verify your module on a synthetic two-source fixture with known ground truth.

    Skeleton Code (Fill Blanks 1-4):

    01  import numpy as np
    02
    03
    04  def pairwise_dist(queries, pool):
    05      # TODO (Blank 1): |queries_i - pool_j| for every query/pool pair, float (Q, N)
    06      dists = ...
    07      return dists
    08
    09
    10  def knn_vote(dists, pool_labels, k):
    11      # TODO (Blank 2): majority label among the k nearest pool points per row;
    12      #                 a tied vote falls back to the single nearest label
    13      pred, frac_b = ...
    14      return pred, frac_b                     # (Q,) int, (Q,) share of B votes
    15
    16
    17  def zscore_assign(queries, A, B, eps=1e-12):
    18      # TODO (Blank 3): |queries - mean| per source, scaled by that source std (ddof=0)
    19      z_A, z_B = ...
    20      return (z_A > z_B).astype(int), z_A, z_B    # 1 = source B, z tie goes to A
    21
    22
    23  def classify(queries, A, B, k=5):
    24      A, B = np.asarray(A, float), np.asarray(B, float)
    25      pool_labels = np.concatenate([np.zeros(len(A)), np.ones(len(B))]).astype(int)
    26      # TODO (Blank 4): all queries at once (no Python loop), labels + margins
    27      knn_pred, knn_margin, z_pred, z_margin = ...
    28      return knn_pred, knn_margin, z_pred, z_margin
    Operator contract for the two-source query classifier: an inputs box holding source arrays A and B plus the query stream feeds two question-marked branches, pairwise distances followed by a kNN vote with a tie rule, and a scale-aware score per source; both branches feed a question-marked step that returns labels and margins for every query. Below, boxes list the forbidden library calls, the allowed NumPy building blocks, and the test oracle

    Figure 1: the inputs and the four returned arrays are fixed, and the two assignment strategies run side by side. Every question-marked step is yours to write in plain NumPy.

    Interactive NumPy Workspace: Switch to the split-screen workspace to fill Blanks 1-4 in the live editor and run the hidden kNN and z-score checks.

    Open in Colab ↗
    Progressive Hints (Free · Zero Spoilers)
    1Inspection Checklist (Where to Look)

    (1) Broadcast Axes: Decide which axis indexes queries and which indexes pool points before you subtract, and check what integer dtype the readings arrive in.
    (2) Row-Wise Neighbors: The k nearest points must be chosen independently for every query row, and equal distances need an order that is identical on every run.
    (3) Scale Contract: Each source distance must be measured in that source’s own spread, including a source whose readings never vary.
    (4) Batch Contract: One vectorized pass over all queries, labels aligned with the pool order, a neighbor count that may exceed the pool, and margins computed per query.

    2Visual Review Map (Figure 2)
    Shape trace for the two-source classifier: the top row marks the target shapes of Blanks 1 and 2, from the query and pool vectors to a question-marked (Q, N) distance matrix, a question-marked (Q, k) neighbor set, and per-query outputs; the bottom row marks the target shapes of Blanks 3 and 4, from the sources to per-query standardized distances, per-query margins, and four returned arrays of shape (Q,)

    Figure 2: The shape trace a strong candidate narrates aloud. Every blank shows the target shapes it must produce, and writing the NumPy ops that reach them is the exercise.

    3Interviewer Nudge & Line Focus

    Pin the input shape, output shape, and dtype of each blank before writing the NumPy op:

    Blank 1 (Pairwise Distances): queries is (Q,) and pool is (N,). Which axis must each array gain so the subtraction broadcasts to (Q, N), and what silently happens instead when Q == N? If both arrays arrive as uint8 sensor counts, what does 3 - 5 evaluate to?
    Blank 2 (kNN Vote + Tie Rule): Along which axis does argsort sort a (Q, N) matrix by default, and does slicing its result with [:k] keep the first k rows or the first k columns? With k = 4 and a 2-2 split, which single neighbor should decide, and which sort kind keeps equal integer distances in pool order on every run?
    Blank 3 (Scale-Aware Score): Source A has std 2 and source B has std 15. A query sits 8 units from mean A and 12 units from mean B: what are the two standardized distances, and does the winner differ from the raw-distance winner? What does your expression return when every reading of a source is identical?
    Blank 4 (Batched Driver + Margins): In which order must A and B be concatenated so the pool lines up with labels on line 25? What should happen when k exceeds n_A + n_B, and how many distinct values can the vote margin take for a fixed k?
    Answer
    Login to view more content
  • CD0011 Linear Regression Closed Form

    Mode B · Build & Trace 30 Min NumPy 1.24+ 4 Linear-Algebra Blanks

    Amazon’s delivery-time estimation team keeps its baseline deliberately boring: a closed-form least-squares fit over package and route features, written in raw NumPy so ops analysts can audit every coefficient without a sklearn dependency. Each row of X holds n numeric package and route features, and y is the observed delivery time in hours. You must implement ordinary least squares with an intercept in NumPy using the closed-form normal equation. scikit-learn, np.polyfit, and any gradient-descent loop are off limits.

    The input X has shape (n_samples, n_features) with m rows and n features, and y has shape (n_samples,). Your function must return the coefficient vector beta of shape (n_features + 1,) with the intercept stored first, the in-sample predictions, and the coefficient of determination R^2. Expect the interviewer to push on numerical stability and on what your code does when the design matrix is singular.

    Complete the 4 missing operations in the skeleton below and trace the exact array shape after each line. Then verify your fit against np.linalg.lstsq with np.testing.assert_allclose, estimate the flop and memory cost for a million-row training set, and explain when the closed form fails and what you would use instead.

    Skeleton Code (Fill Blanks 1-4):

    01  import numpy as np
    02
    03
    04  def fit_ols(X: np.ndarray, y: np.ndarray):
    05      """Closed-form OLS with intercept. X: (n_samples, n_features), y: (n_samples,)."""
    06      X = np.asarray(X, dtype=np.float64)
    07      y = np.asarray(y, dtype=np.float64).ravel()
    08      n_samples, n_features = X.shape
    09      # TODO (Blank 1): prepend an intercept column of ones
    10      #                 X_design has shape (n_samples, n_features + 1); column 0 is the bias
    11      X_design = ...
    12      # TODO (Blank 2): solve the normal equations for beta, shape (n_features + 1,)
    13      #                 must still return a beta when X is rank-deficient
    14      beta = ...
    15      # TODO (Blank 3): in-sample predictions and residuals, both (n_samples,)
    16      y_hat = ...
    17      resid = ...
    18      # TODO (Blank 4): coefficient of determination R^2 (scalar)
    19      r2 = ...
    20      return beta, y_hat, r2
    21
    22
    23  def predict(beta: np.ndarray, X_new: np.ndarray) -> np.ndarray:
    24      """Apply fitted beta (intercept first) to new rows X_new: (k, n_features)."""
    25      X_new = np.asarray(X_new, dtype=np.float64)
    26      return beta[0] + X_new @ beta[1:]
    Operator contract for closed-form OLS: inputs X of shape (n_samples, n_features) and y of shape (n_samples,) flow through four question-marked steps labeled Blank 1 to Blank 4 into outputs beta of shape (n+1,), y_hat of shape (n_samples,), and a scalar r2; below, boxes list the forbidden tools, the allowed NumPy building blocks, and the np.linalg.lstsq test oracle

    Figure 1: The input and output contract is fixed, and the four linear-algebra steps in between are yours to write with plain NumPy.

    Interactive NumPy Workspace: Switch to the split-screen workspace to fill Blanks 1-4 in the live editor and verify against the least-squares oracle.

    Open in Colab ↗
    Progressive Hints (Free · Zero Spoilers)
    1Inspection Checklist (Where to Look)

    (1) Intercept Convention: Line 26 reads the bias from beta[0], so the augmented design must agree with that column order and have shape (n_samples, n_features + 1).
    (2) Linear-System Route: Decide which NumPy routine handles the (n + 1) \times (n + 1) system with the fewest flops and the smallest error, and what it does when the system is singular.
    (3) Residual Geometry: For a correct fit with an intercept, the residuals are orthogonal to every design column and sum to zero.
    (4) Baseline for R-Squared: The score compares your fit against a model that always predicts the mean of y; check that it gives 1 for a perfect fit and 0 for a mean-only fit.

    2Visual Review Map (Figure 2)
    Shape trace for fit_ols: the top row marks the target shapes of Blanks 1 and 2, from inputs X (n_samples, n_features) and y (n_samples,) to an (n_samples, n_features+1) design, an (n_features+1, n_features+1) system, and beta of shape (n+1,); the bottom row marks the target shapes of Blanks 3 and 4, y_hat and resid of shape (n_samples,) and a scalar r2, each with a question mark in place of the operation

    Figure 2: The shape trace a strong candidate narrates aloud. Every blank shows the target shapes it must produce, and writing the operations that reach them is the exercise.

    3Interviewer Nudge & Line Focus

    Pin the exact input and output shape of each blank, and answer the check, before writing the NumPy call:

    Blank 1 (Bias Column): np.ones(n_samples) is 1-D with shape (n_samples,) while X is 2-D. Which NumPy constructor stacks a 1-D vector as a column without an explicit reshape, and on which side must it go so that predict() reads the intercept, not a slope, from beta[0]?
    Blank 2 (Normal-Equation Solve): The system matrix is only (n_features + 1, n + 1). Does computing its inverse and then multiplying cost more or fewer flops than factoring it once, and which route has the smaller error when the matrix is ill-conditioned? What should your code do when the factorization hits an exactly zero pivot?
    Blank 3 (Predictions & Residuals): Which matrix-vector product gives shape (n_samples,)? If y had arrived as an (n_samples, 1) column, what shape would y - y_hat silently broadcast to, and which earlier line already protects you?
    Blank 4 (R-Squared): Your score divides one sum of squares by another. Is the denominator built from y itself or from y after removing its mean, and what does your expression return when every target in the batch is identical?
    Answer
    Login to view more content
  • CD0010 K-Means From Scratch

    Mode B · Build & Trace 30 Min NumPy 4 Array Blanks

    Clustering prototypes show up constantly on Google and Waymo ML teams, and this screen (reported by candidates from both companies' coding rounds) rewards the same habit: writing a few lines of vectorized NumPy that stay correct when the data misbehaves. You must implement KMeans.fit(X, k) from scratch. It takes a float array of shape (n_samples, n_features) and returns integer cluster labels of shape (n_samples,) and centroids of shape (k, n_features). Calling sklearn.cluster.KMeans, scipy.cluster.vq, or scipy.spatial.distance.cdist is forbidden.

    Initialization is fixed for this round: k distinct rows of X drawn at random, with k-means++ left as a follow-up. The interviewer cares less about the happy path than about three edge cases. A cluster can come out empty mid-run, the loop needs a defensible stopping rule, and a correct implementation must preserve specific invariants on every iteration.

    Complete the 4 missing operations in the skeleton below and narrate the array shape after each line. Then state the algorithm's time complexity, explain how you would choose k, and write a test that checks invariants rather than one hand-picked output.

    Skeleton Code (Fill Blanks 1-4):

    01  import numpy as np
    02
    03
    04  class KMeans:
    05      def __init__(self, max_iter: int = 100, tol: float = 1e-6, seed: int = 0):
    06          self.max_iter, self.tol = max_iter, tol
    07          self.rng = np.random.default_rng(seed)
    08
    09      def fit(self, X: np.ndarray, k: int):
    10          n_samples, n_features = X.shape                    # X: (n_samples, n_features) float64
    11          centroids = X[self.rng.choice(n_samples, size=k, replace=False)]   # (k, n_features)
    12          self.inertia_history = []
    13          for it in range(self.max_iter):
    14              # TODO (Blank 1): squared distances from every point to every
    15              #                 centroid, shape (n_samples, k), no Python loops
    16              sq_dists = ...
    17              # TODO (Blank 2): index of the nearest centroid per point, (n_samples,)
    18              labels = ...
    19              self.inertia_history.append(sq_dists[np.arange(n_samples), labels].sum())
    20              prev_centroids = centroids.copy()
    21              # TODO (Blank 3): recompute each centroid as the mean of its
    22              #                 points; an empty cluster must stay finite
    23              ...
    24              # TODO (Blank 4): stop when the centroids have converged
    25              if ...:
    26                  break
    27          self.centroids_, self.labels_, self.n_iter_ = centroids, labels, it + 1
    28          return labels, centroids
    Operator contract for KMeans.fit: input X of shape (n_samples, n_features) with k random rows as initial centroids flows through four question-marked steps (Blank 1 distances, Blank 2 assignment, Blank 3 centroid update, Blank 4 stop check) with a loop back for the next iteration, ending at labels (n_samples,) and centroids (k, n_features); below, three boxes list the edge cases the interviewer probes

    Figure 1: the input and output contract is fixed, the random-row initialization is given, and the four steps inside the Lloyd loop are yours to write, with the interviewer probing empty clusters, the stopping rule, and the loop's invariants.

    Interactive NumPy Workspace: Switch to the split-screen workspace to fill Blanks 1-4 in the live editor and run the invariant checks.

    Open in Colab ↗
    Progressive Hints (Free · Zero Spoilers)
    1Inspection Checklist (Where to Look)

    (1) Broadcast Geometry: Align the point axis of X and the centroid axis of centroids so one subtraction covers every pair, then reduce over the feature axis only.
    (2) Reduction Axis: The assignment must produce one label per point, and line 19 indexes sq_dists with exactly that shape.
    (3) Empty-Cluster Contract: Decide what a centroid with zero members should be before writing the update, and keep every centroid finite.
    (4) Stopping Rule: Compare the updated centroids with the snapshot on line 20 using an explicit tolerance, and remember that line 13 is the second guard.

    2Visual Review Map (Figure 2)
    Shape trace for KMeans.fit: X (n_samples, n_features) and centroids (k, n_features) feed question-marked blanks whose target shapes are an intermediate (n_samples, k, n_features), sq_dists (n_samples, k), labels (n_samples,), new centroids (k, n_features), and a boolean stop flag; the line 19 inertia and the line 20 prev_centroids snapshot are shown as given, with a loop back to Blank 1 for the next iteration

    Figure 2: The shape trace a strong candidate narrates aloud. Every blank shows the target shape it must produce; writing the operations that reach them is the exercise.

    3Interviewer Nudge & Line Focus

    Pin the input shape, output shape, and failure mode of each blank before writing the NumPy call:

    Blank 1 (Distance Matrix): X is (n_samples, n_features) and centroids is (k, n_features). Which singleton axes must you insert so the subtraction broadcasts to a 3-axis tensor, and which axis do you reduce? If n_samples == k, what does a plain X - centroids silently compute instead of raising?
    Blank 2 (Assignment): sq_dists is (n_samples, k). Does the reduction collapse the point axis or the centroid axis, what shape would the other choice produce, and which index wins when two centroids sit at exactly the same distance?
    Blank 3 (Centroid Update): If X contains duplicate rows, two initial centroids can be identical. What does averaging a (0, n_features) array return, what happens to the next distance matrix once one centroid holds that value, and which two finite choices could you make instead?
    Blank 4 (Convergence): Lloyd's algorithm visits finitely many partitions, so why still compare against a tolerance in the data's units, and why does line 13 keep its bound even when your stop check is correct?
    Answer
    Login to view more content
  • CD0009 Logistic Regression From Scratch

    Mode B · Build & Trace 30 Min NumPy Only 4 Operation Blanks

    Waymo’s driving-log triage team scores each recorded segment with a small calibrated classifier that decides whether it should be routed to human review. The classifier is a binary logistic regression built from first principles in NumPy only: importing scikit-learn, PyTorch, JAX, or any autograd library is forbidden, so every derivative must come from your own derivation.

    The feature matrix X has shape (n_samples, n_features) and the label vector y has shape (n_samples,) with entries in \{0, 1\}. Your LogisticRegression class must train with full-batch gradient descent under a fixed learning rate and epoch budget, and expose fit(X, y), predict_proba(X), and predict(X, threshold=0.5). The interviewer will check your gradient derivation on paper before you run anything.

    Complete the 4 missing operations in the skeleton below: a numerically stable sigmoid, the forward pass, the vectorized gradient of binary cross-entropy with respect to w and b, and the parameter update with loss logging. Then verify convergence on a linearly separable synthetic set, and explain how you would confirm your gradients with finite differences.

    Skeleton Code (Fill Blanks 1-4):

    01  import numpy as np
    02
    03
    04  def sigmoid(z: np.ndarray) -> np.ndarray:
    05      # TODO (Blank 1): elementwise 1 / (1 + exp(-z)) that stays finite
    06      #                 and emits no overflow warning for any finite z
    07      return ...
    08
    09
    10  class LogisticRegression:
    11      def __init__(self, lr: float = 0.1, epochs: int = 1000):
    12          self.lr, self.epochs = lr, epochs
    13          self.w, self.b, self.losses = None, 0.0, []
    14
    15      def predict_proba(self, X: np.ndarray) -> np.ndarray:
    16          # TODO (Blank 2): forward pass, X (n_samples, n_features) -> p (n_samples,) in [0, 1]
    17          p = ...
    18          return p
    19
    20      def predict(self, X: np.ndarray, threshold: float = 0.5) -> np.ndarray:
    21          return (self.predict_proba(X) >= threshold).astype(int)
    22
    23      def fit(self, X: np.ndarray, y: np.ndarray) -> "LogisticRegression":
    24          n_samples, n_features = X.shape
    25          self.w, self.b, self.losses = np.zeros(n_features), 0.0, []
    26          for _ in range(self.epochs):
    27              p = self.predict_proba(X)                     # (n_samples,)
    28              # TODO (Blank 3): mean-BCE gradients dw (n_features,) and db (scalar)
    29              dw, db = ...
    30              # TODO (Blank 4): update w and b; append mean BCE to self.losses
    31              ...
    32          return self
    Operator contract for NumPy logistic regression: inputs X of shape (n_samples, n_features) and y of shape (n_samples,) flow into three question-marked steps (sigmoid plus forward pass, BCE gradients for w and b, update step with loss logging) that repeat for the epoch budget, ending in trained w and b used by predict_proba and predict; bottom boxes list the forbidden libraries, the allowed NumPy building blocks, and the two checks

    Figure 1: The input contract is fixed: X of shape (n_samples, n_features) and y of shape (n_samples,) go in, and trained w, b come out. The three question-marked steps inside the epoch loop are yours to write with NumPy alone.

    Interactive NumPy Workspace: Switch to the split-screen workspace to fill Blanks 1-4 in the live editor and run the convergence and gradient checks.

    Open in Colab ↗
    Progressive Hints (Free · Zero Spoilers)
    1Inspection Checklist (Where to Look)

    (1) Overflow-Free Sigmoid: Ask which logits can make the argument of np.exp large and positive, and remember that np.where computes both branch arrays before it selects.
    (2) 1-D Forward Pass: Probabilities must come out with shape (n_samples,) and a scalar bias broadcast across them, never as an (m, 1) column.
    (3) Mean-Reduced Gradient: Derive \partial \mathcal{L} / \partial z on paper before coding; dw must be (n_features,) and both gradients must use the same averaging as the loss.
    (4) Descent Step and Safe Logging: Move against the gradient, and make sure a probability that rounds to exactly 0 or 1 cannot turn the logged loss into inf or nan.

    2Visual Review Map (Figure 2)
    Shape trace for logistic regression: the forward row goes from X (n_samples, n_features) with w (n_features,) and scalar b through Blank 2 logits (n_samples,) and Blank 1 probabilities (n_samples,) to a comparison with y (n_samples,); the backward row goes through Blank 3 gradients dw (n_features,) and scalar db, Blank 4 updated w and b, a logged scalar loss, and loops back for the next epoch; every operation is a question mark

    Figure 2: The shape trace a strong candidate narrates aloud. Every blank shows the target shapes it must produce; the operations that reach them are the exercise.

    3Interviewer Nudge & Line Focus

    Answer each Socratic check with a shape or a number before you type the NumPy line:

    Blank 1 (Stable Sigmoid): In float64, what does np.exp(1000.0) return, and what does exp(z) / (1 + exp(z)) evaluate to at z = +1000? Can you find a single exponent argument that is safe for both signs of z, given that np.where evaluates every branch?
    Blank 2 (Forward Pass): X is (n_samples, n_features) and self.w is (n_features,). What shape does their product have, and what shape would p take if w had been stored as an (n, 1) column instead?
    Blank 3 (BCE Gradients): Multiply the derivative of the per-example loss with respect to p by the derivative of the sigmoid. What does the product simplify to, which matrix maps an (n_samples,) residual to an (n_features,) gradient, and what must you divide by so the gradient matches a mean loss?
    Blank 4 (Update + Logging): If the logged loss rises every epoch, which sign did you flip? And in float64, what does np.log(1 - p) return once a confident logit makes p round to exactly 1.0 (around z = 37)?
    Answer
    Login to view more content
  • CD0004 Rotary Position Embedding Implementation

    Mode B · Build & Trace 30 Min PyTorch 2.x · FP32/BF16 4 Tensor Blanks

    Meta's GenAI org develops the Llama model family, whose rotary position encoding every Llama inference kernel depends on. In a foundation-model coding interview for that stack, you are asked to implement Rotary Positional Embedding (RoPE) from scratch in PyTorch, exactly as Llama 3 uses it with base b = 500000, and without any HuggingFace transformers utilities. The inputs are query and key tensors of shape (B, H, T, D) with an even head dimension D. You also get an explicit position_ids tensor of shape (B, T), so the same code serves KV-cached decoding and left-padded batches.

    You must precompute the inverse frequency band inv_freq, build the cosine and sine tables for arbitrary position_ids, and apply the 2D pairwise rotation to q and k in real-valued FP32 arithmetic before casting back to the input dtype. Forbidden: transformers helpers such as apply_rotary_pos_emb, and complex-number shortcuts (torch.view_as_complex, torch.polar) inside the implementation. Output shapes and dtypes must equal the inputs, and the table must cost O(BTD) memory with no per-head copies.

    Fill in the 4 core tensor operations in the skeleton and trace the broadcasting shapes from (D/2,) and (B, T) to (B, 1, T, D). Then explain why building cos and sin in BF16 corrupts long-context positions, and write a test confirming that \langle \mathrm{RoPE}(q, m), \mathrm{RoPE}(k, n) \rangle depends only on the offset m - n.

    RoPE Skeleton (Fill Blanks 1–4):

    01  import torch
    02  # Real-valued FP32 rotation only: no transformers helpers, no view_as_complex.
    03
    04
    05  class RotaryEmbedding(torch.nn.Module):
    06      def __init__(self, head_dim: int, base: float = 500000.0):
    07          super().__init__()
    08          assert head_dim % 2 == 0, "RoPE needs an even head_dim"
    09          # TODO (Blank 1): inv_freq of shape (D // 2,), computed in FP32
    10          inv_freq = ...
    11          self.register_buffer("inv_freq", inv_freq, persistent=False)
    12
    13      @torch.no_grad()
    14      def forward(self, position_ids: torch.Tensor):
    15          # position_ids: (B, T) int64 -> cos, sin: (B, 1, T, D) in FP32
    16          # TODO (Blank 2): per-token angles, widened to D, plus a head axis
    17          emb = ...
    18          return emb.cos(), emb.sin()
    19
    20
    21  def rotate_half(x: torch.Tensor) -> torch.Tensor:
    22      # x: (B, H, T, D) -> (B, H, T, D)
    23      # TODO (Blank 3): rotate each channel pair by 90 degrees
    24      ...
    25
    26
    27  def apply_rope(q, k, cos, sin):
    28      # q, k: (B, H, T, D) any float dtype; cos, sin: (B, 1, T, D) FP32
    29      # TODO (Blank 4): rotate in FP32, then cast back to the input dtype
    30      q_out = ...
    31      k_out = ...
    32      return q_out, k_out
    Operator contract for RoPE: q and k of shape (B, H, T, D) in bf16 and position_ids of shape (B, T) feed a RoPE core marked with a question mark, which outputs rotated q and k with the same shape and dtype; a note states the goal that the attention score depends only on m minus n

    Figure 1: two activation tensors and a position map go in, and rotated tensors with the same shape and dtype come out. The tensor plumbing in the middle is yours to write.

    Interactive PyTorch Workspace: Switch to the split-screen workspace to implement RoPE Blanks 1-4 and run relative-offset and 100k-context BF16 checks.

    Open in Colab ↗
    Progressive Hints (Free · Zero Spoilers)
    1Inspection Checklist (Where to Look)

    (1) Frequency Band: Build D/2 inverse frequencies with even exponents 2i/D in FP32.
    (2) Explicit Positions: Compute per-token angles directly from position_ids rather than arange(T) so cached decode and left-padding work.
    (3) Broadcast Over Heads: Keep the cos/sin tables at shape (B, 1, T, D) so memory does not scale with H.
    (4) FP32 Rotation Boundary: Pair (i, i + D/2) consistently, rotate in FP32, and cast back to the input dtype only at the end.

    2Visual Review Map (Figure 2)
    Shape trace diagram: Blank 1 produces inv_freq of shape (D/2,) in FP32, position_ids of shape (B, T) enters as (B, T, 1), Blank 2 produces angles (B, T, D/2) then emb (B, T, D), the cos and sin tables are (B, 1, T, D) in FP32 and broadcast over heads into Blanks 3-4, which combine them with q and k of shape (B, H, T, D)

    Figure 2: The shape contract for the table builder. Blank 1 produces the FP32 band, and the later blanks must carry it through each intermediate shape to a table that broadcasts over heads.

    3Interviewer Nudge & Line Focus

    Check precision boundaries and broadcasting rank at each of the 4 blanks:

    Blank 1 (Frequency Band): Generate even indices 0, 2, ..., D - 2 explicitly with dtype=torch.float32 so instantiating the module under a BF16 default dtype never quantizes base ** (-2i / D).
    Blank 2 (Broadcast Table): At position 100,000, BF16 ULP spacing is 512 tokens! Cast position_ids to FP32 before the outer product, concatenate the D/2 angles twice along dim=-1, and unsqueeze a size-1 head axis to get (B, 1, T, D).
    Blank 3 (Pairwise 90° Turn): Under Llama's half-split convention, channel i pairs with channel i + D // 2; rotating (x1, x2) by +90° yields (-x2, x1) concatenated along the last axis.
    Blank 4 (FP32 Apply + Cast): Promote q and k to .float() before computing x * cos + rotate_half(x) * sin, then cast the result back to q.dtype so downstream attention kernels receive the original BF16/FP16 dtype.
    Answer
    Login to view more content