Tag: Retrieval

  • CD0062 Sparse Dot Product

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

  • CD0038 Time-Based KV Store

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

  • CD0028 Stale Index Triage

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

  • CD0020 AI Code Comprehension

    Mode D · AI-Assisted 60 Min NumPy · Python 3 3 Phases · 3 AI Flaws

    Picture a retrieval-evaluation codebase on a Google team. An offline harness ranks a few hundred thousand stored document embeddings against each eval query by cosine similarity and reports recall@k. This round follows the code-comprehension format reported for Google’s 2026 interviews. You receive a module you did not write, an AI assistant is available, and the grade depends on how you read, steer, and audit, not on typing speed.

    Phase 1 (Read & Explain, unaided, no AI): trace what SimilarityIndex computes and name the lines where its cost lives. Then fix the one correctness issue your trace exposes. After an ingest batch in which the upstream encoder timed out on a few documents, every ranking the harness prints contains nan scores, the order is visibly non-monotone, and NumPy emits a RuntimeWarning about an invalid value encountered in a divide.

    Phase 2 (AI-Assisted Optimize): write the prompt that gets the assistant to vectorize the row-wise similarity loop and add a top-k API. Phase 3 (Audit the AI’s Rewrite): the assistant’s draft runs and returns arrays of the right shape, yet it violates the contract below in exactly three places. Find them, fix them in place, and write one verification test proving that the vectorized path matches the reference loop within tolerance.

    Phase 2 Target Contract:
    (1) score(queries): accepts an (n_queries, d) or (d,) input and returns an (n_queries, n_vecs) float64 matrix. Its values must equal the reference loop’s values within 10^{-12}, and no Python loop over stored rows is allowed.
    (2) topk(queries, k): returns (ids, scores), each of shape (m, \min(k, n)), with the best match first. Equal scores are broken by insertion order, exactly as rank() breaks them today, and scores are float64.
    (3) rank(query, k): keeps its current return format, a list of (id, score) pairs, and delegates to topk().

    Starter Module (42 Lines, Read Before You Touch):

    01  import numpy as np
    02
    03
    04  class SimilarityIndex:
    05      """Cosine-similarity index over an in-memory vector store."""
    06
    07      def __init__(self, dim: int):
    08          self.dim = dim
    09          self.ids = []
    10          self.vecs = np.empty((0, dim), dtype=np.float64)
    11
    12      def add(self, ids, vecs):
    13          vecs = np.asarray(vecs, dtype=np.float64)
    14          assert vecs.ndim == 2 and vecs.shape[1] == self.dim
    15          assert len(ids) == vecs.shape[0]
    16          self.ids.extend(ids)
    17          self.vecs = np.vstack([self.vecs, vecs])
    18
    19      def score(self, queries):
    20          """Return an (n_queries, n_vecs) matrix of cosine similarities."""
    21          queries = np.asarray(queries, dtype=np.float64)
    22          n_queries, n_vecs = queries.shape[0], self.vecs.shape[0]
    23          sims = np.zeros((n_queries, n_vecs), dtype=np.float64)
    24          for i in range(n_queries):
    25              q = queries[i]
    26              query_norm = np.linalg.norm(q)
    27              for j in range(n_vecs):
    28                  v = self.vecs[j]
    29                  vec_norm = np.linalg.norm(v)
    30                  sims[i, j] = np.dot(q, v) / (query_norm * vec_norm)
    31          return sims
    32
    33      def rank(self, query, k=None):
    34          """Return top-k (id, score) pairs, best match first."""
    35          sims = self.score(np.asarray(query)[None, :])[0]
    36          order = sorted(range(len(sims)), key=lambda j: -sims[j])
    37          if k is not None:
    38              order = order[:k]
    39          return [(self.ids[j], sims[j]) for j in order]
    40
    41      def __len__(self):
    42          return len(self.ids)
    Three-phase round: Phase 1 read and explain the starter module unaided, Phase 2 prompt the AI to vectorize score() and add topk(), Phase 3 audit a draft containing three unnamed flaws shown as question marks; below, three contract boxes for score(), topk(), and the loop-versus-vectorized parity oracle

    Figure 1: The round runs read, steer, audit in that order. The Phase 2 target contract along the bottom is the yardstick for both your prompt and the AI’s draft.

    Interactive PyTorch Workspace: Switch to the split-screen workspace to run the Phase 1 warm-up, steer the simulated assistant, and audit its draft against the hidden parity, ordering, and dtype checks.

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

    (1) Explain Before You Touch: State in one sentence what sims[i, j] means and what rank() returns, including how it orders equal scores.
    (2) Complexity Hot Spot: Count how many times the innermost lines run for m queries and n stored rows, and which per-row work repeats for every query.
    (3) Degenerate Rows: Decide what a cosine score should be when a vector has no magnitude, before trusting any ranking built on it.
    (4) Same Quantity, Fewer Loops: A vectorized score must reproduce every factor of line 30, not just the part that looks like a matmul.
    (5) Output Contract: Order, tie-break, shape, and dtype are all part of the API that downstream tests pin.

    2Visual Review Map (Figure 2)
    Stage map with two rows: the starter's reference loop (input queries, norms in the loop marked with a question mark, per-pair score, sort, rank output) and the AI draft pipeline (input queries, input prep, score matrix, and ordering each marked with a question mark, then the topk and rank output), joined by a parity check arrow

    Figure 2: The reference loop (top) and the AI draft (bottom) as stage maps. Every ? marks a stage to audit, and deciding what each stage should do is the exercise.

    3Interviewer Nudge & Line Focus

    Work the three phases in order using the stage checks below:

    Phase 1 (Read & Explain): How many times do lines 29-30 execute for n_queries queries and n_vecs stored rows, which norm gets recomputed once per query, and what does line 30 evaluate to when a stored row has no magnitude at all?
    Phase 2 (Spotting Flawed Prompts): Do not judge prompts by coverage of the score formula alone. Check whether the spec pins all three contracts: row normalization, descending order with stable ties, and float64 end to end. A contract the prompt drops comes back dropped in the regenerated draft.
    Phase 3 (Auditing the Cosine Scorer): Scale one stored row by 10: should its cosine score change, and does it in the draft’s score()? Which direction does np.argsort order each row by default, and which of two tied rows must come first? Then trace the dtype of every intermediate: what does a float64 golden-score assertion receive?
    Answer
    Login to view more content
  • MSD0063 Image Copyright Detection

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

  • MSD0061 Nearby Place Recommendation

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

  • MSD0058 Ride-Hailing Matching System

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

  • MSD0050 Document QA Extraction

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

  • MSD0049 Google Related Searches

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

  • MSD0040 Automated Retail Checkout

    Design a deep learning model for a retail store’s automated checkout system that recognizes items from camera feeds and computes totals without barcode scanning. A customer places items on a counter or walks through a gate, overhead and angled cameras capture the items, and the system must identify each product, count multiples, handle occlusion and stacked items, distinguish similar-looking products (two flavors of the same brand), and produce a receipt in seconds.

    The system must handle a large product catalog (thousands of SKUs) that changes as inventory rotates, work under varying lighting and camera angles, and keep the error rate low enough that manual corrections are rare.

    How would you design this model? Cover the candidate recognition architectures (object detection vs instance segmentation vs metric-learning retrieval against a product catalog), how you handle the large and rotating SKU catalog, how you count multiples and handle occlusion, how you generate training data for new products with few examples, and how you calibrate confidence to flag uncertain items for manual review.

    Line-art scene: overhead and angled cameras looking at a checkout counter with overlapping and stacked items, a magnifier over two nearly identical flavor cans, and a receipt with question marks

    The Problem: the catalog is huge and rotates weekly, the items overlap and stack, and two flavors of the same brand differ by a color band. The model has seconds to turn pixels into an exact receipt.

    Answer

    Split the problem into localization and identity, and keep identity out of the network weights. A class-agnostic instance segmenter finds every item instance and its mask, a crop encoder trained with a metric-learning loss maps each instance to a unit embedding, and the SKU is decided by cosine nearest-neighbor search against a catalog index of enrolled prototypes. This makes catalog rotation an indexing operation rather than a retraining project, since a new product needs about 20 enrollment crops and no weight update. Masks (not boxes) drive multiple-instance counting under occlusion, counts are fused across the overhead and angled views, and a calibrated margin gate abstains on ambiguous items so the review lane sees only the genuinely hard ones.

    (1) Closed-Set Object Detection: one detector with a K-way softmax head over all SKUs; fastest single pass, but the catalog is baked into the weights.
    (2) Instance Segmentation With A Class Head: per-item masks give reliable separation of touching and stacked products, but identity still lives in a fixed classifier.
    (3) Class-Agnostic Localization Plus Metric-Learning Retrieval: the chosen design; localization is SKU-independent and identity is a nearest-prototype lookup in an index that can be edited nightly.
    (4) Open-Vocabulary Detection With Text Prompts: zero-shot on new categories, but it cannot separate two flavors of one brand, so it serves only as a proposal generator or a cold-start fallback.

    Mechanism diagram: multi-view frames feed a class-agnostic segmenter, crops are embedded by an encoder, a catalog index returns cosine top-k matches, cross-view fusion produces per-SKU counts, and a confidence gate routes items to the receipt or a review lane; a separate enrollment box feeds new SKU prototypes into the index

    Figure 1: Localize anything, then look it up: frames → masks → embeddings → catalog index → fused counts → gate. New SKUs enter through the index, never through the weights.

    Clarify Before Designing:
    (1) Catalog Shape: how many SKUs, how many are added or retired per week, and how many are near-duplicates within a brand family?
    (2) Compute Budget: edge box per lane or shared server GPU, and what is the wall-clock budget from last item placed to receipt shown?
    (3) Camera Geometry: fixed calibrated overhead plus angled views on a static counter, or a gate where items must be tracked while moving?
    (4) Enrollment Data: does the retailer already supply studio packshots per SKU, and can we photograph new products before they reach the shelf?
    (5) Error Asymmetry: what is the cost of an undercount (shrinkage) versus an overcharge (trust), and what per-basket review rate is acceptable?
    (6) Presentation Rules: may the interface ask the customer to spread items out, or must the model handle arbitrary piles?


    Login to view more content