Practice

0/754 solved · 420 free, 334 Pro
ProblemTopicDifficulty
Compute every pairwise distance without a Python loopNumPy foundationsNumPy foundationsEasyOne-hot encode class labels with fancy indexingNumPy foundationsNumPy foundationsEasyRank leaderboard scores so ties share a placeNumPy foundationsNumPy foundationsEasyUndo a length sort with the inverse permutation from argsortNumPy foundationsNumPy foundationsEasyRemap sparse token ids to a compact vocabulary with np.uniqueNumPy foundationsNumPy foundationsEasyAverage values per group id with weighted bincountNumPy foundationsNumPy foundationsEasyDivide arrays safely with a fill value where the denominator is zeroNumPy foundationsNumPy foundationsEasyAdd per-query and per-document biases to a score matrix with broadcastingNumPy foundationsNumPy foundationsEasyTurn each row of counts into a probability distributionNumPy foundationsNumPy foundationsEasyPick the log-probability of the correct token at every positionNumPy foundationsNumPy foundationsEasyAverage only the real tokens in a padded batchNumPy foundationsNumPy foundationsMediumCut a token sequence into overlapping fixed-size windowsNumPy foundationsNumPy foundationsMediumAnswer many range-sum queries in constant time with prefix sumsNumPy foundationsNumPy foundationsMediumAssign sequences to length buckets with searchsorted and count paddingNumPy foundationsNumPy foundationsMediumCompute all pairwise Jaccard similarities from a binary matrixNumPy foundationsNumPy foundationsMediumBuild a causal mask that also blocks attention across packed documentsNumPy foundationsNumPy foundationsMediumSort a leaderboard by score, then latency, then name with np.lexsortNumPy foundationsNumPy foundationsMediumPad variable-length token lists into a batch with a maskNumPy foundationsNumPy foundationsMediumCompute a masked logsumexp that never overflowsNumPy foundationsNumPy foundationsMediumApply a numerically stable softmax inside each group of a flat arrayNumPy foundationsProNumPy foundationsProHardExtract strided, dilated windows with as_strided and no copiesNumPy foundationsProNumPy foundationsProHardSelect the top-k items inside every group without a Python loopNumPy foundationsProNumPy foundationsProHardReturn the top k values per row, sorted, with stable tie breakingNumPy foundationsProNumPy foundationsProHardBuild a cosine similarity matrix for a set of embeddingsLinear algebraLinear algebraEasyMeasure how much a rank-k approximation loses with the SVDLinear algebraLinear algebraEasyProject vectors onto the span of a few basis vectorsLinear algebraLinear algebraEasyCount the numerical rank of a matrix from its singular valuesLinear algebraLinear algebraEasyCompute a matrix's 2-norm condition number from its singular valuesLinear algebraLinear algebraEasyFind the main direction of your data with PCALinear algebraLinear algebraMediumOrthonormalise a set of vectors with Gram-SchmidtLinear algebraLinear algebraMediumSolve least squares with an SVD pseudo-inverse that drops tiny singular valuesLinear algebraLinear algebraMediumSolve a tridiagonal system in linear time with the Thomas algorithmLinear algebraLinear algebraMediumWrite a Cholesky factorisation and use it to solve a systemLinear algebraLinear algebraMediumFind the eigenvalue nearest a shift with inverse power iterationLinear algebraLinear algebraMediumFind the top k eigenpairs with power iteration and deflationLinear algebraProLinear algebraProHardCompute a QR decomposition with Householder reflectionsLinear algebraProLinear algebraProHardFactor a matrix as PA = LU with partial pivoting and get its determinantLinear algebraProLinear algebraProHardCheck a gradient with central differencesCalculus and gradientsCalculus and gradientsEasyDifferentiate a quadratic form when the matrix is not symmetricCalculus and gradientsCalculus and gradientsEasyDerive the gradient of mean squared error for a linear modelCalculus and gradientsCalculus and gradientsEasyBuild a Jacobian with central finite differencesCalculus and gradientsCalculus and gradientsEasyClassify a critical point from its HessianCalculus and gradientsCalculus and gradientsEasyDerive the gradient of softmax plus cross-entropyCalculus and gradientsCalculus and gradientsMediumDerive the gradient of cosine similarity with respect to one vectorCalculus and gradientsCalculus and gradientsMediumCompute the Hessian of the logistic regression lossCalculus and gradientsCalculus and gradientsMediumChoose a step size with Armijo backtracking line searchCalculus and gradientsCalculus and gradientsMediumDifferentiate the Gaussian negative log-likelihood with respect to mean and log sigmaCalculus and gradientsCalculus and gradientsMediumPush a gradient through tanh by the chain ruleCalculus and gradientsProCalculus and gradientsProHardTake a Hessian-free Newton step with finite-difference Hessian-vector productsCalculus and gradientsProCalculus and gradientsProHardDifferentiate a validation loss through a ridge regression solutionCalculus and gradientsProCalculus and gradientsProHardCheck lasso optimality with the KKT subgradient conditionsCalculus and gradientsProCalculus and gradientsProHardTrack mean and variance of a stream in one passProbability and statisticsProbability and statisticsEasyCompute the KL divergence between two diagonal GaussiansProbability and statisticsProbability and statisticsEasyCompare two token distributions with Jensen-Shannon divergenceProbability and statisticsProbability and statisticsEasySample categories from fixed uniforms with the inverse CDFProbability and statisticsProbability and statisticsEasyCompute the mean and variance of a discrete random variable and of aX + bProbability and statisticsProbability and statisticsEasyUpdate a discrete posterior over hypotheses after each observationProbability and statisticsProbability and statisticsEasyPut a Wilson score confidence interval on a success rateProbability and statisticsProbability and statisticsEasyCompare two classifiers on the same test set with McNemar's testProbability and statisticsProbability and statisticsEasyDecide if a new prompt really converts better with a two-proportion z-testProbability and statisticsProbability and statisticsMediumUpdate your belief about a model's pass rate with a Beta priorProbability and statisticsProbability and statisticsMediumPut a bootstrap confidence interval on an evaluation scoreProbability and statisticsProbability and statisticsMediumCompare two eval runs with Welch's t-test statisticProbability and statisticsProbability and statisticsMediumCompute Spearman rank correlation with averaged tie ranksProbability and statisticsProbability and statisticsMediumRun a two-sample permutation test for a difference in meansProbability and statisticsProbability and statisticsMediumCompute the chi-square test of independence for a contingency tableProbability and statisticsProbability and statisticsMediumBuild split conformal prediction intervals for a regressorProbability and statisticsProbability and statisticsMediumCompute the sample size per group for a two-proportion A/B testProbability and statisticsProbability and statisticsMediumEvaluate a multivariate Gaussian log-density stably with a Cholesky factorProbability and statisticsProProbability and statisticsProHardControl false discoveries across many eval comparisonsProbability and statisticsProProbability and statisticsProHardBuild conformal prediction sets for a classifier with adaptive scoresProbability and statisticsProProbability and statisticsProHardStandardise features without leaking test dataData processing and featuresData processing and featuresEasyScale features with the median and IQR so outliers do not dominateData processing and featuresData processing and featuresEasyEncode hour of day and day of week as sine and cosine featuresData processing and featuresData processing and featuresEasyClip outliers using percentiles learned on the training set onlyData processing and featuresData processing and featuresEasyTurn categorical tokens into a fixed-size vector with the hashing trickData processing and featuresData processing and featuresEasyCompute balanced class weights for an imbalanced datasetData processing and featuresData processing and featuresEasyFit a min-max scaler on train and apply it to testData processing and featuresData processing and featuresEasyOrdinal-encode a category column and map unseen values to -1Data processing and featuresData processing and featuresEasyImpute missing values with train medians and add missing-indicator columnsData processing and featuresData processing and featuresEasyCap outliers with IQR fences learned from training dataData processing and featuresData processing and featuresEasyBin a feature into equal-width buckets learned on trainData processing and featuresData processing and featuresEasyFind test rows that also appear in the training setData processing and featuresData processing and featuresEasyBuild stratified K-fold validation folds by dealing each class round-robinData processing and featuresData processing and featuresEasyExpand features into degree-2 polynomial and interaction termsData processing and featuresData processing and featuresEasySplit a dataset so every class keeps its shareData processing and featuresData processing and featuresMediumBin a feature into quantile buckets learned from training dataData processing and featuresData processing and featuresMediumFrequency-encode a category with a shared bucket for rare and unseen valuesData processing and featuresData processing and featuresMediumGenerate K-fold train and validation index splitsData processing and featuresData processing and featuresMediumRemove duplicate training texts after normalising themData processing and featuresData processing and featuresMediumOne-hot encode with an 'other' column for rare and unseen categoriesData processing and featuresData processing and featuresMediumFlag outliers with the modified z-score based on the medianData processing and featuresData processing and featuresMediumApply the Yeo-Johnson power transform for a given lambdaData processing and featuresData processing and featuresMediumExtract hour, weekday and cyclic time features from Unix timestampsData processing and featuresData processing and featuresMediumTarget-encode a category with smoothingData processing and featuresProData processing and featuresProHardFit imputation, scaling and one-hot encoding on train and apply them to testData processing and featuresProData processing and featuresProHardEstimate Jaccard similarity between documents with MinHash signaturesData processing and featuresProData processing and featuresProHardSplit folds by user so no user lands in both train and validationData processing and featuresProData processing and featuresProHardFill missing values from the k nearest rows (KNN imputation)Data processing and featuresProData processing and featuresProHardChoose the Box-Cox lambda by maximum likelihood over a gridData processing and featuresProData processing and featuresProHardFit linear regression in one line with the normal equationRegressionRegressionEasyFit a polynomial curve by expanding x into powersRegressionRegressionEasyCompute the elastic net penalty and its gradientRegressionRegressionEasyTrain logistic regression one gradient step at a timeRegressionRegressionMediumStop overfitting with ridge regressionRegressionRegressionMediumTrain a regression that shrugs off outliers with the Huber lossRegressionRegressionMediumFit weighted least squares in closed formRegressionRegressionMediumTake one gradient step for softmax regressionRegressionRegressionMediumCompute the quantile (pinball) lossRegressionRegressionMediumFit ridge regression with cyclic coordinate descentRegressionRegressionMediumFit Lasso with coordinate descent and soft thresholdingRegressionProRegressionProHardFit Poisson regression with Newton stepsRegressionProRegressionProHardCompute the Bayesian linear regression posteriorRegressionProRegressionProHardFit elastic net with an intercept by coordinate descentRegressionProRegressionProHardTrain L2-regularised logistic regression with Newton's methodRegressionProRegressionProHardCompute OLS coefficients, standard errors and t-statisticsRegressionProRegressionProHardFit isotonic regression with the pool adjacent violators algorithmRegressionProRegressionProHardScore ridge penalties with the leave-one-out shortcutRegressionProRegressionProHardClassify points by majority vote of their nearest neighboursSupervised modelsSupervised modelsEasyRun one epoch of the perceptron learning ruleSupervised modelsSupervised modelsEasyClassify by the nearest class centroidSupervised modelsSupervised modelsEasyCompute information gain for one splitSupervised modelsSupervised modelsEasyClassify with distance-weighted k nearest neighbour votesSupervised modelsSupervised modelsEasyFind the best decision tree split with Gini impuritySupervised modelsSupervised modelsMediumTrain a linear SVM with hinge loss subgradient descentSupervised modelsSupervised modelsMediumPredict with distance-weighted k nearest neighboursSupervised modelsSupervised modelsMediumRun one round of gradient boosting for squared errorSupervised modelsSupervised modelsMediumClassify word-count vectors with multinomial Naive BayesSupervised modelsSupervised modelsMediumClassify binary feature vectors with Bernoulli Naive BayesSupervised modelsSupervised modelsMediumCompute information gain and gain ratio for a categorical splitSupervised modelsSupervised modelsMediumScore a random forest with out-of-bag votesSupervised modelsSupervised modelsMediumFind the best split with the XGBoost gain formulaSupervised modelsSupervised modelsMediumFind Fisher's linear discriminant direction for two classesSupervised modelsSupervised modelsMediumPredict with Gaussian Naive BayesSupervised modelsProSupervised modelsProHardBoost decision stumps with AdaBoost and reweightingSupervised modelsProSupervised modelsProHardGrow a depth-limited regression treeSupervised modelsProSupervised modelsProHardRun one iteration of k-meansUnsupervised learningUnsupervised learningEasyPick spread-out starting centroids with farthest-first seedingUnsupervised learningUnsupervised learningEasyReport the explained variance ratio of PCAUnsupervised learningUnsupervised learningEasyCompute soft cluster memberships for a Gaussian mixtureUnsupervised learningProUnsupervised learningProMediumMerge points bottom-up with single linkage clusteringUnsupervised learningProUnsupervised learningProMediumPick k-means++ starting centers deterministicallyUnsupervised learningProUnsupervised learningProMediumMove points one mean-shift stepUnsupervised learningProUnsupervised learningProMediumRun k-means to convergence and re-seed empty clustersUnsupervised learningProUnsupervised learningProMediumProject data onto k principal components with the SVD and reconstruct itUnsupervised learningProUnsupervised learningProMediumScore a clustering with the Davies-Bouldin indexUnsupervised learningProUnsupervised learningProMediumScore a clustering with the silhouette coefficientUnsupervised learningProUnsupervised learningProHardFind dense clusters and noise points with DBSCANUnsupervised learningProUnsupervised learningProHardRun EM for a 1D Gaussian mixtureUnsupervised learningProUnsupervised learningProHardCompute t-SNE input affinities with a perplexity searchUnsupervised learningProUnsupervised learningProHardBuild an agglomerative clustering tree with complete or average linkageUnsupervised learningProUnsupervised learningProHardCompute precision, recall and F1 from predictionsEvaluation metricsEvaluation metricsEasyMeasure how overconfident a classifier is with expected calibration errorEvaluation metricsEvaluation metricsEasyBuild a confusion matrixEvaluation metricsEvaluation metricsEasyCompute mean reciprocal rankEvaluation metricsEvaluation metricsEasyPick a final answer by self-consistency majority voteEvaluation metricsEvaluation metricsEasyConvert language model loss to bits per byteEvaluation metricsEvaluation metricsEasyCompute R-squared and adjusted R-squared for a regressionEvaluation metricsEvaluation metricsEasyCompute the Matthews correlation coefficient for a binary classifierEvaluation metricsEvaluation metricsEasyCompute ROC AUC by counting ranked pairsEvaluation metricsEvaluation metricsMediumGrade a search ranking with NDCG at kEvaluation metricsEvaluation metricsMediumCompute macro and micro F1 for a multi-class classifierEvaluation metricsEvaluation metricsMediumMeasure rater agreement with Cohen's kappaEvaluation metricsEvaluation metricsMediumEstimate pass@k without biasEvaluation metricsEvaluation metricsMediumCompute ROUGE-L F1 from the longest common subsequenceEvaluation metricsEvaluation metricsMediumExtract and normalise a final answer for a math verifierEvaluation metricsEvaluation metricsMediumScore pairwise LLM-judge results with position swappingEvaluation metricsEvaluation metricsMediumCompute exact match and token F1 for QA answersEvaluation metricsEvaluation metricsMediumCompute the points of a ROC curve with tied scoresEvaluation metricsEvaluation metricsMediumPick the decision threshold that maximises F1Evaluation metricsEvaluation metricsMediumBuild a precision recall curve and average precision with tied scoresEvaluation metricsProEvaluation metricsProHardCompute sentence BLEU with brevity penaltyEvaluation metricsProEvaluation metricsProHardScore multiple-choice answers by log-likelihoodEvaluation metricsProEvaluation metricsProHardEvaluate perplexity of a long text with a strided sliding windowEvaluation metricsProEvaluation metricsProHardBatch LM cross-entropy with ignore index, perplexity and gradientEvaluation metricsProEvaluation metricsProHardCalibrate classifier scores with Platt scalingEvaluation metricsProEvaluation metricsProHardCompare two clusterings with the adjusted Rand indexEvaluation metricsProEvaluation metricsProHardSmooth a noisy metric with an exponential moving averageTime seriesTime seriesEasyGenerate walk-forward train and test windows for backtestingTime seriesTime seriesEasyCompute a trailing rolling meanTime seriesTime seriesEasyCompute symmetric MAPETime seriesTime seriesEasyForecast with the seasonal naive methodTime seriesTime seriesEasyBuild lag and difference features for forecastingTime seriesTime seriesMediumFind the weekly pattern with autocorrelationTime seriesTime seriesMediumForecast a trending series with Holt's linear smoothingTime seriesTime seriesMediumCompute mean absolute scaled errorTime seriesTime seriesMediumSplit a series into trend, seasonal and residualTime seriesTime seriesMediumDetect a mean shift with CUSUMTime seriesTime seriesMediumPick the smoothing factor of simple exponential smoothing by one-step errorTime seriesTime seriesMediumTest residuals for leftover autocorrelation with the Ljung-Box statisticTime seriesTime seriesMediumFit an AR(p) model by least squares and forecast several steps aheadTime seriesProTime seriesProHardFilter a noisy signal with a 1D Kalman filterTime seriesProTime seriesProHardCompute the partial autocorrelation function with Durbin-LevinsonTime seriesProTime seriesProHardMeasure hit rate and recall at k for a recommenderRecommender systemsRecommender systemsEasyCompute the BPR ranking loss for implicit feedback without overflowRecommender systemsRecommender systemsEasyRecommend the most popular unseen itemsRecommender systemsRecommender systemsEasyMeasure catalog coverage of recommendationsRecommender systemsRecommender systemsEasyRank trending items with time-decayed popularityRecommender systemsRecommender systemsEasyBlend personal and popular scores for cold-start usersRecommender systemsRecommender systemsEasyMeasure intra-list diversity of a recommendation listRecommender systemsRecommender systemsEasyRecommend the next item from session transition countsRecommender systemsRecommender systemsEasyPredict a rating from similar usersRecommender systemsProRecommender systemsProMediumTake one SGD step of matrix factorisationRecommender systemsProRecommender systemsProMediumRecommend unseen items with item-item cosine similarityRecommender systemsProRecommender systemsProMediumSample negative items a user has not interacted withRecommender systemsProRecommender systemsProMediumCompute mean average precision at kRecommender systemsProRecommender systemsProMediumRecommend related items by co-occurrence liftRecommender systemsProRecommender systemsProMediumTake one SGD step of Bayesian personalized rankingRecommender systemsProRecommender systemsProMediumPredict with a factorization machine in linear timeRecommender systemsProRecommender systemsProMediumRe-rank a feed with per-creator caps and a no-repeat windowRecommender systemsProRecommender systemsProMediumRun one full alternating least squares sweep on observed ratingsRecommender systemsProRecommender systemsProHardCorrect in-batch softmax for item popularityRecommender systemsProRecommender systemsProHardSolve user factors in implicit-feedback ALS with confidence weightsRecommender systemsProRecommender systemsProHardCompare two rankers online with team-draft interleavingRecommender systemsProRecommender systemsProHardImplement GELU, the activation inside GPT and BERTActivationsActivationsEasyCompute softplus without overflowing on large inputsActivationsActivationsEasyImplement ELU and its derivativeActivationsActivationsEasyImplement hard swishActivationsActivationsEasyFind the fraction of dead ReLU unitsActivationsActivationsEasyImplement PReLU with a learnable slope per channelActivationsActivationsEasyCompute maxout units and which piece wonActivationsActivationsEasyWrite a sigmoid and log-sigmoid that never overflowActivationsActivationsMediumReturn SiLU and its exact derivative for the backward passActivationsActivationsMediumImplement mish and its gradientActivationsActivationsMediumBuild the SwiGLU feed-forward block used in LlamaActivationsProActivationsProHardForward and backward pass for GLU, ReGLU, SwiGLU and GEGLU gatesActivationsProActivationsProHardImplement sparsemaxActivationsProActivationsProHardBinary cross-entropy straight from logitsLossesLossesEasyCross-entropy with label smoothing from raw logitsLossesLossesEasyCompute the multiclass hinge lossLossesLossesEasyCompute the soft Dice lossLossesLossesEasyCompute smooth L1 box regression loss over positive anchorsLossesLossesEasyDown-weight easy examples with focal lossLossesLossesMediumToken-level distillation KL that ignores paddingLossesLossesMediumCompute batch-hard triplet lossLossesLossesMediumCompute class-weighted cross-entropyLossesLossesMediumTrain embeddings with the InfoNCE contrastive lossLossesProLossesProHardSymmetric contrastive loss and its gradient with respect to the similarity matrixLossesProLossesProHardCompute the supervised contrastive lossLossesProLossesProHardAdd momentum to gradient descentOptimizersOptimizersEasyClip a list of gradients by their combined global normOptimizersOptimizersEasyTake a Nesterov momentum stepOptimizersOptimizersEasyCompute the Noam warmup learning rateOptimizersOptimizersEasyCompute an exponentially weighted average with bias correctionOptimizersOptimizersEasyRun Adagrad on a quadratic with uneven curvatureOptimizersOptimizersEasySimulate reduce-learning-rate-on-plateauOptimizersOptimizersEasyImplement one step of the Adam optimizerOptimizersOptimizersMediumRun the sign-based Lion optimizer with decoupled weight decayOptimizersOptimizersMediumTake a centered RMSProp stepOptimizersOptimizersMediumWrap an optimizer with LookaheadOptimizersOptimizersMediumRun Adadelta, the optimizer with no learning rateOptimizersOptimizersMediumBuild a warmup plus cosine schedule with warm restartsOptimizersOptimizersMediumClip gradients unit-wise relative to weight norms (AGC)OptimizersOptimizersMediumAdamW with linear warmup and cosine decayOptimizersProOptimizersProHardMinimise a quadratic with AdamW, bias correction and a no-decay maskOptimizersProOptimizersProHardCompute Adafactor's factored second momentOptimizersProOptimizersProHardBackward pass of a dense layerNeural networksNeural networksEasyCompute Xavier and He initialisation scales for dense and conv weightsNeural networksNeural networksEasyCount the parameters of an MLPNeural networksNeural networksEasyFind where early stopping haltsNeural networksNeural networksEasyRun an MLP forward pass and keep every layer's activationNeural networksNeural networksEasyAdd L1 and L2 penalties and their gradients to weight matrices onlyNeural networksNeural networksEasyMeasure the vanishing gradient through a chain of sigmoid layersNeural networksNeural networksEasyApply drop path (stochastic depth) to a residual branchNeural networksNeural networksEasyImplement inverted dropoutNeural networksNeural networksMediumForward pass of a pre-norm residual MLP blockNeural networksNeural networksMediumBackpropagate through an embedding lookupNeural networksNeural networksMediumBackpropagate through a 2-layer tanh net for regression and binary classificationNeural networksNeural networksMediumTrace activation spread through deep ReLU layers for Xavier and He initNeural networksNeural networksMediumRun one training epoch with full-batch, mini-batch or SGD updatesNeural networksNeural networksMediumEstimate prediction uncertainty with Monte Carlo dropoutNeural networksNeural networksMediumTrain a tiny MLP to learn XORNeural networksProNeural networksProHardBackprop a 2-layer ReLU MLP with softmax cross-entropy, ignored labels and weight decayNeural networksProNeural networksProHardBackpropagate through a residual MLP blockNeural networksProNeural networksProHardOrder a compute graph for backprop with a topological sortAutogradAutogradEasyRun reverse mode over an op tape where values are reusedAutogradAutogradEasyWrite the backward pass of a matrix multiplyAutogradAutogradEasyRun forward-mode autodiff over a tiny instruction listAutogradAutogradEasyBuild a tiny reverse-mode autograd engineAutogradAutogradMediumReduce a broadcast gradient back to the input's shapeAutogradAutogradMediumRoute gradients through a max reductionAutogradAutogradMediumCompute a gradient on a DAG with memoized backpropAutogradAutogradMediumBackprop through softmax without building the JacobianAutogradProAutogradProHardBuild a Value autograd class that survives very deep graphsAutogradProAutogradProHardBackprop a deep tanh chain with gradient checkpointingAutogradProAutogradProHardNormalize activations with RMSNormNormalizationNormalizationEasyImplement LayerNorm forwardNormalizationNormalizationEasyStandardise conv weights per output channelNormalizationNormalizationEasyApply batch norm to conv feature maps per channelNormalizationNormalizationEasyApply instance normalization to imagesNormalizationNormalizationEasyBatchNorm with running statistics for inferenceNormalizationNormalizationMediumImplement GroupNorm with contiguous channel groupsNormalizationNormalizationMediumFold an eval-mode batch norm into the preceding linear layerNormalizationNormalizationMediumDerive the LayerNorm backward passNormalizationProNormalizationProHardDerive the BatchNorm training-mode backward pass for 2-D and 4-D inputsNormalizationProNormalizationProHardImplement the backward pass of group normalizationNormalizationProNormalizationProHardWrite a 2D convolution with stride and paddingComputer visionComputer visionEasyTrack feature map sizes through a stack of dilated convolutionsComputer visionComputer visionEasyConvert an image batch from NHWC to NCHWComputer visionComputer visionEasyBuild a normalised 2D Gaussian kernelComputer visionComputer visionEasyCompare parameters and multiply-adds of standard vs depthwise separable convComputer visionComputer visionEasyCompute the receptive field of a stack of conv layersComputer visionComputer visionEasyCenter-crop a U-Net skip connection and concatenateComputer visionComputer visionEasyHorizontally flip and crop an image together with its boxesComputer visionComputer visionEasyMax pooling forward and backwardComputer visionProComputer visionProMediumDetect edges with Sobel filters and a magnitude thresholdComputer visionProComputer visionProMediumUnfold image patches with im2colComputer visionProComputer visionProMediumResize an image with bilinear interpolationComputer visionProComputer visionProMediumRun a depthwise separable conv block forwardComputer visionProComputer visionProMediumImplement average pooling forward and backward with overlapping windowsComputer visionProComputer visionProMediumApply a squeeze-and-excitation block to feature mapsComputer visionProComputer visionProMediumGenerate anchor boxes over a feature map gridComputer visionProComputer visionProMediumCompute IoU and generalized IoU for box pairsComputer visionProComputer visionProMediumBlur an image with a separable Gaussian filter and reflect paddingComputer visionProComputer visionProMediumTrace tensor shapes and parameter counts through a LeNet-style CNNComputer visionProComputer visionProMediumImplement pixel shuffle (depth to space) upsamplingComputer visionProComputer visionProMediumEncode ground-truth boxes as regression deltas from anchorsComputer visionProComputer visionProMediumRemove duplicate detections with IoU and non-max suppressionComputer visionProComputer visionProHardAssign anchor boxes to ground-truth objects for detector trainingComputer visionProComputer visionProHardImplement a single-channel transposed convolutionComputer visionProComputer visionProHardImplement a multi-channel grouped conv2d with stride, padding and dilationComputer visionProComputer visionProHardImplement the backward pass of a strided multi-channel conv2dComputer visionProComputer visionProHardBuild an Inception module: four branches concatenated on channelsComputer visionProComputer visionProHardRescore overlapping detections with Gaussian soft-NMSComputer visionProComputer visionProHardImplement RoI max pooling for region featuresComputer visionProComputer visionProHardBuild YOLO-style training targets on a grid with anchorsComputer visionProComputer visionProHardRun a vanilla RNN over a sequenceSequence modelsSequence modelsEasyDecode a CTC output with best-path greedy decodingSequence modelsSequence modelsEasyPick the last real hidden state of each sequenceSequence modelsSequence modelsEasyBuild teacher-forcing decoder inputsSequence modelsSequence modelsEasyBatchify a token stream for truncated backprop through timeSequence modelsSequence modelsEasyImplement one step of an LSTM cellSequence modelsProSequence modelsProMediumRun one step of a GRU cell on a batchSequence modelsProSequence modelsProMediumDecode the best HMM path with ViterbiSequence modelsProSequence modelsProMediumCompute Bahdanau additive attentionSequence modelsProSequence modelsProMediumRun a stacked (multi-layer) RNN over a sequenceSequence modelsProSequence modelsProMediumCarry RNN state through padding with a maskSequence modelsProSequence modelsProMediumCompute a Luong attention step with dot or general scoringSequence modelsProSequence modelsProMediumBackpropagate through time in a linear RNNSequence modelsProSequence modelsProHardCompute the CTC loss with the forward algorithm in log spaceSequence modelsProSequence modelsProHardCompute HMM state posteriors with forward-backwardSequence modelsProSequence modelsProHardRun a bidirectional RNN on padded sequences of different lengthsSequence modelsProSequence modelsProHardUnroll a seq2seq decoder with scheduled teacher forcingSequence modelsProSequence modelsProHardImplement the backward pass of one LSTM cell stepSequence modelsProSequence modelsProHardScore words by TF-IDFTokenization and NLPTokenization and NLPEasyEncode text with a byte fallback so no character is ever unknownTokenization and NLPTokenization and NLPEasyNormalize text by lowercasing, stripping accents and collapsing spacesTokenization and NLPTokenization and NLPEasyCount word n-grams and return the k most frequent with stable tiesTokenization and NLPTokenization and NLPEasyBuild a bag-of-words count matrix over a fixed vocabularyTokenization and NLPTokenization and NLPEasyTurn WordPiece tokens back into text by merging ## piecesTokenization and NLPTokenization and NLPEasyPre-tokenize text into words, numbers and symbolsTokenization and NLPTokenization and NLPEasyExtract character n-grams with boundary markersTokenization and NLPTokenization and NLPEasyDecode SentencePiece pieces back to textTokenization and NLPTokenization and NLPEasyBuild next-token training pairs with a sliding window and strideTokenization and NLPTokenization and NLPEasyMeasure tokenizer compression and fertility on a text sampleTokenization and NLPTokenization and NLPEasyJoin word tokens back into readable textTokenization and NLPTokenization and NLPEasyDo one merge step of a BPE tokenizerTokenization and NLPTokenization and NLPMediumCompute Levenshtein edit distanceTokenization and NLPTokenization and NLPMediumTokenize words with WordPiece greedy longest matchTokenization and NLPTokenization and NLPMediumBuild a vocabulary with special tokens, a minimum frequency and UNKTokenization and NLPTokenization and NLPMediumRank documents for a query with smoothed TF-IDF and cosine similarityTokenization and NLPTokenization and NLPMediumClean text with stopword removal and a rule-based suffix stemmerTokenization and NLPTokenization and NLPMediumTruncate a sentence pair to a token budget with the longest-first strategyTokenization and NLPTokenization and NLPMediumEncode a word with ranked BPE mergesTokenization and NLPTokenization and NLPMediumMap tokens back to character offsetsTokenization and NLPTokenization and NLPMediumSplit text so special tokens stay wholeTokenization and NLPTokenization and NLPMediumMap raw bytes to printable characters for byte-level BPETokenization and NLPTokenization and NLPMediumTrain a bigram language model and measure perplexityTokenization and NLPProTokenization and NLPProHardFind the most likely segmentation with a unigram model and ViterbiTokenization and NLPProTokenization and NLPProHardEncode a batch with CLS and SEP, truncation, padding side and an attention maskTokenization and NLPProTokenization and NLPProHardRecover the edit operations behind a Levenshtein distance by backtrackingTokenization and NLPProTokenization and NLPProHardFind collocations by ranking bigrams with pointwise mutual informationTokenization and NLPProTokenization and NLPProHardScore bigrams with interpolated Kneser-NeyTokenization and NLPProTokenization and NLPProHardRetrieve the top-k chunks for a query embeddingEmbeddings and RAGEmbeddings and RAGEasyMerge several retrievers' rankings with reciprocal rank fusionEmbeddings and RAGEmbeddings and RAGEasyTruncate Matryoshka embeddings and renormaliseEmbeddings and RAGEmbeddings and RAGEasyMeasure recall at k of an approximate indexEmbeddings and RAGEmbeddings and RAGEasyRerank retrieved chunks in two stages with a score thresholdEmbeddings and RAGEmbeddings and RAGEasyReorder retrieved chunks so the best sit at the edges of the promptEmbeddings and RAGEmbeddings and RAGEasySplit a document into overlapping chunksEmbeddings and RAGEmbeddings and RAGMediumCombine keyword and vector scores with min-max normalizationEmbeddings and RAGEmbeddings and RAGMediumSearch binary-quantised embeddings by Hamming distanceEmbeddings and RAGEmbeddings and RAGMediumChunk text by sentences under a token budgetEmbeddings and RAGEmbeddings and RAGMediumChunk a document at semantic breakpoints between sentencesEmbeddings and RAGEmbeddings and RAGMediumPack retrieved chunks into a token budget for the promptEmbeddings and RAGEmbeddings and RAGMediumRemove near-duplicate chunks with word shingles and Jaccard similarityEmbeddings and RAGEmbeddings and RAGMediumRank documents with BM25Embeddings and RAGProEmbeddings and RAGProHardRe-rank retrieved chunks for diversity with maximal marginal relevanceEmbeddings and RAGProEmbeddings and RAGProHardSearch an inverted-file (IVF) vector indexEmbeddings and RAGProEmbeddings and RAGProHardScore vectors with product-quantisation lookup tablesEmbeddings and RAGProEmbeddings and RAGProHardGenerate sinusoidal position encodingsAttention and transformersAttention and transformersEasyMeasure how focused each attention row is with entropyAttention and transformersAttention and transformersEasyCount attention FLOPs for a sequenceAttention and transformersAttention and transformersEasyAdd token and position embeddings for a GPT input batchAttention and transformersAttention and transformersEasyShow that an embedding lookup is a one-hot matrix multiplyAttention and transformersAttention and transformersEasyWrite scaled dot-product attention with a causal maskAttention and transformersAttention and transformersMediumSplit and merge attention headsAttention and transformersAttention and transformersMediumBuild the ALiBi attention bias for every headAttention and transformersAttention and transformersMediumApply a key padding mask in batched attentionAttention and transformersAttention and transformersMediumBucket relative positions like T5Attention and transformersAttention and transformersMediumScale RoPE frequencies with NTK-aware interpolationAttention and transformersAttention and transformersMediumApply a causal mask when queries are fewer than keysAttention and transformersAttention and transformersMediumSplit a fused QKV checkpoint weight into separate projectionsAttention and transformersAttention and transformersMediumImplement the original post-norm transformer blockAttention and transformersAttention and transformersMediumAdd QK-norm to multi-head causal attentionAttention and transformersAttention and transformersMediumCount the parameters of a GPT-2 style modelAttention and transformersAttention and transformersMediumRotate a vector by its position (RoPE)Attention and transformersProAttention and transformersProHardRun a full pre-norm transformer block forward passAttention and transformersProAttention and transformersProHardBackpropagate through scaled dot-product attentionAttention and transformersProAttention and transformersProHardCompute the gradient of a tied input and output embeddingAttention and transformersProAttention and transformersProHardConvert a GPT block to a Llama-style block (RMSNorm, RoPE, SwiGLU)Attention and transformersProAttention and transformersProHardTurn logits into probabilities without overflowingSampling and decodingSampling and decodingEasyKeep only the k most likely tokens before samplingSampling and decodingSampling and decodingEasyFilter the next-token distribution with min-pSampling and decodingSampling and decodingEasyGreedy decode until end of sequenceSampling and decodingSampling and decodingEasyBan tokens and repeated n-grams before samplingSampling and decodingSampling and decodingEasyRank finished beams with a length penaltySampling and decodingSampling and decodingEasyReturn the chosen token's log-prob and the top alternativesSampling and decodingSampling and decodingEasyKeep the nucleus: top-p filteringSampling and decodingSampling and decodingMediumApply repetition, frequency and presence penalties to logitsSampling and decodingSampling and decodingMediumFilter logits with locally typical samplingSampling and decodingSampling and decodingMediumRun batched greedy decoding with per-row EOS trackingSampling and decodingSampling and decodingMediumScore next tokens with contrastive decodingSampling and decodingSampling and decodingMediumDecode with beam searchSampling and decodingProSampling and decodingProHardGenerate a sequence with temperature, top-k, top-p and fixed random drawsSampling and decodingProSampling and decodingProHardDecode under a finite-state grammarSampling and decodingProSampling and decodingProHardTrim a chat history to fit the context windowLLM inference and servingLLM inference and servingEasyWork out how many tokens fit in GPU memory for the KV cacheLLM inference and servingLLM inference and servingEasyCompute TTFT, TPOT and throughput from request timestampsLLM inference and servingLLM inference and servingEasyPrice an API request with cached input tokensLLM inference and servingLLM inference and servingEasySize concurrency with Little's lawLLM inference and servingLLM inference and servingEasyWrite new keys and values into a preallocated batched KV cacheLLM inference and servingLLM inference and servingEasyPick the best draft length for speculative decodingLLM inference and servingLLM inference and servingEasyMeasure goodput against TTFT and TPOT SLOsLLM inference and servingLLM inference and servingEasyMeasure the wasted slots of static batchingLLM inference and servingLLM inference and servingEasyRate limit API requests with a token bucketLLM inference and servingLLM inference and servingEasySize prefill and decode pools for disaggregated servingLLM inference and servingLLM inference and servingEasyGenerate one token at a time with a KV cacheLLM inference and servingLLM inference and servingMediumAllocate KV cache memory in pages, like vLLMLLM inference and servingProLLM inference and servingProMediumVerify a draft model's guesses in speculative decodingLLM inference and servingProLLM inference and servingProMediumIs decoding memory-bound? A roofline estimateLLM inference and servingProLLM inference and servingProMediumCount prefix cache hits with a token trie and block granularityLLM inference and servingProLLM inference and servingProMediumEvict KV cache blocks with an LRU policyLLM inference and servingProLLM inference and servingProMediumGather a paged KV cache through a block tableLLM inference and servingProLLM inference and servingProMediumRun a paged KV block allocator with a free listLLM inference and servingProLLM inference and servingProMediumRoute requests to replicas by shared prompt prefixLLM inference and servingProLLM inference and servingProMediumServe many LoRA adapters in one batchLLM inference and servingProLLM inference and servingProMediumCompare FCFS and shortest-job-first latency for LLM requestsLLM inference and servingProLLM inference and servingProMediumSimulate continuous batchingLLM inference and servingProLLM inference and servingProHardSimulate a chunked prefill scheduler with a per-step token budgetLLM inference and servingProLLM inference and servingProHardAccept or reject draft tokens in speculative samplingLLM inference and servingProLLM inference and servingProHardSimulate KV memory preemption with recomputeLLM inference and servingProLLM inference and servingProHardTrack shared KV blocks with copy-on-write for beam searchLLM inference and servingProLLM inference and servingProHardStream text safely when stop sequences can span chunksLLM inference and servingProLLM inference and servingProHardPer-channel vs per-tensor int8: measure the errorQuantizationQuantizationEasyQuantize activations to uint8 with a scale and zero pointQuantizationQuantizationEasyUnpack int4 weights from bytesQuantizationQuantizationEasyQuantize with stochastic rounding from given random drawsQuantizationQuantizationEasyWork out effective bits per weight and model size for group quantizationQuantizationQuantizationEasyQuantize weights to int8 and measure the errorQuantizationProQuantizationProMediumGroup-wise int4 quantization like GPTQ and AWQ checkpointsQuantizationProQuantizationProMediumSearch for an activation-aware per-channel scale before int4 roundingQuantizationProQuantizationProMediumRound float32 to bfloat16QuantizationProQuantizationProMediumMigrate activation outliers with SmoothQuant scalesQuantizationProQuantizationProMediumMultiply int8 activations by int8 weights and dequantizeQuantizationProQuantizationProMediumQuantize a KV cache to int8 per token and headQuantizationProQuantizationProMediumBackpropagate through fake quantization with a learned scaleQuantizationProQuantizationProMediumSearch the clipping range that minimizes quantization errorQuantizationProQuantizationProMediumRun a matrix-vector product on packed 4-bit weights with zero pointsQuantizationProQuantizationProMediumRequantize an int32 accumulator with a fixed-point multiplierQuantizationProQuantizationProMediumBlock-wise 4-bit codebook quantization with double-quantized scalesQuantizationProQuantizationProHardQuantise a weight row GPTQ-style with error feedbackQuantizationProQuantizationProHardQuantize weights to 4-bit groups while keeping salient columns in floatQuantizationProQuantizationProHardSplit outlier features into a float matmul and the rest into int8QuantizationProQuantizationProHardRound float values to the FP8 E4M3 formatQuantizationProQuantizationProHardRotate activations with a Hadamard matrix before 4-bit quantizationQuantizationProQuantizationProHardLimit attention to a sliding window of recent tokensEfficient architecturesEfficient architecturesEasyCompare KV cache size for multi-head, grouped-query and latent attentionEfficient architecturesEfficient architecturesEasyCount total and active parameters of an MoE layerEfficient architecturesEfficient architecturesEasyCompute model FLOPs utilization (MFU) for a training runEfficient architecturesEfficient architecturesEasyEstimate KV cache memory with cross-layer KV sharingEfficient architecturesEfficient architecturesEasyChoose which positions stay in an attention-sink streaming cacheEfficient architecturesEfficient architecturesEasyBuild a local plus global attention maskEfficient architecturesEfficient architecturesEasyPrune weights to 2:4 structured sparsityEfficient architecturesEfficient architecturesEasyCompute savings from confidence-based early exitEfficient architecturesEfficient architecturesEasyShare keys and values across heads with grouped-query attentionEfficient architecturesProEfficient architecturesProMediumRoute each token to its top 2 experts in a mixture of expertsEfficient architecturesProEfficient architecturesProMediumCausal linear attention with a running stateEfficient architecturesProEfficient architecturesProMediumRoute tokens with expert capacity and drop the overflowEfficient architecturesProEfficient architecturesProMediumRoute tokens with Mixture-of-DepthsEfficient architecturesProEfficient architecturesProMediumImplement top-k sparse attention per queryEfficient architecturesProEfficient architecturesProMediumEvict KV cache entries while keeping heavy hitters and recent tokensEfficient architecturesProEfficient architecturesProMediumPick the rank that keeps a target energy in a low-rank factorizationEfficient architecturesProEfficient architecturesProMediumCompute the Switch Transformer load-balancing lossEfficient architecturesProEfficient architecturesProHardDecode with a sliding-window KV cache stored as a ring bufferEfficient architecturesProEfficient architecturesProHardMerge similar tokens with bipartite matchingEfficient architecturesProEfficient architecturesProHardSelect key blocks by compressed scores, then attend inside themEfficient architecturesProEfficient architecturesProHardCompute multi-head latent attention scores from the latent cacheEfficient architecturesProEfficient architecturesProHardRun the gated delta rule for linear attentionEfficient architecturesProEfficient architecturesProHardCount LoRA's trainable parametersFine-tuningFine-tuningEasyEstimate GPU memory for QLoRA-style fine-tuningFine-tuningFine-tuningEasyMask prompt tokens out of the SFT lossFine-tuningFine-tuningEasyRender chat messages into a model prompt stringFine-tuningFine-tuningEasySwap one merged LoRA adapter for anotherFine-tuningFine-tuningEasyCount trainable parameters when freezing most of a modelFine-tuningFine-tuningEasyLoRA forward pass and weight mergeFine-tuningProFine-tuningProMediumAttention with trainable prefix keys and values (prefix tuning)Fine-tuningProFine-tuningProMediumPack examples into fixed-length training rowsFine-tuningProFine-tuningProMediumCompute a DoRA adapted weightFine-tuningProFine-tuningProMediumWrite an SFT collate function that shifts, pads and masks labelsFine-tuningProFine-tuningProMediumCompare token-mean and sequence-mean SFT loss reductionsFine-tuningProFine-tuningProMediumTurn an LM head into a classifier with label wordsFine-tuningProFine-tuningProMediumMerge several LoRA adapters into one weight with weightsFine-tuningProFine-tuningProMediumMake gradient accumulation match one big batchFine-tuningProFine-tuningProHardBackward pass of a LoRA layer with adapter dropoutFine-tuningProFine-tuningProHardMerge fine-tuned models with TIESFine-tuningProFine-tuningProHardExtract a LoRA adapter from a full fine-tune with SVDFine-tuningProFine-tuningProHardFine-tune a classifier on the last real token's hidden stateFine-tuningProFine-tuningProHardTrain a reward model with the Bradley-Terry lossAlignmentAlignmentEasyScore a reward model by pairwise preference accuracyAlignmentAlignmentEasyEstimate KL divergence from samples three waysAlignmentAlignmentEasyCompute the IPO preference lossAlignmentAlignmentEasyAdd label smoothing to the DPO loss (conservative DPO)AlignmentAlignmentEasyCompute batched GRPO advantages and filter zero-signal groupsAlignmentAlignmentEasyCompute RLOO leave-one-out baselinesAlignmentAlignmentEasyCompute the DPO loss from log-probabilitiesAlignmentProAlignmentProMediumBuild per-token RLHF rewards with a KL penaltyAlignmentProAlignmentProMediumCompute the KTO loss for unpaired feedbackAlignmentProAlignmentProMediumCompute the SimPO lossAlignmentProAlignmentProMediumImplement the ORPO odds-ratio preference lossAlignmentProAlignmentProMediumTrain a reward model on a full ranking of K answersAlignmentProAlignmentProMediumGRPO: group-relative advantages with the PPO clipped objectiveAlignmentProAlignmentProHardFull PPO loss with GAE, advantage whitening and value clippingAlignmentProAlignmentProHardCompute the DPO gradient weights by handAlignmentProAlignmentProHardCompute a token-level clipped policy loss with asymmetric clippingAlignmentProAlignmentProHardCompute the DPO loss directly from policy and reference logitsAlignmentProAlignmentProHardSample a VAE latent with the reparameterization trickGenerative modelsGenerative modelsEasyScore a denoising autoencoder against the clean inputGenerative modelsGenerative modelsEasySchedule the KL weight with cyclical annealingGenerative modelsGenerative modelsEasyScore anomalies with a tied-weight autoencoder's reconstruction errorGenerative modelsGenerative modelsEasyInterpolate between two latent vectors with slerpGenerative modelsGenerative modelsEasyCompute the VAE loss: reconstruction BCE plus KL to a standard normalGenerative modelsProGenerative modelsProMediumCompute GAN discriminator and non-saturating generator losses from logitsGenerative modelsProGenerative modelsProMediumRun an affine coupling layer forward and backwardGenerative modelsProGenerative modelsProMediumCompute the Inception Score from class probabilitiesGenerative modelsProGenerative modelsProMediumBuild PixelCNN mask A and mask B with colour channel orderingGenerative modelsProGenerative modelsProMediumCompute WGAN-GP critic and generator losses with an analytic input gradientGenerative modelsProGenerative modelsProHardQuantize latents to a VQ-VAE codebook with straight-through gradientsGenerative modelsProGenerative modelsProHardCompute the Frechet distance between GaussiansGenerative modelsProGenerative modelsProHardTake one discriminator and one generator step of a 1D GAN by handGenerative modelsProGenerative modelsProHardBackpropagate through the VAE reparameterization and KL termGenerative modelsProGenerative modelsProHardCut an image into flattened patches for a vision transformerVision transformers and CLIPVision transformers and CLIPEasyClassify images zero-shot with CLIP embeddingsVision transformers and CLIPVision transformers and CLIPEasyReassemble an image from ViT patch vectorsVision transformers and CLIPVision transformers and CLIPEasyCount ViT tokens, attention cost and patch embedding sizeVision transformers and CLIPVision transformers and CLIPEasyEmbed patches, prepend a CLS token and add position embeddingsVision transformers and CLIPProVision transformers and CLIPProMediumCompute CLIP's symmetric image-text contrastive lossVision transformers and CLIPProVision transformers and CLIPProMediumMask patches for a masked autoencoderVision transformers and CLIPProVision transformers and CLIPProMediumBuild 2D sine-cosine position embeddingsVision transformers and CLIPProVision transformers and CLIPProMediumPartition a feature map into (shifted) windows for window attentionVision transformers and CLIPProVision transformers and CLIPProMediumEvaluate CLIP-style image-text retrieval with recall at kVision transformers and CLIPProVision transformers and CLIPProMediumClassify an image from the CLS token after one multi-head attention blockVision transformers and CLIPProVision transformers and CLIPProHardResize learned ViT position embeddings for a new input resolutionVision transformers and CLIPProVision transformers and CLIPProHardCompute attention rollout for a ViTVision transformers and CLIPProVision transformers and CLIPProHardBuild the attention mask for shifted window attentionVision transformers and CLIPProVision transformers and CLIPProHardAdd noise to an image in one jump: q(x_t | x_0)Diffusion modelsDiffusion modelsEasyCombine conditional and unconditional noise with classifier-free guidanceDiffusion modelsDiffusion modelsEasyCompute Min-SNR loss weightsDiffusion modelsDiffusion modelsEasyBuild the Karras noise scheduleDiffusion modelsDiffusion modelsEasyClip predicted clean images with dynamic thresholdingDiffusion modelsDiffusion modelsEasyChoose the starting step and noise the input for image-to-imageDiffusion modelsDiffusion modelsEasyBuild the cosine noise scheduleDiffusion modelsProDiffusion modelsProMediumBuild a linear beta schedule and find where signal-to-noise drops below 1Diffusion modelsProDiffusion modelsProMediumConvert between v-prediction and x0/epsilonDiffusion modelsProDiffusion modelsProMediumCompute the forward-process posterior q(x_{t-1} | x_t, x_0)Diffusion modelsProDiffusion modelsProMediumApply classifier-free guidance with guidance rescaleDiffusion modelsProDiffusion modelsProMediumTake one DDPM denoising stepDiffusion modelsProDiffusion modelsProHardRun a deterministic DDIM sampler over a strided timestep subsequenceDiffusion modelsProDiffusion modelsProHardTake a Heun (2nd order) step of the diffusion ODEDiffusion modelsProDiffusion modelsProHardTake one DDIM step with stochasticity etaDiffusion modelsProDiffusion modelsProHardSample with the Euler ancestral method over a sigma scheduleDiffusion modelsProDiffusion modelsProHardCompute discounted returns for an episodeReinforcement learningReinforcement learningEasyRun an epsilon-greedy multi-armed bandit from fixed random drawsReinforcement learningReinforcement learningEasyPick the next arm with the UCB1 ruleReinforcement learningReinforcement learningEasyCompute n-step bootstrapped returnsReinforcement learningReinforcement learningEasyCompute Double DQN targetsReinforcement learningReinforcement learningEasyDo one Bellman expectation backup for a single stateReinforcement learningReinforcement learningEasyBuild linear and exponential epsilon decay schedulesReinforcement learningReinforcement learningEasyUpdate a value table with TD(0) over an episodeReinforcement learningReinforcement learningEasyCompute one-step actor-critic advantages and lossesReinforcement learningReinforcement learningEasyTurn MCTS visit counts into a move policy with temperatureReinforcement learningReinforcement learningEasyMask illegal moves out of a policy head's softmaxReinforcement learningReinforcement learningEasyAdd potential-based reward shaping to an episodeReinforcement learningReinforcement learningEasyRun tabular Q-learning updatesReinforcement learningProReinforcement learningProMediumPick the next move in MCTS with the PUCT ruleReinforcement learningProReinforcement learningProMediumCompute a REINFORCE policy-gradient update with a baselineReinforcement learningProReinforcement learningProMediumBack up a playout value through an MCTS path with alternating playersReinforcement learningProReinforcement learningProMediumRun tabular SARSA updates over an episodeReinforcement learningProReinforcement learningProMediumCompute soft state values for maximum-entropy RLReinforcement learningProReinforcement learningProMediumUpdate a gradient bandit's action preferencesReinforcement learningProReinforcement learningProMediumRun Gaussian Thompson sampling from fixed noise drawsReinforcement learningProReinforcement learningProMediumEstimate state values with first-visit Monte CarloReinforcement learningProReinforcement learningProMediumCompute the DQN loss with a target network and Huber lossReinforcement learningProReinforcement learningProMediumCompute prioritized replay sampling probabilities and importance weightsReinforcement learningProReinforcement learningProMediumFind a Go group and count its liberties with flood fillReinforcement learningProReinforcement learningProMediumEstimate a policy's return from another policy's episodes with importance samplingReinforcement learningProReinforcement learningProMediumUpdate a search distribution with the cross-entropy methodReinforcement learningProReinforcement learningProMediumCompute Generalized Advantage EstimationReinforcement learningProReinforcement learningProHardSolve a slippery gridworld with value iterationReinforcement learningProReinforcement learningProHardSearch a game tree with negamax and alpha-beta pruning, counting visited leavesReinforcement learningProReinforcement learningProHardSolve a small MDP with policy iterationReinforcement learningProReinforcement learningProHardRun TD(lambda) with accumulating and replacing eligibility tracesReinforcement learningProReinforcement learningProHardBuild a sum tree and sample replay indices from itReinforcement learningProReinforcement learningProHardRun PPO epochs with the clipped objective and KL early stoppingReinforcement learningProReinforcement learningProHardPlay a Go move with captures and the suicide ruleReinforcement learningProReinforcement learningProHardFind the best tic-tac-toe move with depth-aware minimaxReinforcement learningProReinforcement learningProHardTotal the tokens each model used on successful API callsSQLSQLEasyFind users whose total API spend is over a budget with HAVINGSQLSQLEasyCount how many different models each user called with COUNT DISTINCTSQLSQLEasyPick a final label from human and model labels with COALESCESQLSQLEasyFind training runs that were never evaluated with a LEFT JOIN anti-joinSQLSQLEasyCompute the prompt cache hit rate per model while ignoring unknown rowsSQLSQLEasyShow each team's share of total GPU hours with a window over all rowsSQLSQLEasyCount failed training runs per project, keeping projects with zero failuresSQLSQLMediumPick the best scoring model for each eval task with ROW_NUMBERSQLSQLMediumPivot request statuses into columns with conditional aggregationSQLSQLMediumFind eval tasks where a candidate model scores below the baseline with a self joinSQLSQLMediumKeep every run in the top two distinct scores per project with DENSE_RANKSQLSQLMediumKeep the latest annotation per item, then count labelsSQLSQLMediumMeasure how many days each model version stayed live with LEADSQLSQLMediumFind models slower than the overall average latency using CTEsSQLSQLMediumCompute day-over-day percent change in API cost per team with LAGSQLProSQLProHardSplit agent events into sessions by idle gap and report sessions per userSQLProSQLProHardBuild a three-step signup funnel where steps must happen in orderSQLProSQLProHardCompute day-1 and day-7 retention per signup cohortSQLProSQLProHardCompute the median latency per model with window functionsSQLProSQLProHardFind the longest streak of consecutive failed runs per pipelineSQLProSQLProHardFind the day each user crossed a token quota with a running totalSQLProSQLProHardSummarise API calls per model with named groupby aggregationspandaspandasEasyKeep only the latest subscription record per userpandaspandasEasyMelt a wide leaderboard into long rows and drop missing scorespandaspandasEasyCompare class balance across train, val and test with value_countspandaspandasEasyCount prompts per tag by exploding a list columnpandaspandasEasyJoin usage to a price table and fill missing prices with a defaultpandaspandasMediumPivot repeated eval runs into a model by benchmark score tablepandaspandasMediumAudit eval coverage with an outer merge and the indicator columnpandaspandasMediumFill missing latencies with each model's median and a global fallbackpandaspandasMediumForward fill each user's plan in time order without leaking across userspandaspandasMediumPrice API requests with marginal token tiers using vectorized NumPy instead of applypandaspandasMediumAdd each request's share of its user's tokens and its rank with groupby transformpandaspandasMediumCompute a 3-day calendar rolling error rate per model with gaps in the datapandasPropandasProHardResample a request log to hourly traffic, filling empty hours with zerospandasPropandasProHardFlag metric spikes with a rolling z-score of the previous values per modelpandasPropandasProHardBuild a monthly cohort retention matrix with pandaspandasPropandasProHardPrice each API call with the rate in effect at that time using merge_asofpandasPropandasProHardword2vec skip-gram negative sampling loss (Mikolov et al., 2013)Paper implementationsPaper implementationsEasyCompute-optimal model and data size with a Chinchilla-style rule of thumbPaper implementationsPaper implementationsEasyEvaluate the Chinchilla scaling lawPaper implementationsPaper implementationsEasyBuild a global magnitude pruning maskPaper implementationsPaper implementationsEasyCompute the SwiGLU feed-forward hidden size used by LlamaPaper implementationsPaper implementationsEasyAdd the z-loss auxiliary term to cross-entropyPaper implementationsPaper implementationsEasyApply tanh soft-capping to logits and get its gradientPaper implementationsPaper implementationsEasyKnowledge distillation loss with temperature (Hinton et al., 2015)Paper implementationsProPaper implementationsProMediumALiBi linear attention biases (Press et al.) instead of position embeddingsPaper implementationsProPaper implementationsProMediumMix a batch with mixupPaper implementationsProPaper implementationsProMediumCompute a multi-token prediction loss over several headsPaper implementationsProPaper implementationsProMediumRun a self-refinement loop with a stopping rulePaper implementationsProPaper implementationsProMediumFlashAttention-style tiled causal attention forward (Dao et al., 2022)Paper implementationsProPaper implementationsProHardMamba-style selective state-space scan with zero-order-hold discretizationPaper implementationsProPaper implementationsProHardImplement recurrent retention from RetNetPaper implementationsProPaper implementationsProHardImplement differential attention with the lambda reparameterizationPaper implementationsProPaper implementationsProHardSimulate a parallel tree reductionGPU kernels (simulated)GPU kernels (simulated)EasyCount memory transactions for a warp's global loadsGPU kernels (simulated)GPU kernels (simulated)EasyPredict attainable FLOPs with the roofline modelGPU kernels (simulated)GPU kernels (simulated)EasyMeasure warp divergence from branch outcomesGPU kernels (simulated)GPU kernels (simulated)EasyLaunch an elementwise kernel with the right grid size and bounds checkGPU kernels (simulated)GPU kernels (simulated)EasyCount the work each thread does in a grid-stride loopGPU kernels (simulated)GPU kernels (simulated)EasyMeasure wave quantization of a tiled kernelGPU kernels (simulated)GPU kernels (simulated)EasyEstimate memory traffic saved by fusing elementwise kernelsGPU kernels (simulated)GPU kernels (simulated)EasyCount global memory loads for naive vs tiled matmulGPU kernels (simulated)ProGPU kernels (simulated)ProMediumCalculate SM occupancy from threads, registers and shared memoryGPU kernels (simulated)ProGPU kernels (simulated)ProMediumReduce a warp with butterfly XOR shufflesGPU kernels (simulated)ProGPU kernels (simulated)ProMediumFind the argmax with a parallel tree reduction and lowest-index tiesGPU kernels (simulated)ProGPU kernels (simulated)ProMediumSimulate a warp-per-row matrix-vector kernelGPU kernels (simulated)ProGPU kernels (simulated)ProMediumMerge split-KV partial attention resultsGPU kernels (simulated)ProGPU kernels (simulated)ProMediumCompute a matmul with split-K partial sumsGPU kernels (simulated)ProGPU kernels (simulated)ProMediumCount atomic serialization in a warp-level histogramGPU kernels (simulated)ProGPU kernels (simulated)ProMediumMap program ids to tiles with grouped ordering for cache reuseGPU kernels (simulated)ProGPU kernels (simulated)ProMediumMerge per-thread mean and variance statistics in a blockGPU kernels (simulated)ProGPU kernels (simulated)ProMediumOnline softmax, the trick inside FlashAttentionGPU kernels (simulated)ProGPU kernels (simulated)ProHardCount shared-memory bank conflict passes per warpGPU kernels (simulated)ProGPU kernels (simulated)ProHardSimulate a work-efficient parallel prefix sumGPU kernels (simulated)ProGPU kernels (simulated)ProHardSimulate a multi-stage load and compute pipelineGPU kernels (simulated)ProGPU kernels (simulated)ProHardCompute dK and dV tile by tile from the saved log-sum-expGPU kernels (simulated)ProGPU kernels (simulated)ProHardAverage gradients across data-parallel workersDistributed trainingDistributed trainingEasyCompute the idle bubble fraction of a pipeline-parallel scheduleDistributed trainingDistributed trainingEasyPick gradient accumulation steps for a global batchDistributed trainingDistributed trainingEasyCompare ring and tree all-reduce with a latency-bandwidth modelDistributed trainingDistributed trainingEasyEstimate peak parameter memory for fully sharded training with prefetchDistributed trainingDistributed trainingEasyApply an outer momentum step after local SGD roundsDistributed trainingDistributed trainingEasyChoose a checkpoint interval that minimizes activation memoryDistributed trainingDistributed trainingEasySimulate ring all-reduce step by stepDistributed trainingProDistributed trainingProMediumEstimate per-GPU memory under ZeRO stages 0 to 3Distributed trainingProDistributed trainingProMediumEstimate per-step communication for DP, ZeRO and TPDistributed trainingProDistributed trainingProMediumShard flattened parameters across ranksDistributed trainingProDistributed trainingProMediumGroup gradients into all-reduce buckets in backward orderDistributed trainingProDistributed trainingProMediumBuild the all-to-all send matrix for expert parallelismDistributed trainingProDistributed trainingProMediumSimulate a dynamic loss scaler for mixed-precision trainingDistributed trainingProDistributed trainingProMediumSplit an MLP across GPUs with tensor parallelismDistributed trainingProDistributed trainingProHardSimulate a GPipe-style schedule with uneven stage timesDistributed trainingProDistributed trainingProHardGenerate a 1F1B pipeline scheduleDistributed trainingProDistributed trainingProHardSplit attention heads across GPUs with tensor parallelismDistributed trainingProDistributed trainingProHardCompute cross-entropy when the vocabulary is split across GPUsDistributed trainingProDistributed trainingProHardSimulate a two-level hierarchical all-reduceDistributed trainingProDistributed trainingProHardCompress gradients with top-k and error feedbackDistributed trainingProDistributed trainingProHardParse a ReAct agent's action from model outputAgentsAgentsEasyTrim an agent's chat history to fit a token budgetAgentsAgentsEasyDetect a repeating tool-call loopAgentsAgentsEasyRoute a request to a tool by keyword scoreAgentsAgentsEasyCompute full-jitter and equal-jitter retry delaysAgentsAgentsEasyTruncate a long tool result to a token budget keeping head and tailAgentsAgentsEasyMeasure agent reliability with pass^kAgentsAgentsEasyDeduplicate repeated tool calls with a canonical cache keyAgentsAgentsEasyWrite the loop that runs a tool-calling agentAgentsProAgentsProMediumRetry a flaky tool with exponential backoffAgentsProAgentsProMediumExtract a JSON tool call from messy model outputAgentsProAgentsProMediumEnforce token and dollar budgets on an agent runAgentsProAgentsProMediumRetrieve agent memories by similarity and recencyAgentsProAgentsProMediumRedact emails, phone numbers and card numbers before text reaches a modelAgentsProAgentsProMediumValidate tool arguments against a schema before callingAgentsProAgentsProHardSchedule an agent's task plan into parallel waves with cycle detectionAgentsProAgentsProHardCompact an agent's message history under a token budgetAgentsProAgentsProHardRepair a truncated JSON tool call from a streaming modelAgentsProAgentsProHardParse a full multi-step ReAct trace into structured stepsAgentsProAgentsProHardFind the latency and critical path of an agent's task planAgentsProAgentsProHardSchedule tool calls under global and per-tool concurrency limitsAgentsProAgentsProHardDetect feature drift with the Population Stability IndexMLOpsMLOpsEasyReport p50, p95 and p99 latency with the nearest-rank methodMLOpsMLOpsEasyBump a semantic model versionMLOpsMLOpsEasyFlag stale features in a feature storeMLOpsMLOpsEasyMeasure agreement between a shadow model and productionMLOpsMLOpsEasyCompute SLO error budget burn ratesMLOpsMLOpsEasyRaise drift alerts with an EWMA control chartMLOpsMLOpsEasyValidate a data batch against a schema with null-rate, type and range checksMLOpsMLOpsEasyCatch train-serving skew in feature pipelinesMLOpsProMLOpsProMediumDrive a staged canary rollout from per-window error ratesMLOpsProMLOpsProMediumPick a champion model with guardrail metricsMLOpsProMLOpsProMediumMeasure feature drift with smoothed KL divergence on quantile binsMLOpsProMLOpsProMediumAssign users to experiment variants with salted hash bucketingMLOpsProMLOpsProMediumDetect drift in a categorical feature with a chi-square statisticMLOpsProMLOpsProMediumTwo-sample Kolmogorov-Smirnov statistic for drift alertsMLOpsProMLOpsProHardJoin training labels to features without leaking the futureMLOpsProMLOpsProHardSimulate a circuit breaker in front of a model APIMLOpsProMLOpsProHardApply stage transitions in a model registryMLOpsProMLOpsProHard

Pro problems are Pro.

Browse by topic

Study plans and mocks