Optimization Building Blocks
Original Python research interviews on gradient accounting, optimizer state, constrained updates, quadratic models, numerical checks, and explicit optimization decisions.
These problems are original practice. They are not questions from a named employer or a live hiring loop.
1.Weight gradient means by their actual sample support
Write
combine_gradients(rows, width). rows is[nonnegative_integer_count,gradient_mean_vector]with finite vectors of length width>=0. Return the sample-count-weighted mean vector. Ignore zero-count rows, including their vector values. If total support is zero returnNone. Do not average batch means equally or mutate inputs.2.Coalesce repeated sparse coordinates and remove exact zeros
Write
coalesce_gradients(entries, size). entries is[integer_index,finite_value]rows, 0<=index<size; size is a nonnegative integer. Sum all contributions per index, then return sorted[index,sum]rows with nonzero sums. A cancellation removes that coordinate. Do not return a dense vector or mutate entries.3.Respect freezing before applying decoupled weight decay
Write
masked_step(params, gradients, trainable, decay, lr, weight_decay). Four lists have equal length; values are finite, masks Boolean, lr/weight_decay>=0. Frozen coordinates stay unchanged. For trainable i returnparams[i]*(1-lr*weight_decay) - lr*gradients[i]whendecay[i], elseparams[i]-lr*gradients[i]. Return a new list.4.Use updated moments and the supplied one-based step
Write
moment_step(p, g, m, v, beta1, beta2, step, lr, eps). Four equal-length finite lists, v>=0; betas in [0,1), step>=1 integer, lr>=0, eps>0. Set M=beta1*m+(1-beta1)*g, V=beta2*v+(1-beta2)*g^2. Return{"p":p-lr*(M/(1-beta1^step))/(sqrt(V/(1-beta2^step))+eps),"m":M,"v":V}coordinatewise. No decay or mutation.5.Center the moving squared gradient before scaling
Write
centered_rms(p, g, mean, square, beta, lr, eps). Four equal-length finite lists, square>=0; beta in [0,1), lr>=0, eps>0. Update M=beta*mean+(1-beta)*g and S=beta*square+(1-beta)*g^2. Set variance=max(0,S-M^2). Return{"p":p-lr*g/(sqrt(variance)+eps),"mean":M,"square":S}. No bias correction or mutation.6.Include the current square before the adaptive update
Write
accumulated_step(p, g, sums, lr, eps). Equal-length finite lists, sums>=0, lr>=0, eps>0. For each coordinate set S=sums+g^2, then P=p-lr*g/(sqrt(S)+eps). Return{"p":P,"sums":S}without mutation. The denominator uses the updated square sum, including this gradient.7.Threshold the result of a gradient step toward zero
Write
proximal_step(p, g, lr, penalty). p/g are equal-length finite lists; lr/penalty>=0. Let z=p-lr*g and threshold=lr*penalty. Returnsign(z)*max(abs(z)-threshold,0) coordinatewise, with exact zeros returned as 0. Apply thresholding after the gradient step. Do not mutate inputs.8.Apply both sparse thresholding and quadratic shrinkage
Write
mixed_prox(values, rate, l1, l2). values is finite; rate/l1/l2>=0. This contract defines the penalty l1*sum(abs(x))+l2*sum(x^2)/2. Returnsign(v)*max(abs(v)-rate*l1,0)/(1+rate*l2) for every v. Preserve input order and do not mutate values.9.Project onto a nonnegative vector with fixed total mass
Write
simplex_projection(values, mass). values is a finite list, mass>=0; positive mass requires a nonempty list. Return its Euclidean projection ontox[i]>=0 andsum(x)=mass. Usex[i]=max(values[i]-theta,0), choosing theta to meet that sum. mass=0 returns all zeros. Keep original coordinate order and do not mutate.10.Preserve feasible vectors when projecting to an L1 ball
Write
l1_projection(values, radius). values is a finite list; radius>=0. Return its Euclidean projection onto sum(abs(x))<=radius. If already feasible return a copy unchanged. Otherwise choose theta so sum(max(abs(v)-theta,0))=radius and restore each sign. radius=0 returns zeros. Do not mutate values.11.Project each tentative coordinate to its own interval
Write
box_step(params, gradients, lower, upper, lr). Four equal-length finite lists,lower[i]<=upper[i], lr>=0. Compute tentative=params[i]-lr*gradients[i], then clamp it to [lower[i],upper[i]]. Return the new vector. The old parameters need not already satisfy their intervals; do not mutate inputs.12.Remove only the gradient component normal to a constraint
Write
tangent_gradient(gradient, normal). Equal-length finite lists. Return gradient-normal*dot(gradient,normal)/dot(normal,normal), the tangent component for a single affine equality. If normal is the zero vector return a copy of gradient. Do not normalize the tangent length or mutate inputs.13.Keep directional slope distinct from directional curvature
Write
quadratic_direction(hessian, linear, point, direction). Forf(x)=x^T*H*x/2+linear^T*x, H is finite symmetric n-by-n; vectors have length n. Return{"slope":direction^T*(H*point+linear),"curvature":direction^T*H*direction}. n may be zero. Do not mutate inputs.14.Minimize a convex quadratic along a bounded ray
Write
capped_step(slope, curvature, cap). Finite scalars, curvature>=0 and cap>=0. Minimize slope*a+curvature*a^2/2 over 0<=a<=cap. Return 0 if slope>=0, otherwise cap if curvature=0, elsemin(cap,-slope/curvature). For a flat objective choose 0. Do not divide by zero.15.Choose the first supplied sufficient-decrease candidate
Write
choose_armijo(base, slope, c, candidates). Finite exact-decimal scalars, slope<0 and 0<c<1; candidates is[positive_step,observed_loss]rows in priority order. Return the zero-based index of the first row satisfying loss<=base+c*step*slope, orNone. Do not sort steps, accept mere decrease, or evaluate a new loss.16.Separate model quality from trial-step acceptance
Write
trust_decision(actual, predicted, radius, boundary). Finite scalars; radius>0 and boundary Boolean. If predicted<=0 return{"ratio":None,"accept":False,"radius":radius/2}. Otherwise ratio=actual/predicted; accept iff ratio>0.1. Halve radius if ratio<0.25; double only if ratio>0.75 and boundary; else hold it. Compare decimal inputs exactly; report numeric ratio.17.Apply a diagonal-plus-rank-one Hessian without expansion
Write
structured_hvp(diagonal, u, weight, direction). Three equal-length finite vectors and finite scalar weight represent H=diag(diagonal)+weight*u*u^T. Return H*direction using the structure; do not construct an n-by-n matrix. Empty vectors return []. Do not mutate inputs.18.Use a centered perturbation along a polynomial direction
Write
polynomial_difference(coefficients, x, direction, h). coefficients lists finite coefficients in ascending power order forf(z)=sum(c[k]*z^k); x/direction finite and h>0. Return (f(x+h*direction)-f(x-h*direction))/(2*h). Empty coefficients mean f=0. This is the finite difference, not the exact analytic derivative.19.Keep small gradients visible in a relative error check
Write
gradient_discrepancies(analytic, numerical, floor, tolerance). Equal-length finite vectors; floor>0 and tolerance>=0. For each coordinate error=abs(a-n)/max(floor,abs(a)+abs(n)). Return{"errors":errors,"bad":indices where error>tolerance}. Interpret decimal inputs exactly for comparisons; equality is accepted. Preserve order.20.Pull a cotangent backward through two linear maps
Write
linear_pullback(a, b, cotangent). a is finite m-by-n, b is k-by-m, cotangent length k; m/n/k>0. For y=a*x and z=b*y, return the input cotangent a^T*b^T*cotangent as a length-n list. Do not compute a forward product in the wrong order, allocate a Jacobian product, or mutate inputs.21.Reject a whole update when any gradient is missing
Write
atomic_step(params, gradients, lr, step). Equal-length lists; params finite, gradients finite orNone; lr>=0 and step>=0 integer. If any gradient isNonereturn{"params":copy_of_params,"step":step,"applied":False}. Otherwise subtract lr*gradient coordinatewise, increment step once, and set applied=True. Empty vectors form a valid applied step. Do not mutate.22.Change loss scale only on explicit supported events
Write
scale_history(events, initial, interval). initial>0 finite, interval>=1 integer; events areTrue(overflow),False(finite step), orNone(no report). Start scale=initial, streak=0. Overflow halves scale and clears streak. Finite increments streak; at interval double scale and clear streak.Noneholds both. Return[scale,streak]after every event.23.Return moving averages with finite-step debiasing
Write
ema_history(values, beta). values lists finite scalars and 0<=beta<1. Start mean=0. At one-based step t update mean=beta*mean+(1-beta)*value. Return[mean,mean/(1-beta^t)]after each value. Keep the stored raw mean separate from the reported debiased estimate; empty input returns [].24.Average snapshots after a burn-in position only
Write
suffix_average(snapshots, start). snapshots is finite equal-width vectors, start>=0 integer, zero-based. Return the coordinatewise mean ofsnapshots[start:], orNoneif this suffix is empty. Do not include earlier snapshots, use exponential weights, or mutate any vector. A supported zero-width suffix returns [].25.Synchronize slow parameters at complete step boundaries
Write
lookahead_trace(initial, deltas, interval, mix). initial and each delta are equal-width finite vectors; interval>=1 integer, mix in[0,1]. Start fast=slow=initial. Add each delta to fast; on every interval-th step set slow=slow+mix*(fast-slow), then fast=copy(slow). Return{"fast":fast,"slow":slow}after all deltas, without mutation.26.Gate a two-coordinate Newton solve on positive definiteness
Write
damped_newton(a, b, c, gradient, damping). Finite H=[[a,b],[b,c]], gradient length 2, damping>=0. Set A=a+damping, C=c+damping, det=A*C-b^2. ReturnNoneunless A>0 and det>0. Otherwise return[-C*g0+b*g1, b*g0-A*g1]/det. Do not invert the undamped matrix or mutate gradient.27.Advance one supplied conjugate-gradient state
Write
conjugate_step(H, x, r, p). H is symmetric positive-definite n-by-n; vectors are finite length n and p!=0 when r!=0. Let s=r.r, q=H*p. If s=0 return copies x/r, zero p, alpha=beta=0. Else alpha=s/(p.q), X=x+alpha*p, R=r-alpha*q, beta=(R.R)/s, P=R+beta*p. Return{"x":X,"r":R,"p":P,"alpha":alpha,"beta":beta}. No mutation.28.Remove a conflicting component against a frozen gradient
Write
remove_conflict(gradient, reference). Equal-length finite vectors. Ifdot(gradient,reference)<0, return gradient-dot(gradient,reference)/dot(reference,reference)*reference. Otherwise return a copy unchanged. A zero reference is unchanged. Project only gradient against the original reference; do not alter the reference or normalize the output.29.Require an actual margin before replacing a checkpoint
Write
accepted_trials(initial_loss, trials, margin). Finite exact-decimal losses, margin>=0; trials is[unique_string_id,loss]in arrival order. Start best=initial_loss, id=None. Accept a trial only if best-loss>margin, then replace best/id. Return{"accepted":accepted_ids,"best":best_loss,"id":last_accepted_id}. Compare against the last accepted loss; equality is rejected.30.Use newly updated coordinates within a quadratic sweep
Write
coordinate_sweep(H, b, initial, order). H is finite symmetric positive-definite n-by-n; b/initial length n. order lists valid coordinate indices, possibly repeated. For each i in order immediately setx[i]=(b[i]-sum(H[i][j]*x[j] for j!=i))/H[i][i], using current x. Return x after all updates. Empty order returns a copy; do not mutate inputs.