Product recommendation: 15 deep chapters, 3 original diagrams, data and labels, retrieval/ranking, experiments and serving, plus bilingual interview scripts.
Private-document RAG: 14 deep chapters, 3 original diagrams, contextual retrieval, training and citations, access, evaluation, serving, and bilingual interview scripts.
First establish whose decision the system improves and how success will be measured. At each stage, state a concrete choice, its rationale, and the evidence that would make you revisit it.
Draw two paths: online request → features/retrieval → scoring → constraints → response; offline events → labels → training → validation → versioned deployment. Connect them through outcome logs.
可以直接練的轉場句Ready-to-rehearse transitions
「在選模型前,我想先確認我們要改善哪個決策,以及不能犧牲的護欄。」“Before choosing a model, I would clarify the decision we are improving and the guardrails we cannot compromise.”
「我會把一筆訓練樣本定義為……,並只使用決策當下已知的特徵。」“I would define one training example as … and use only features available at decision time.”
「先用這個 baseline 驗證資料;只有錯誤分析顯示需要時,才增加模型複雜度。」“This baseline validates the data pipeline. I would add complexity only when error analysis identifies a limitation it can address.”
「現在我把它放到線上:這是 critical path、時間預算,以及依賴失效時的回退方式。」“For serving, this is the critical path, its latency budget, and the fallback when a dependency fails.”
「離線改善是篩選條件;是否真的改善產品,要靠可信的線上實驗。」“Offline improvement is a screening criterion; a trustworthy online experiment establishes product impact.”
「如果這個指標改善、但護欄退化,我會先檢查……,而不是直接擴大上線。」“If the primary metric improves but a guardrail regresses, I would investigate … before expanding the rollout.”
Titles follow the supplied list. Full prompts were unavailable, so these are independently scoped practice designs, not internal implementations, official solutions, or interview predictions. All scale, candidate-count, and latency figures are illustrative assumptions. References support concepts; the case designs are a synthesis.
02 / Worked cases
題目與參考回答Cases & worked answers
22 / 22
先收合答案口說,再展開對照。勾選紀錄只保存在這個瀏覽器。列印目前篩選的案例與所選語言。Close answers and rehearse first, then compare. Checkmarks are stored only in this browser. Printing includes the current case filter and selected language.
沒有符合的題目,請調整搜尋或篩選。No matching cases. Adjust the search or filter.
01最先練的 3 題Start with these 3Meta Ad Click PredictionAd relevance / Ranking / Calibration+
設計一個在廣告曝光前預測點擊機率、支援即時排序的系統。
Design a system that predicts click probability before an ad impression and supports real-time ranking.
14 chapters, 3 original diagrams, exposure and label maturity, sampling correction, features and sequence models, training, experiments, serving, code guides, and bilingual rehearsal answers.
I would first clarify the placement, billing model, and primary objective. I will assume CPC ads and focus on predicting click probability for valid impressions. A downstream ranking service combines that estimate with bids, quality, and budget constraints. I would start with a simple calibrated model, then justify additional complexity through temporal validation, slice analysis, and an online experiment.
Define the decision and objective. Ask whether this is search or feed advertising, CPC or CPA billing, and whether value means qualified clicks or conversions. For this exercise, use CPC. CTR is a model output, not the sole product KPI. Consider revenue per thousand valid impressions, with conversion quality, hides/reports, latency, and retention as guardrails.
State scale assumptions. Assume a peak of 10k requests/s, 200 candidates per request, and a 100 ms p95 ranking-service budget. That is about 2M candidate scores/s, motivating batched scoring, cached features, and candidate pruning. These are interview assumptions.
Use impressions as examples. Join impression_id to user/ad/context features, position, candidate set, policy/model versions, timestamps, and click events. Deduplicate clicks and handle invalid traffic. Define a click-attribution window and only label a non-click after that window matures.
Use information available at decision time. Features include prior behavior, creative text/image representations, device, time, and pre-impression aggregates. Use point-in-time joins and chronological train/validation/test splits. Handle conversion delays separately. Record negative-sampling rates; unshown ads do not have observed click labels.
Start with an interpretable baseline. Use smoothed CTR by placement/category, then logistic regression or GBDT to verify data quality and incremental value. For large sparse feature spaces, consider embeddings and explicit feature interactions, such as a DLRM-style model. Encode text and images offline where feasible.
Specify the learning objective. Binary cross-entropy estimates p(click | user, ad, context, shown). Calibrate on a separate validation set with natural traffic prevalence. A multitask click/conversion/hide model requires explicit loss weights and attribution windows. Click-conditional CVR is not the same as impression-level conversion probability.
Build offline and online data paths. Impression/click streams feed durable storage, deduplication, watermarking, label maturation, and training validation. Recent counters update an online feature store. Daily retraining is a starting assumption; adjust it based on drift and measured value.
Make releases reversible. Version the model, feature schema, and calibrator together. Progress through replay, shadow traffic, a canary, and A/B testing. On feature timeouts, use a lightweight model trained to handle missingness. Eligibility, budgets, and frequency caps remain enforced. Monitor feature age, missingness, p95/p99 latency, and predicted versus observed CTR.
Separate ranking from probability quality. ROC-AUC measures discrimination; interpret PR-AUC alongside prevalence. Use log loss, Brier score, and reliability diagrams for probability quality. Evaluate on natural traffic and slice by placement, new ads, device, geography, and activity level.
Test product impact online. Use stable user assignment, check SRM and logging completeness, and predefine the primary metric, MDE, sample size, and duration. Shared campaign budgets may create interference, requiring campaign- or geo-level designs. Revenue gains must pass user and advertiser guardrails, with fast rollback available.
06失敗案例與取捨Failures & tradeoffs
AUC 上升但收入下降: 先查校準、分群偏差、候選集合、延遲與預算消耗,不要直接重訓更大模型。新廣告沒曝光: 用內容特徵與受限探索,而非只靠 ID embedding。
AUC rises but revenue falls: inspect calibration, slice shifts, candidate composition, latency, and budget consumption before increasing model size. New ads receive no exposure: add content features and constrained exploration rather than relying only on ID embeddings.
Main tradeoffs. Clickbait can increase CTR while hurting conversions and trust. Fresh features improve responsiveness but add dependencies and latency. Use minimal necessary features, layered fallbacks, natural-distribution calibration, and exploration data to limit feedback loops. Profile feature fetching and embedding tables as traffic grows.
深入拆解Deep dives
下採樣與機率校準Downsampling and calibration
若所有正例保留、負例以 r 的機率保留,抽樣資料預測 q 對應真實 p = r·q / (1−q+r·q)。例如 r=0.1、q=0.2,p≈0.0244。此式假設類別內隨機抽樣;不適用於任意 hard-negative sampling。可用正確 sample weights 直接學原分布,但不要再重複做同一抽樣修正;校準仍須獨立驗證。
If all positives are retained and each negative is retained with probability r, a sampled-data estimate q corresponds to p = r·q / (1−q+r·q). With r=0.1 and q=0.2, p≈0.0244. This assumes random sampling within each class, not arbitrary hard-negative mining. Correct sample weights can target the original distribution directly; do not apply the same correction twice. Validate calibration separately.
預測、價值與拍賣分層Separate prediction, value, and auction policy
A simplified CPC expected-value score is eCPM = 1000 × bid_per_click × pCTR. Its units are expected bid value per thousand impressions; it is not a full auction or realized-revenue formula. If conversion requires a click, pCVR_per_impression = pCTR × p(conversion | click). View-through conversions need a separate definition. Quality, relevance, pacing, and frequency constraints require explicit policy handling.
An illustrative budget is 20 ms for features, 40 ms for batched inference, 20 ms for constraints/response, and 20 ms of slack. These are critical-path allocations: adding stage p95 values does not produce an end-to-end p95. Load-test tail latency, candidate counts, and cache misses. Reduce candidates or fall back to a lightweight model on deadline pressure.
AUC depends on ordering, while bid-value and budget decisions depend on absolute probabilities. Models with identical AUC can have very different calibration.
It can model presentation context if serving semantics are consistent. Do not mistake the old rank position for intrinsic relevance. Controlled exploration can estimate exposure propensities; corrections require care because small propensities create high variance.
02最先練的 3 題Start with these 3Amazon Product Recommendation SystemRecommendation / Retrieval / Multimodal+
設計商品推薦系統,從大量商品中選出個人化、可購買而且有幫助的推薦。
Design personalized recommendations that select useful, purchasable products from a large catalog.
15 chapters and 3 original diagrams: data and mature labels, feature engineering, item-to-item, two towers, ranking, experiments, and serving, with code guides and bilingual rehearsal scripts.
I would scope this to one surface, such as a homepage recommendation shelf, and optimize for satisfactory purchases rather than clicks alone. The design uses multiple candidate sources, a ranker, and constrained reranking. I would establish popularity and item-to-item baselines before adding two-tower retrieval and multitask ranking. Exposure bias, cold start, and inventory freshness are central, with purchases and return-related guardrails validating online impact.
Scope the surface first. Homepage, product-detail, and cart recommendations express different intents. Assume a personalized homepage shelf. Ask about sponsored content, anonymous traffic, and freshness requirements. A primary metric might be matured valid orders per user, with cancellations/returns, satisfaction, repeat visits, and latency as guardrails.
State scale assumptions. Assume 10M products, 5k peak requests/s, and 150 ms p95. Merge roughly 1k candidates, pre-rank to 200, and select 20. Tune these counts using recall–latency curves rather than treating them as fixed rules.
Distinguish behavioral signals. Log request_id, candidate and displayed items, positions, clicks, carts, orders, returns, timestamps, and model versions. Displayed-but-ignored items are weak negatives; unshown items are unknown. Purchases are sparser than clicks, and returns mature later, requiring separate label windows.
Make examples reproducible. Use pre-request history, session intent, category, price, text/image features, and inventory snapshots. Do not use future prices or post-purchase attributes. Split chronologically and retain cold-user/item slices. Normalize product variants and duplicate listings.
Give retrieval and ranking distinct jobs. Start with popular items, category candidates, and item-to-item co-purchase signals. Add a two-tower user/session and item model using a contrastive or sampled-softmax objective. In-batch negatives may be false negatives; account for popularity-driven sampling and product variants.
Use richer interactions in ranking. A GBDT or deep ranker predicts clicks, carts, purchases, and returns. Combine these through an explicit utility function and hard constraints. Retrieval dot products are not purchase probabilities. Image/text representations can help new items, but first measure a strong metadata baseline.
04訓練與部署Training & deployment
版本一致的 embedding 與 ANN。 離線產生商品向量,更新主索引;新商品用增量索引,定期合併。user tower、item tower 與 index 必須是相容版本,切換時原子更新並保留上一版。特徵、模型與 index 都可回滾。
Version embeddings and ANN indexes together. Generate item vectors offline, maintain a main index plus incremental updates, and compact periodically. User/item towers and the index must be compatible; switch atomically and retain the previous version. Features, models, and indexes all need rollback paths.
Separate freshness requirements. Descriptions change slowly, session intent updates via streams, and price/inventory comes from an authoritative service with explicit TTLs. Filter during retrieval and recheck before output. Do not encode live stock as a permanent embedding property. Fall back to eligible popular or recently viewed items on ANN failure.
A/B 以 user 為單位。 預設樣本量與實驗時長,先查 SRM;看 orders/user 與增量收益,同時等待取消/退貨成熟。若只是把首頁購買搬到另一個入口而非新增,要用整體使用者指標辨識 cannibalization。
Diagnose by stage. Measure candidate Recall@K against known relevant items, then ranker NDCG@K, purchase log loss, and calibration. Check catalog coverage, diversity, and cold-start slices. ANN recall measures agreement with exact nearest-neighbor search; it is different from relevance recall.
Randomize by user. Predefine power and duration, check SRM, and measure orders per user and incremental value while allowing cancellation/return labels to mature. Whole-user metrics help distinguish additional purchases from moving purchases between surfaces.
主要取捨。 ANN 召回速度對長尾 recall;更大 ranker 對延遲;即時行為對噪音與隱私。先分析是「好商品沒召回」還是「召回後排錯」,再投資對應階段。以探索與跨時段評估減少熱門度 feedback loop。
New users: use context, session behavior, popularity, and optional preferences. New products: use metadata, image/text representations, and constrained exploration. Overspecialization: add category/brand diversity and suppress duplicates or no-longer-needed durable goods.
Main tradeoffs. ANN speed competes with long-tail recall; larger rankers compete with latency; real-time behavior adds both freshness and noise. Determine whether useful items were missed by retrieval or misordered after retrieval before investing. Exploration and temporal evaluation help limit popularity feedback loops.
10M × 128 dimensions × 2 bytes for FP16 gives 2.56 GB of raw vectors, excluding ANN structures, metadata, replicas, and workspace. At 5k requests/s and 200 final-ranker candidates, demand is 1M scores/s. Derive capacity from measured batch latency, hardware throughput, and failover headroom, not raw-vector size alone.
為什麼不是一個模型排全部商品?Why not score every product with one model?
Expensive cross-feature scoring over 10M products is impractical per request. Two towers permit precomputed item vectors and fast retrieval; the ranker spends richer user–item interactions on a small candidate set. The objectives may differ, and a ranker cannot recover omitted items, so measure coverage and incremental value by candidate source.
如何處理負樣本?How would you sample negatives?
檢索可混合 random、in-batch 與 hard negatives,排除已知正例與重複商品;評估抽樣分布是否偏熱門。精排優先使用同次曝光集合的成熟結果,並區分無互動與明確不喜歡。曝光偏差需額外探索資料或有假設條件的 propensity correction;不是換一種 loss 就消失。
Retrieval can mix random, in-batch, and hard negatives while excluding known positives and duplicates. Inspect popularity bias in sampling. Ranking should use matured outcomes from impression sets and distinguish non-interaction from explicit dislike. Exposure bias requires exploration data or assumption-dependent propensity correction; a new loss alone does not remove it.
Recall@1000 很高,購買仍下降?Recall@1000 is high, but purchases fall. Why?
先查 ground truth 是否只代表舊策略、精排和校準是否退化,再看缺貨/價格、展示位置、延遲與多樣性。若商品進了候選卻未展示,是排序或約束問題,不必先換 retriever。
Check whether relevance labels only reflect the old policy, then inspect ranking, calibration, inventory, prices, presentation, latency, and diversity. If useful items enter candidates but are never displayed, investigate ranking or constraints before replacing retrieval.
03最先練的 3 題Start with these 3Anthropic RAG SystemRetrieval / LLM / Groundedness+
設計一個能回答私有文件問題、提供可驗證引用並隨資料更新的 RAG 系統。
Design a RAG system that answers questions over private documents with verifiable citations and fresh knowledge.
14 chapters and 3 original diagrams: data and labels, hybrid/contextual retrieval, training losses, citations and access, evaluation and serving, with 6 interactive scenarios, code guides, and bilingual rehearsal scripts.
I would clarify document types, update frequency, access permissions, and expected behavior when an answer is unavailable. I would establish a BM25-and-citations baseline, then add dense retrieval, fusion, and reranking when evaluation supports them. Retrieval and generation need separate evaluation. Authorization happens before generation, citations identify source versions and spans, and insufficient evidence leads to an explicit limitation or clarification.
Define the answer contract. Ask about formats, languages, tables, update frequency, cross-document reasoning, and permissions. Answers must address the question and cite evidence; missing evidence should trigger clarification or abstention. Optimize supported task completion, with authorization violations, false claims, latency, and cost as guardrails.
Separate latency measures. Assume 1M chunks, 100 queries/s, a 2 s p95 time to first token, and 8 s to completion. Bound answer length and tool calls. Streaming improves responsiveness but does not prove lower total generation latency.
Make documents traceable assets. Store doc_id, version, section/page, source offsets, updated_at, tenant_id, and ACL for each chunk. Respect headings and paragraphs; preserve table headers and units. Tune chunk size and overlap through evaluation. Propagate deletions and permission revocations to indexes and caches.
Build a challenging gold set. Include real questions, relevant spans, required facts, acceptable answers, unanswerable cases, and access-denied cases. Split by document family and time to avoid near-duplicate leakage. Synthetic questions can expand coverage, but need human auditing and independent evaluation.
Prove retrieval first. Start with BM25, a fixed prompt, and citations. Dense embeddings add semantic matching; BM25 preserves exact identifiers and terms. Fuse ranks with Reciprocal Rank Fusion, then rerank a bounded candidate set with a cross-encoder. Do not directly add incompatible score scales.
Generate from authorized, relevant evidence. Require source IDs and acknowledgment of missing evidence, and map citations back to source spans. Hold the generator fixed for retrieval ablations. Fine-tune retrievers/rerankers only when representative labels and error analysis justify it; RAG does not require LLM fine-tuning.
Separate indexing from serving. Content hashes support deduplication and incremental updates. Keep reversible index snapshots and consistent embedding versions. Authenticate and enforce tenant/ACL restrictions during search, then recheck revocations before reranking/output. Pure post-filtering can severely reduce recall.
Bound failures. Cache keys include permission scope, query, and document/index versions; revocations invalidate caches. On retrieval/model timeout, return authorized sources or explain that the answer could not be completed. Treat documents as data, not authorization to call tools or change instructions. Trace retrieval, prompt/model versions, citations, and stage latency.
Make evaluation attributable. Retrieval metrics include evidence Recall@K, MRR/nDCG, empty-result rate, and recall after ACL restrictions. Generation metrics include correctness, claim-level groundedness, citation precision/coverage, and abstention precision/recall. A citation being present does not mean it supports a claim. Isolate retrieval and generator changes in ablations.
Measure completion online. Test task success, reformulations, escalation, cost, TTFT, and full-response time. Calibrate an LLM judge against human labels with an explicit rubric, blinded comparisons, and language/length bias checks. Human-review consequential errors.
主要取捨。 更大 K 提升可能 recall,卻增加噪音、token 與 latency;rerank 增加精度與成本。遇到最新價格或庫存,不依靠舊文件,改查權威 API。提示注入、資料過期與答案拼湊都需專門測試,不能把低 temperature 當成防幻覺保證。
Correct document, wrong answer: inspect chunk boundaries, table units, conflicting versions, and context use. Missing evidence: inspect ingestion, ACL filters, query rewriting, and separate BM25/dense recall.
Main tradeoffs. Larger K can increase recall but also noise, tokens, and latency. Reranking trades cost for precision. Live price or inventory requires authoritative APIs rather than stale documents. Test prompt injection, outdated evidence, and unsupported synthesis explicitly; low temperature is not a guarantee against hallucination.
For a claim such as “two-year warranty,” cite a specific span of product_manual v3, not a homepage. Verify both that the source supports the claim and that it applies to the product, time, and region in question. Surface conflicting evidence or follow a predefined authority hierarchy instead of letting the model guess.
RRF(d) = Σ 1 / (c + rank_i(d)); a source contributes nothing when d is absent from its list. The constant c controls rank sensitivity. An illustrative setup retrieves 100 BM25 and 100 dense results, reranks 50 deduplicated candidates, and selects 8 chunks. Tune K, c, and chunk size through quality/latency ablations, and avoid filling context with duplicates.
Use a fixed workflow for straightforward document questions. Add a bounded controller when the task requires adaptive source selection, clarification, or live tools. Enforce step, cost, and time limits; validate tool schemas. Purchases and other side effects require user confirmation and idempotency keys. Decompose failures into retrieval, tools, reasoning, and output.
Test with oracle evidence. If the smaller model answers correctly once given the right spans, retrieval is the bottleneck. If it still fails, investigate the prompt, context, or generator.
I would define a feed request as the ranking unit and clarify valuable engagement and negative guardrails. Candidates come from followed accounts and recommended content, followed by staged ranking and diversity constraints. The main challenges are bias from the previous exposure policy and the conflict between short-term engagement and long-term satisfaction.
Clarify whether the feed contains friends, public content, or both, and whether chronological ordering is a baseline. Optimize valuable engagement or survey-calibrated satisfaction, with hide/report, safety, and retention guardrails. Assume 20 items and a 200 ms p95 budget for practice, with an explicit freshness requirement.
Log viewable impressions, not only served items, plus position, dwell, shares, hides, and reports. Dwell can indicate confusion rather than satisfaction. Use request-time features and chronological splits; unseen items lower in the feed are not strong negatives. Retain policy propensities and controlled exploration data.
03Baseline/模型Baseline & models
Baseline 是時間衰減+關係強度,接著 GBDT/多任務 deep ranker 預測有意義互動與負面反應。候選源包含好友、興趣、熱門;精排後依作者/主題多樣性與安全規則重排。多目標權重須有可解釋效用與線上驗證。
Start with recency decay and relationship strength, then a GBDT or multitask deep ranker for valuable actions and negative feedback. Mix friend, interest, and trending candidates. Apply author/topic diversity and safety constraints after ranking. Objective weights need an interpretable utility definition and online validation.
Stream recent interactions and learn long-term interests offline. Avoid unconditional fan-out for very high-fanout authors; combine precomputed candidates with request-time retrieval. Cache candidates and batch scoring. Invalidate deleted content promptly, and fall back to an eligible chronological feed on timeout.
Offline, evaluate per-task log loss, NDCG, slice calibration, and creator coverage. Counterfactual estimates require propensity support and do not automatically eliminate bias. Online, check SRM and measure satisfaction, retention, and negative actions. Social spillovers may require cluster designs or explicit interference analysis.
High dwell can reward sensational content, and popular creators can become increasingly dominant. Use constrained exploration, concentration monitoring, diversity, and quality guardrails. If offline gains hurt retention, slice by source, creator, new users, and content length to find misaligned incentives.
為什麼不只最大化 watch time?Why not maximize watch time alone?
它偏好長內容,也可能獎勵低品質黏著。需加入內容長度校正、負面訊號與獨立滿意度/留存證據。
It favors long content and can reward low-quality engagement. Add length-aware analysis, negative signals, and independent satisfaction/retention evidence.
I would distinguish exact-product matching, category similarity, and style inspiration. Visual similarity alone may not satisfy shopping intent. I would retrieve with visual embeddings and rerank with category, text, attributes, and purchasability, evaluating retrieval and final relevance separately.
Clarify whole-image versus selected-object input, exact-SKU requirements, and supported categories. Optimize successful queries and relevant interactions, with no-result rate and latency guardrails. For practice, scope to product images and 300 ms p95; let users select an object in multi-object scenes.
Collect query–item relevance, exact/category/style labels, impression clicks, and image–text pairs. Split by near-duplicate image and product family. Include hard negatives that look similar but differ in material or function, and audit missing or incorrect descriptions.
Start with a pretrained visual encoder and ANN. Compare image–text aligned encoders, domain contrastive fine-tuning, and crop-level representations. Rerank using color, material, text, and category. Graph-based representations such as PinSage-style embeddings can add candidates, but graph proximity is not identical to visual similarity.
Encode catalog items offline and queries online, versioning encoders and indexes together. Bound GPU batching by request deadlines. Cache common image hashes; handle corrupt/low-resolution images explicitly or offer text search. Incrementally index new products and remove invalid items.
分 exact match 與 semantic relevance 看 Recall@K、mAP/NDCG;另量 ANN recall、類別與膚色/光線/背景切片。線上 A/B 看成功搜尋與商品互動,監控推論成本、p95/p99、無結果率;只看相似度分數沒有產品意義。
Evaluate exact matching and semantic relevance separately with Recall@K, mAP/NDCG, plus ANN recall and category/lighting/background slices. Audit relevant representation differences such as skin tone for applicable image categories. Online, test successful searches and product interactions with cost, tail-latency, and no-result guardrails.
The model may exploit backgrounds or brand watermarks; test crops, background augmentation, and hard cases. Similar appearance can hide size/function differences, so allow text refinements and attribute constraints. Better crops and labels may outperform a larger encoder; verify through ablations.
They can share a backbone, but need different relevance labels, objectives, or reranking weights. Evaluate by intent before choosing multiple heads or retrieval routes.
I would establish model size, sequence length, token budget, GPU memory, and network topology, then build a correctness baseline on one device or a small cluster. Profiling and memory limits determine the scaling strategy: data parallelism first, sharded state when necessary, then tensor or pipeline parallelism. Success means time and cost to target quality, including recovery from failures.
Clarify pretraining versus fine-tuning, dense versus MoE, target loss, deadline, hardware, and interconnect. Optimize time/cost to quality, useful tokens/s, and recovery time rather than GPU utilization alone. Define global batch size and token accounting.
Deduplicate and filter data, track provenance/versions, and check held-out contamination. Derive next-token labels by shifting sequences and mask padding. Distributed sampling must avoid unintended duplication or omissions. Save shuffle seeds, data cursors, and consumed-token counts.
Establish a small-model reference at a reliable precision, then compare mixed precision. DDP replicates state; FSDP/ZeRO shard it at communication cost. Tensor parallelism favors fast interconnects; pipeline parallelism introduces bubbles. Global batch equals microbatch × accumulation steps × data-parallel world size.
Profile compute, collectives, data loading, and I/O. Activation checkpointing trades recomputation for memory. Save model, optimizer, scheduler, RNG, data cursor, and shard metadata with a completeness manifest. A checkpoint is useful only after a tested restore. Restart synchronous groups consistently after failures to avoid rank-step divergence.
Compare loss trajectories, gradients, and downstream quality with matched data and effective batches, then measure tokens/s/GPU, scaling efficiency, MFU, and cost/token. Validate the platform with cluster canaries, controlled workloads, and failure injection. A training platform does not need a click-rate A/B test; deployed model behavior gets its own product experiment.
For OOM, separate parameter, optimizer, and activation memory. For NaNs, inspect data, overflow, loss scaling, and learning rate. Poor scaling may come from collectives, stragglers, or I/O. Sharding adds communication; frequent checkpoints add I/O. Choose checkpoint intervals from failure frequency, save cost, and acceptable recomputation.
A conventional mixed-precision Adam estimate is 2 bytes for FP16 parameters, 2 for gradients, 4 for FP32 master weights, and 8 for two FP32 moments: roughly 16 bytes/parameter. Implementations differ in master copies and gradient dtypes. A 7B model therefore has about 112 GB of such state before activations, buffers, and fragmentation. ZeRO/FSDP can shard state, but peak memory must be measured.
More GPUs, worse convergence, or more failed-work replay can offset throughput gains. Compare total GPU-hours, cost, and elapsed time to the same quality target.
The title is broad, so I would ask whether cost comes from training, data, or inference. I will focus on online LLM inference: establish cost per successful task, then compare caching, routing, batching, and quantization in controlled steps. Every saving must pass quality and tail-latency guardrails.
Log request shape, token counts, queue time, TTFT, completion time, route, hardware, and success labels, minimizing sensitive content. Replay sets must include long contexts, rare languages, peaks, and hard tasks rather than only easily cached requests.
Baseline a fixed model and standard serving. Profile before changing exact/prefix caching, small-model routing, quantization/distillation, or unnecessary output length. Train the router for quality and cost, escalating uncertain cases. Semantic caching needs applicability and authorization checks.
Version routing policies, models, quantization, and caches; canary one change at a time. Bound dynamic-batching queues by deadlines and scale using queue depth and arrivals. Define degraded-service quality limits instead of queueing indefinitely. Invalidate caches by data and permission version.
Evaluate matched tasks for quality, success, cost, and load behavior; construct a quality–cost–latency Pareto frontier. Online, compare cost per successful task and tail latency under stable assignment, sliced by cache hits, request length, and language, including idle infrastructure cost.
Large batches improve throughput but add waiting; small models can increase retries; quantization can damage specific languages or tool formats. Report total successful-task cost, not just fewer GPUs. If the actual scope is training, shift to data efficiency, checkpointing, utilization, and time-to-quality.
Escalate using validated uncertainty or format-failure signals with a bounded escalation count. Include both inference passes and added latency in evaluation, avoiding retry loops.
I would separate locating a product from linking it to an exact SKU. The system detects objects, retrieves catalog candidates from crops, and verifies matches. Uncertain cases should return a category or user choices rather than force an exact SKU.
白板資料流Whiteboard data flow
圖片Image
物件偵測Object detection
Crop embeddingCrop embeddings
Catalog retrievalCatalog retrieval
SKU/屬性驗證SKU / attribute verification
Tag 與使用者修正Tags & corrections
01釐清產品目標Clarify product goals
釐清自動標記還是輔助創作者、是否允許多商品、exact SKU 或 generic category。主指標為正確接受的標籤率,護欄為錯配率與延遲;錯連商品通常比少一個 tag 更傷信任。
Clarify automatic versus creator-assisted tagging, multiple objects, and exact SKU versus category labels. Optimize correctly accepted tags, with mismatch and latency guardrails; incorrect links can be worse than missing tags.
Collect boxes, categories, attributes, SKUs, and corrections. Unannotated objects are not necessarily background. Split by product family/image group, including occlusions, rare brands, backgrounds, and viewpoints. Reserve unseen SKUs for open-set evaluation.
Start with a pretrained detector plus image-embedding retrieval, then fine-tune detection and image–text representations. Verify SKU matches using crops, multi-view catalog images, OCR, and attributes. Threshold confidence to choose exact match, category output, or abstention.
Process uploads asynchronously where possible and precompute catalog embeddings. Track model, index, and taxonomy versions; invalidate unavailable products. Route low-confidence cases to human/user confirmation and audit corrections before training on them.
離線分開看 detection mAP、attribute F1、SKU Recall@K 和 precision at coverage。線上看正確 tag 接受率、修正率及後續商品互動;用隨機人工抽樣補足「使用者沒修正不代表正確」的盲點。
Evaluate detection mAP, attribute F1, SKU Recall@K, and precision at coverage separately. Online, measure correct acceptance, corrections, and downstream interactions. Random human audits address the fact that an uncorrected tag is not necessarily correct.
06失敗案例與取捨Failures & tradeoffs
遮擋、仿品、同款不同尺寸造成 exact match 不可靠;以多候選與屬性檢查解決。提高 threshold 可減少誤配卻降低 coverage;依風險與人工容量選擇 operating point。
Occlusion, imitations, and size variants can make exact matching unreliable; use alternatives and attribute verification. Higher thresholds reduce errors but reduce coverage. Choose the operating point based on mismatch cost and review capacity.
Classification targets a relatively fixed taxonomy. Catalog retrieval can add new SKU vectors without retraining a class head every time, but still needs unknown-product rejection.
09依方向補強Specialized practiceTikTok Content ModerationMultimodal / Safety / Human review+
設計結合文字、影像、聲音與人工覆核的內容審核系統。
Design content moderation using text, video, audio, and human review.
I would clarify policy categories, severity, and available actions. Models estimate category-specific risk and uncertainty; a decision layer routes cases according to error costs and review capacity. One score should not govern all content. Evaluation must include misses, false positives, appeals, and language differences.
Clarify uploaded video, live streams, or pre-recommendation filtering. Define policy taxonomy, severity, and actions. Track violating-exposure prevalence with false-positive, successful-appeal, and review-SLA guardrails; live streams need shorter deadlines.
Use versioned-policy multilabel annotations, time spans, languages, and appeals. Preserve uncertainty in disputed cases and restrict sensitive data. Split by creator/near-duplicate video and time. Random traffic audits estimate prevalence; reports alone are selection-biased.
Start with hashes/rules and unimodal classifiers, then evaluate multimodal fusion. Prioritize recall for severe rare categories. Calibrate and threshold by policy, routing uncertain or consequential cases to reviewers as an explicit system component.
04訓練與部署Training & deployment
階梯式檢查:便宜過濾、重模型、人工;影片抽幀與 ASR 須有延遲預算。模型與政策獨立版本化,政策改動先回放。人工 queue 要依風險與 SLA 排序,保留理由與申訴路徑,避免故障時全部自動放行或全部刪除。
Use a cascade of cheap filters, expensive models, and human review, budgeting frame sampling and ASR. Version models and policies separately and replay policy changes. Prioritize review queues by risk/SLA, retain reasons and appeals, and define degraded behavior instead of blindly allowing or removing everything.
Measure per-policy PR-AUC, recall at fixed FPR, calibration, language/group slices, and reviewer agreement. Start with shadowing and audits, then constrained canaries. Do not casually relax severe-content policy for an A/B test. Use controlled rollouts to track prevalence, appeals, and resolution time.
Sarcasm, quotation, dialects, and background audio can cause errors; use context, multimodal evidence, and expert labels. Refresh hard cases for adversarial transformations and policy drift. Higher recall increases review load and false positives, so set thresholds jointly with severity and capacity.
被檢舉次數可當違規標籤嗎?Can report counts be violation labels?
只能當弱訊號,可能受到曝光量與惡意檢舉影響;最終標籤需依政策審核,並用隨機抽樣檢查漏判。
Only as a weak signal: exposure volume and coordinated reporting can distort it. Policy-based adjudication and random audits are needed for reliable labels and missed-case estimates.
10依方向補強Specialized practiceYoutube Video Recommendation SystemRecommendation / Retrieval / Ranking+
設計大規模影片推薦,兼顧使用者滿意度、探索與內容新鮮度。
Design large-scale video recommendations balancing satisfaction, discovery, and freshness.
口說開場範例Spoken opening
我會用候選生成和排序兩階段處理大目錄,並把推薦目標定義為滿意的觀看體驗。watch time 是訊號,但需搭配跳出、不感興趣與滿意度,避免只推薦長片。新影片與 session 意圖會透過內容特徵和即時更新處理。
I would separate candidate generation from ranking to handle a large catalog and optimize satisfying viewing experiences. Watch time is useful but needs early abandonment, dislikes, and satisfaction measures to avoid favoring long videos. Content features and real-time session updates handle new videos and changing intent.
Distinguish homepage from “up next.” Optimize satisfying viewing sessions, with not-interested actions, abandonment, safety, and retention as guardrails. Define how duration and completion contribute to value rather than using total minutes alone.
Log viewable impressions, plays, duration, seeks, skips, surveys, and video length. Autoplay is not active preference. Split chronologically, exclude future history, and slice by duration, new creators, and language. Survey responses may be selection-biased.
Start with popularity and co-watch. Use two-tower or sequence representations for retrieval and multitask viewing/satisfaction ranking. Content embeddings support new videos and session context captures current intent. Rerank for repeat creators, previously viewed items, and exploration.
Refresh video embeddings and models offline while streaming recent viewing. Deploy compatible index versions, support deletions and eligibility, and maintain cold-start candidates. On timeout, serve eligible subscription/popular content and log fallback exposure for evaluation.
Evaluate Recall@K, NDCG, watch-prediction error, satisfaction calibration, and new-video coverage. Online, measure satisfying sessions, retention, abandonment, and creator concentration, including fatigue across sessions.
06失敗案例與取捨Failures & tradeoffs
只看 watch time 會偏長片或聳動內容;用長度分層、多目標與品質規則。新片無互動先靠內容與受限探索;metadata 可能被操弄,須驗證內容訊號。與商品推薦相比,session sequence 和觀看深度更重要。
Watch time alone can favor long or sensational videos; use duration slices, multiple objectives, and quality constraints. New videos need content signals and constrained exploration; metadata can be manipulated. Compared with commerce, session sequence and viewing depth deserve more attention.
I would distinguish discovery shelves from autoplay. Repetition can be desirable in music, and a skip may reflect context rather than dislike. I would combine long-term preferences, session intent, and sequence context, adjusting exploration based on user response.
Clarify commute, exercise, or discovery use, sequence continuity, and offline needs. Optimize satisfying sessions, saves, and return visits, with early skips, repetition fatigue, and playability as guardrails.
Log source, exposure, listening duration, skip timing, saves, repeats, and explicit dislikes. Skips are not equally negative. Evaluate temporal and artist/version slices; audio and regional availability are item features.
Start with favorite artists and popularity, then collaborative retrieval, audio embeddings, and session sequence ranking. Rerank for transitions, artist repetition, and discovery; repeated songs should not be universally banned.
Precompute track embeddings/candidates and stream session state. Prefetch queues to reduce playback gaps. Filter unavailable tracks promptly and use playable cached queues during outages. Preserve queue consistency across releases.
Offline, measure next-track Recall@K, skip prediction, save calibration, and discovery coverage. Online, test satisfying sessions, saves, early skips, and repeat visits by new/old tracks, context, and user activity.
Acoustic similarity may not fit the listener's mood. Too much exploration disrupts sessions; too little becomes repetitive. Use controlled exploration, context, and explicit dislikes without equating popularity with preference.
Intentional replay often signals preference, while an automatically repeated queue may be system-induced. Labels need playback provenance and user actions.
Design recommendations for titles and rows on a streaming-video homepage.
口說開場範例Spoken opening
我會將首頁看成多列內容組成的 slate,而不是單一影片清單。除了單一 title 分數,還要處理列之間的重複與主題覆蓋;開始播放與最後滿意觀看是不同標籤。
I would treat the homepage as a slate of rows rather than one title list. Beyond title scores, the system must control cross-row duplication and thematic coverage. Starting a title and ultimately enjoying it are different outcomes.
Clarify individual profiles versus shared households. Optimize successful discovery, time to a satisfying choice, and satisfaction, with early abandonment, failed search, and retention guardrails rather than starts alone.
Log row/title impressions and positions, starts, viewing, completion, continuation, and ratings. Completion differs by duration; separate profile mixing and unshown items. Split by time and series family.
Start with popularity, categories, and continue-watching. Retrieve through collaborative/content embeddings and rank for satisfying viewing. A second layer chooses row themes/order, limits cross-row duplication, and balances familiarity and discovery.
Precompute candidates/content features and add recent session context online. Filter by regional availability, profile settings, and title status. Fall back to eligible popular and continue-watching rows, preserving visual stability.
離線 title NDCG 加 slate coverage/重複率,線上看成功選片、滿意觀看、早退與回訪。實驗按 profile 或 household 依干擾決定分流,避免不同家庭成員污染結果。
Evaluate title NDCG plus slate coverage/duplication, then online successful choice, satisfying viewing, early abandonment, and repeat visits. Choose profile- or household-level randomization according to interference risk.
06失敗案例與取捨Failures & tradeoffs
系列/熱門片占滿所有列會降低發現;單一 title 更好不代表整頁更好。以 slate 多樣性和跨列去重約束;共用 profile 導致偏好混雜時,降低過度個人化並引入 session context。
Popular titles or series can dominate every row. Better individual titles do not guarantee a better page. Apply slate diversity and cross-row deduplication; shared profiles may need less aggressive personalization and stronger session context.
I would distinguish mandatory notifications from those that can be delayed or suppressed. For optional notifications, the target is incremental value relative to not sending, minus interruption cost. A high open rate alone does not prove usefulness.
Define types, urgency, quiet hours, and cross-device duplicates. Route essential alerts separately. Optimize incremental valuable activity for optional messages, with opt-outs, interruption feedback, and retention guardrails.
02資料與標籤Data & labels
記錄候選、是否發送、送達/可見、open、dismiss、延後與 opt-out;未送通知沒有 open 標籤。需隨機 send/no-send holdout 才能估因果 uplift,處理送達延遲與選擇偏差。
Log candidates, send decisions, delivery/visibility, opens, dismissals, delays, and opt-outs. Unsent messages lack open labels. Randomized send/no-send holdouts are needed for causal uplift; handle delivery delays and selection bias.
03Baseline/模型Baseline & models
Baseline 為偏好+頻控+時段規則,再用 response model 排序;有足夠隨機資料後才學 uplift。效用包含增量活動、打擾成本及發送限制,不以未校準開啟率直接選擇所有通知。
Start with preferences, caps, and timing rules, then a response ranker. Train uplift models once adequate randomized data exists. Utility combines incremental activity and interruption cost under constraints, rather than sending everything with a high predicted open rate.
04訓練與部署Training & deployment
線上處理事件去重、TTL 與使用者本地時間;跨裝置用 shared state 避免多發。發送 API 需冪等,排程後仍重查偏好;fallback 只依允許的規則處理,不補發已過期通知。
Deduplicate events, enforce TTLs and local time, and share state across devices. Use idempotent sends, recheck preferences at dispatch, and avoid replaying expired notifications. Fallback follows explicitly allowed rules.
Evaluate response calibration and uplift using randomized labels. Online, measure incremental activity, opt-outs, retention, and sends per user with stable holdouts, preserving essential notifications and user preferences.
Frequent messages can increase short-term returns while causing opt-outs. Add fatigue features and caps. Notifications may substitute for one another, so evaluate daily slates and total interruption cost, not only independent message scores.
I would define the task as returning a few useful complete queries for a prefix and context. A prefix index with popularity is the low-latency baseline, followed by intent-aware personalization. Tight deadlines favor using large models for offline candidate enrichment rather than generating at every keystroke.
白板資料流Whiteboard data flow
Prefix/localePrefix / locale
Cache/trie 候選Cache / trie candidates
趨勢與個人化融合Trend & personalization merge
安全/隱私過濾Safety / privacy filters
Top suggestionsSuggestions
選擇與搜尋結果Selection & search outcomes
01釐清產品目標Clarify product goals
問語言、拼字修正、熱門趨勢與個人化需求。練習假設 p95 50 ms server budget;主指標為省下輸入後的成功搜尋,護欄是錯誤引導、不當建議與尾延遲。
Clarify languages, typo tolerance, trends, and personalization. Assume a 50 ms server p95 budget for practice. Optimize reduced typing followed by successful search, with misleading/unsafe suggestions and tail latency as guardrails.
Log prefixes, suggestion impressions, selections, final queries, and search outcomes, accounting for position/acceptance bias. Keep private or rare queries out of public candidates. Split temporally and test unseen prefixes.
Start with a trie/FST, frequency, and recency decay. Add locale, session, and query-quality ranking. Use bounded typo/semantic expansion, with safety eligibility separate from relevance scores.
Cache common prefixes, incrementally refresh trends, and atomically replace indexes. Use debouncing and request sequence IDs to discard stale responses. Fall back to cached suggestions; handle empty prefixes and IME composition separately.
Popular queries may be noisy or manipulated, and short prefixes can reveal inappropriate information. Use privacy-conscious aggregation, candidate thresholds, and trend reliability checks. More personalization reduces cacheability and increases privacy complexity.
I would define success as a mutually accepted, useful connection rather than merely sending an invitation. Candidates come from mutual contacts and permitted contextual signals, with blocks and visibility preferences enforced. Ranking must account for both sender and recipient.
Clarify the surface, invitation frequency, and privacy settings. Optimize accepted, valuable connections, with ignores, blocks, reports, and recipient burden as guardrails. Enforce blocked/invisible relationships as hard exclusions.
Record exposures, invitations, acceptance, ignores, and downstream interaction. Acceptance is delayed, and no invitation is not rejection. Reconstruct graphs as of event time to prevent future-edge leakage; propagate privacy changes.
Start with common neighbors or Adamic–Adar, then graph embeddings/GNN retrieval and invite/conditional-accept ranking. Two-sided utility should not overwhelm popular recipients. Cold-start candidates can use voluntarily supplied, permitted context.
Precompute graph candidates and update new edges incrementally, bounding expansion around high-degree nodes. Recheck blocks, privacy, caps, and existing connections online, invalidating caches on revocation. Fall back to eligible candidates or an empty result.
High-degree people can dominate exposure and receive excessive invitations; enforce recipient-capacity and diversity constraints. Mutual contacts can reveal sensitive relationships, so explanations must use permitted signals. Reduce recommendations when precision is low.
I would define the cost of blocking legitimate mail and the recovery path, then establish rules and a lightweight text baseline. A layered risk system puts uncertain messages into recoverable quarantine and tracks sender and language drift.
Separate spam, phishing, and malware actions. Track inbox spam prevalence, with legitimate-mail false positives, latency, and recoverability as guardrails. Personal preferences should not override explicit safety constraints.
Use spam/not-spam corrections, audits, and reputation signals; inaction is not a reliable label. Split by time and campaign to avoid duplicate leakage. Track label provenance and protect message content.
Start with rules plus TF-IDF logistic regression or Naive Bayes, then evaluate text encoders and header/link features. Set risk-aware thresholds with high cost for legitimate-mail false positives; calibrate on natural traffic.
Use fast models in delivery and heavier follow-up analysis where appropriate. Version models, rules, and reputation separately. Shadow and canary changes, preserving inbox recovery. Define quarantine behavior for service failures.
離線 PR-AUC、recall at very low FPR、per-language calibration;用人工隨機抽樣估真實錯誤。線上受控 rollout 量測 inbox spam、合法信恢復與申訴,不只看使用者回報數。
Measure PR-AUC, recall at very low FPR, and language calibration, using random audits for real error rates. Controlled rollouts track inbox spam, legitimate-mail recovery, and complaints rather than report counts alone.
Obfuscation, sender rotation, and poisoning cause drift; maintain new-campaign holdouts and audited labels. Stricter thresholds reduce spam but may hide important mail, making quarantine and recovery central tradeoffs.
Only with class prevalence. An all-legitimate classifier may score highly when spam is rare. Evaluate recall at low FPR and the cost of lost legitimate mail.
17共通能力延伸Transfer practiceStripe Real-Time Fraud DetectionClassification / Real time / Delayed labels+
I would frame this as a cost-sensitive choice among approval, challenge, review, and decline. I would start with rules and GBDT, focusing on event-time features, delayed labels, and missing counterfactual outcomes for declined transactions.
Clarify authorization deadlines, amount distribution, verification actions, and review capacity. Optimize total decision cost including fraud, false declines, and friction, with legitimate approval, p99 latency, and appeal guardrails.
Join transaction IDs, devices, merchants, historical velocity, verification, and matured dispute/review labels. Define fraud carefully; not every dispute is fraud. Split by time and attack group, exclude post-decision information, and treat blocked outcomes as unobserved rather than automatically fraudulent.
Start with rules and GBDT; anomaly detection is an additional signal. Sequence/graph models need demonstrated incremental value. Calibrate risk and select actions using amount, false-decline cost, and review capacity rather than identical costs for every transaction.
Define event-time windows, deduplication, and out-of-order handling in streamed features. Align online features and training joins. Shadow/canary releases and use explicit risk-tier fallbacks on deadline failures. Retain reasons, versions, and auditability.
離線 PR-AUC、recall at fixed false-decline rate、amount-weighted loss 與 calibration;只用成熟標籤。線上在受控且允許的風險範圍內比較合法成功率、損失及 review load,等待損失窗口成熟,保留人工稽核。
Evaluate PR-AUC, recall at fixed false-decline rate, amount-weighted loss, and calibration on matured labels. Within permitted bounded risk, compare legitimate approvals, losses, and review load online. Wait for outcome maturity and retain manual audits.
Attack drift, stale features, and poisoning can degrade performance. Monitor freshness, slice risk, and matured losses. Reducing false declines may increase fraud, so tune challenge paths and review capacity as well as thresholds.
沒有被拒交易的真實結果,如何評估?How do you evaluate declined transactions without outcomes?
承認不可辨識的反事實,利用人工審查、驗證結果與風險受限的探索補標籤;不能把 accepted-only test set 當成全流量無偏估計。
Acknowledge unobserved counterfactuals. Use reviews, verification outcomes, and bounded exploration where appropriate; accepted-only test sets are not unbiased estimates for all traffic.
I would define a trend as growth relative to regional, language, and time-of-day baselines rather than total volume. Streaming aggregation generates candidates, clustering merges the same event, and user diversity/reliability checks precede freshness and quality ranking.
Clarify global versus local trends, update frequency, and personalization. Optimize timely relevant event discovery, with manipulation, duplicate topics, misleading labels, and detection-delay guardrails.
Collect event time, language, region, author, text, and interactions. Deduplicate reshares and distinguish unique authors. Label topic merges and trend quality, retain seasonal baselines, and remove deleted or non-public data.
Start with regional/language window counts and growth rates, then add seasonal residuals, unique authors, reliability, and semantic clustering. Smooth tiny baselines and require minimum support so 1→10 events do not automatically dominate.
Use event-time windows, watermarks, and late updates. Partition aggregation/clustering and handle hot-key skew. Publish timestamped versioned lists; on stream failure, serve a clearly aged prior list or pause the affected region.
Bot bursts, ambiguous names, and cross-language duplicates distort trends. Use author diversity, reliability checks, entity/time disambiguation, and human fallback. Shorter windows react faster but need persistence thresholds to avoid instability.
I would separate price prediction from pricing decisions. Historical booked prices are a baseline, not proof of the optimal price. We need demand estimates and uncertainty at different prices, with host limits and overrides.
Clarify advisory versus automatic pricing, revenue versus occupancy goals, horizon, and host constraints. Optimize matured net revenue per available night with cancellation, occupancy, adoption, and volatility guardrails.
Collect listing/date, availability, exposure, offered price, bookings, cancellations, and market context. Blocked/unlisted nights are not zero-demand observations. Booked-only data is selected, and events confound both prices and demand.
Start with seasonal comparable-listing medians. Model p(book | price, context), or a multi-day booking hazard, and optimize constrained expected net revenue including fees/cancellations. Observational association is not price elasticity; identification assumptions or controlled variation are required.
Generate horizon-based recommendations daily with event-driven updates. Version data, models, and decisions. Show explanations/uncertainty and host bounds. Use conservative comparable prices when data is sparse and recheck limits before publication.
Evaluate demand calibration, replayed revenue, and uncertainty coverage, while acknowledging backtests cannot prove counterfactual pricing gains. Consider market/listing clusters or switchbacks online, accounting for competition and booking horizons, and wait for cancellations/stays to mature.
New listings and events add uncertainty, while volatile prices hurt trust. Use intervals, rate-of-change bounds, and overrides. Short-term high prices may hurt occupancy or long-term value; evaluate the defined horizon rather than only the next booking.
為什麼「預測歷史成交價」不等於最佳定價?Why is predicting booked prices not optimal pricing?
它只學到舊政策下成功成交的價格;沒有估計其他價格的需求與未成交資料,無法直接識別收入最大值。
It learns successful prices under the old policy without identifying demand at alternatives or unbooked outcomes, so it does not identify the revenue optimum.
20共通能力延伸Transfer practiceUber ETA PredictionRegression / Spatiotemporal / Real time+
設計即時抵達時間預測,處理路況變化與不確定性。
Design real-time arrival-time prediction under changing traffic and uncertainty.
口說開場範例Spoken opening
我會先確認是叫車等待時間、接人 ETA 還是行程 ETA。以路由引擎的路段時間總和做 baseline,再學習 residual 與預測區間;更新頻率要兼顧準確和畫面穩定。
I would distinguish dispatch waiting time, pickup ETA, and trip ETA. A routing engine's segment-time sum is the baseline; learned residuals and prediction intervals improve it. Update frequency must balance accuracy with display stability.
白板資料流Whiteboard data flow
位置/路由Location / route
即時路況與歷史特徵Live traffic & historical features
ETA/quantile 模型ETA / quantile model
平滑與區間Smoothing & interval
顯示/重算Display / refresh
實際抵達Actual arrival
01釐清產品目標Clarify product goals
定義起終點、prediction timestamp、何謂到達與允許更新頻率。主指標為使用者感知 ETA error,護欄是尾端低估、更新抖動與延遲;等待與行程模型可分開。
Define origin/destination, prediction timestamp, arrival semantics, and refresh frequency. Optimize user-relevant ETA error with tail underestimation, jitter, and latency guardrails; waiting and travel models can differ.
Use GPS, map matching, route, time, traffic, and arrival events. Labels are remaining time from the prediction timestamp. Canceled trips are censored, not ordinary completions. Split by time/city and exclude future traffic.
03Baseline/模型Baseline & models
Baseline 為路段平均時間+轉彎/等候成本;GBDT residual model 容易起步,再比較 graph/sequence 模型。quantile loss 預測 p50/p90 等區間,處理誤差非對稱;檢查 quantile crossing。
Start with segment travel times plus turning/waiting costs, then a GBDT residual model before graph/sequence approaches. Quantile losses estimate p50/p90 and asymmetric uncertainty; check for quantile crossing.
Handle delayed GPS and outliers in traffic streams, caching segment features. Retrain periodically and monitor holidays/incidents. Fall back to routing estimates on timeout and smooth display updates without hiding real delays.
Measure MAE, p90 absolute error, quantile calibration, and city/route/weather slices; MAPE is unstable for very short trips. Online, track realized error, cancellations, and trust, considering selection effects when displayed ETAs change behavior.
GPS drift, closures, rare incidents, and rerouting cause errors. Use freshness checks, anomaly handling, intervals, and route refreshes. Frequent updates add cost and jitter, so choose frequency using experience metrics.
I would scope the perception task and operating conditions, separating perception from planning and control. The design covers temporal sensors, detection/tracking/spatial representations, and uncertainty. Validation requires replay, simulation, closed-course testing, and controlled deployment rather than ordinary web-style A/B testing for road safety.
Clarify sensors, operational design domain, weather/roads, output types, and end-to-end deadlines. Scope this to perception rather than a complete autonomous-driving system. Success combines scenario risk, miss rates, and worst-case latency.
Collect synchronized multi-view/temporal data, calibration parameters, 3D boxes/lanes/occupancy labels, and hard scenarios. Split by drive, geography, and time to avoid adjacent-frame leakage. Track label uncertainty and synthetic-data domain shift.
Start with a validated detector and tracker, then compare temporal fusion, multitask spatial representations, and applicable sensor fusion. Output state and uncertainty; low confidence must not be interpreted downstream as “no obstacle.”
Training may be distributed, but edge deployment requires thermal, memory, and deterministic-deadline profiling. Version models/calibration, shadow first, and expand under a validation plan. Sensor failures or out-of-domain conditions trigger predefined system-level degraded behavior.
Evaluate 3D detection, tracking, occupancy, and uncertainty by distance/occlusion, emphasizing consequential scenarios such as pedestrians and construction. Validate through replay, simulation, closed-course testing, and controlled shadowing. Aggregate mAP does not establish road safety.
Glare, unusual obstacles, calibration drift, and domain shifts are central failures. Maintain scenario suites, active hard-case selection, and sensor-health checks. Larger models can undermine deadline reliability; evaluate improvements with system-level risk.
為什麼 mAP 提升仍不代表更安全?Why does higher mAP not necessarily mean safer behavior?
平均值可能掩蓋少數高風險場景,且未包含時序穩定、校準與端到端行為;需場景風險和系統驗證。
Averages can hide rare consequential failures and omit temporal stability, calibration, and downstream behavior. Scenario risk and system validation remain necessary.
Understand shopping needs, retrieve products and ads, verify live prices/stock, and generate trustworthy recommendations with clear sponsorship labels.
完整深入篇Full deep dive
14 個章節、重畫架構圖、資料與 loss、即時工具、贊助排序、評估與 45 分鐘口說流程。
14 chapters, original diagrams, data and losses, live tools, sponsorship, evaluation, and a 45-minute rehearsal.
I would initially scope the assistant to comparison and recommendation, with purchases requiring separate user confirmation. It clarifies budget and hard constraints, retrieves and ranks products, and verifies prices/stock through authoritative tools. Generated claims use verified evidence. Relevance and sponsorship are explicit separate concerns, and success is completed shopping tasks with trust guardrails.
Bound the action scope. Ask whether the assistant recommends or buys, which merchant APIs exist, authentication, currency, and delivery region. For “a lightweight laptop under $500,” clarify intended use and required specifications. Optimize supported task completion, with incorrect prices, unavailable items, misleading sponsorship, tool errors, and cost as guardrails.
Connect dialogue, catalog, and tools. Log turn/request IDs, consented preferences, candidate/display sets, product versions, price timestamps, tool parameters/results, citations, and sponsorship flags. Labels include relevance, constraint satisfaction, factual accuracy, tool success, completion, and cancellations/returns. Split by time, product family, and user where appropriate.
Start with a workflow before an agent. Baseline constraint extraction, catalog search, and template comparison. Add hybrid/multimodal retrieval, ranking, and a bounded tool controller. Plan dynamically only when clarification or tool follow-up is needed. Enforce hard specifications, budget, and availability before ranking by relevance and utility; sponsored items must also meet eligibility/relevance thresholds.
Use explicit tool contracts. search_products returns identifiers and traceable metadata; get_price_stock(product_id, region) returns currency, price, stock, and timestamp. Enforce timeouts, schema validation, retry bounds, and circuit breakers. If buying is supported, show the final price/details for confirmation before executing with an idempotency key. Merchant text cannot authorize side effects.
Evaluate components and the whole task. Offline tests cover constraints, product Recall/NDCG, price freshness, claim groundedness, tool success, and sponsorship labeling. Include tool failures, conflicting specs, no valid products, and prompt injection. Online, track task success, satisfaction, cancellations/returns, cost, and latency, separating sponsored traffic and using blinded human review.
Price changes or stock-outs: revalidate and expose timestamps. Tool failure: do not invent values; show verified information and the gap. No eligible products: explain conflicting constraints and ask which can change. More autonomous agents add tool calls, cost, and uncertainty; use them only when measurable task gains justify the complexity.
A user wants “a lightweight 13–14 inch laptop for office work under US$500.” Parse currency, size, and use → retrieve catalog → enforce specifications → rank three options → check regional price, tax/shipping if available, and stock → explain tradeoffs with sources → label sponsorship → confirm item, quantity, and final total before any purchase. Explicitly identify excluded charges when the API does not provide them.
Enforce eligibility, relevance, and hard constraints before monetization; label sponsorship clearly. Monitor success and trust separately for organic and sponsored results, and prevent the generator from hiding or rewriting labels.
多步工具成功率為何重要?Why does multistep tool reliability matter?
Under a simplifying independence assumption, ten steps each succeeding with probability 0.98 yield about 0.98^10 ≈ 0.817 end-to-end success. Real failures may be correlated. Remove unnecessary steps, bound retries, and measure whole-task success rather than only individual tools.
03 / Explain the metric, not just its name
評估速查:每個指標回答什麼?What does each metric actually tell you?
指標Metric
定義與用途Meaning & use
常見盲點Pitfall
Recall@K
Top-K 找回的相關項目數 / 全部已知相關項目數。看候選階段有沒有漏掉好結果。Relevant items in the top K divided by all known relevant items. Diagnoses candidate omissions.
真實相關集合常不完整,需說明標籤來源;不是 ANN 與 exact kNN 的一致率。Relevance labels may be incomplete. Specify their source; this is not ANN agreement with exact kNN.
NDCG@K
用位置折扣計算排序效用,再除以理想排序。常用 DCG = Σ(2^rel−1)/log₂(rank+1)。Discounts relevance by rank, then normalizes by ideal ranking. A common DCG is Σ(2^rel−1)/log₂(rank+1).
需定義 relevance 等級與零 IDCG 的處理;分數好不保證增量產品價值。Define relevance grades and zero-IDCG handling. Gains do not establish incremental product value.
不衡量機率校準;PR-AUC 依正例率而變,不宜跨不同抽樣分布直接比較。Neither measures calibration. PR-AUC depends on prevalence and is not directly comparable across different sampling distributions.
Log loss / Brier
Binary log loss = −mean[y log p+(1−y) log(1−p)];Brier = mean[(p−y)²]。衡量機率預測。Binary log loss = −mean[y log p+(1−y) log(1−p)]; Brier = mean[(p−y)²]. Both score probability predictions.
混合了校準與區分能力;要搭配 reliability diagram、切片和自然分布評估。They combine calibration and discrimination effects. Add reliability diagrams, slices, and natural-distribution evaluation.
Groundedness / citations
檢查可驗證 claim 是否有提供的證據支持;引用 precision 看所引來源是否支持 claim。Check whether verifiable claims are supported by supplied evidence; citation precision checks support from the cited source.
有引用不等於來源正確、時效適用或回答完整;正確性、coverage、權限需分開測。Citations do not establish source truth, freshness, or completeness. Evaluate correctness, coverage, and access separately.
MAE / quantile coverage
MAE 看平均絕對誤差;預測 p90 應約有 90% 結果低於它,需按切片驗證。MAE measures average absolute error; about 90% of outcomes should fall below a calibrated p90 prediction, including within slices.
平均值可掩蓋極端低估;MAPE 對接近零的標籤不穩。Means can hide severe underestimation; MAPE is unstable near zero.
p95 / p99 / cost
端到端量測尾延遲,同時報吞吐、錯誤率與每成功任務成本。Measure end-to-end tail latency together with throughput, error rate, and cost per successful task.
階段 p95 不能直接相加;平均 latency 與 cache-hit-only 數字會掩蓋長尾。Stage p95 values are not additive. Mean latency and cache-hit-only measurements hide tails.
A/B · SRM · MDE
先定分流單位、主指標、最小可偵測效果與樣本量;SRM 檢查實際分組比例是否異常。Predefine randomization unit, primary metric, minimum detectable effect, and sample size. SRM checks anomalous allocation ratios.
先修資料問題;重複偷看、組間干擾、樣本不成熟都可能讓結論失真。Resolve data issues first. Peeking, interference, and immature outcomes can invalidate conclusions.
Make the experiment concrete: for orders/user, use stable user assignment, power calculations based on user-level variance, a predefined MDE, and a fixed observation window. Check SRM/logging before effect sizes and confidence intervals. Do not stop merely because one day's p-value drops below 0.05. Sequential testing needs a valid prespecified procedure. Shared ad budgets, social ties, and marketplaces may require different assignment designs.
Suggested sequence: use three 45-minute sessions for Ads, Products, and RAG. Next, compare Feed and Visual Search, then tackle the shopping assistant. Add Training, Cost, or Moderation where you need depth; use the remaining cases to practice transfer. Rehearse without answers, identify the stage where you stalled, then read and explain it again.
These are original papers and official technical resources. They support the linked concepts; architectures, SLOs, and decisions in the cases are synthesized recommendations, not official answer keys. Title-list reference: TensorTonic system-design page.