Module contents
Lesson 16 of 23Core 100 min

Failure investigation: when the result does not come out (or looks too good)

Apply the scientific method to failure investigation: observe, formulate and prioritize rival hypotheses, reduce to a minimal failing experiment, and isolate responsible differences. Study bisection and delta debugging, error slices with multiplicity control, too-good-result audits, and informative negative reporting.

After this lesson you can

  • Apply the failure-investigation loop and prioritize hypotheses by plausibility and test cost.
  • Reduce a failure to a minimal experiment reproducing it in minutes.
  • Use delta debugging to isolate a minimal combination of configuration differences causing a discrepancy.
  • Find data slices with anomalous error and control multiplicity of the search.
  • Audit a too-good result for leakage, contamination, and metric errors, and report an informative negative result.

Before you start

A failure is also an observation

A training run produces lower accuracy than published, or a figure so high it seems impossible. Both observations need explanation. A sequence of improvised changes can fix the symptom without revealing its cause; trying many adjustments and reporting only the successful one introduces selection. Failure investigation records result, command, data, environment, seeds, and expected comparison. It then formulates rival hypotheses, chooses a discriminating test, runs the control, and updates the log. A negative test rules out a cause only under conditions where it was sensitive.

A loss that does not decrease could result from permuted labels, an unsuitable learning rate, or disconnected gradients. A tiny fixed batch the model cannot memorize is a warning: inspect labels, output, loss, and gradients. If it can memorize, those components work in that case; full evaluation is not thereby proven correct. Keep one working and one failing configuration and compare their resolved files.

What to test first

The minimal failing experiment reduces data, steps, architecture, or dependencies until the discrepancy recurs quickly. Check that the reduced case retains the same symptom: a different NaN does not automatically explain the original. Fix a seed for debugging, then repeat with several to assess stability. For intermittent failure, one run is not a reliable oracle; record failure rate, repeat each configuration, and define how uncertain results are classified.

If exactly one of several exhaustive causes is present, each test is perfect, and cost is fixed, the optimal order is descending pi/cip_i/c_i. For two tests i,ji,j, placing ii first costs ci+(1−pi)cjc_i+(1-p_i)c_j and the reverse costs cj+(1−pj)cic_j+(1-p_j)c_i; the first wins when pi/ci≥pj/cjp_i/c_i \ge p_j/c_j. If causes coexist, tests have false negatives, or they modify state, the rule is insufficient. Update probabilities and consider how well each test distinguishes hypotheses.

InteractivePrioritize tests

A: p=0.50, cost=4 h, p/c=0.13 · B: p=0.30, cost=1 h, p/c=0.30 · C: p=0.20, cost=1 h, p/c=0.20

Swapping adjacent tests reduces expected cost if the first has higher p/c. The criterion changes if tests are imperfect or causes coexist.

0.50
0.30
4
1
1
Your order A → B → C4.70 h
Optimal B → C → A3.70 h
Edit weights and costs and compare your order with the optimum under the stated assumptions. Weights are normalized.

Isolate differences and interactions

Bisection works when one independent causal difference exists and each half can be applied and tested. With 16 differences, one cause, and a deterministic oracle, four half-tests suffice in the worst case if the full set is already known to fail and the empty set not to fail. If those endpoints need checking, count additional runs. A regression in a commit sequence needs a stable predicate and ordered history; not every failure is monotonic.

Consider comparing reference and new training with 12 changes. Before searching, check both endpoints more than once: if the reference also sometimes fails, the predicate “failed once” mixes noise with causes. Then retain batch and random state for each test, record the configuration actually run, and note time, version, and output. The two changes isolated by ddmin are causal candidates in that environment. Final checking reapplies both, removes one at a time, and where possible repeats with other seeds and data. This distinguishes isolation from mechanistic explanation: understanding why they interact requires inspecting gradients, scales, or specific invariants.

Delta debugging splits changes and tests subsets and complements; it increases granularity when reduction fails. Zeller and Hildebrandt formalize isolation of failure-inducing inputs. A 1-minimal result fails, but removing any one element stops failure. It need not be the globally smallest failing set or the only cause. Define defaults, dependencies, and incompatibilities; an invalid configuration needs a third outcome and must not be confused with success.

InteractiveChanges that fail together
1. seed2. batch3. rate4. order5. precision6. normalization7. clipping8. loss9. optimizer10. mask11. epochs12. augmentation

Individual tests and halves do not reproduce this interaction. The ddmin result is 1-minimal: removing either of its two changes eliminates the failure.

Result0 failures
Tests12
In this deterministic synthetic predicate, rate and mask fail only together. Compare individual tests, halves, and ddmin.

Here changing each element separately and testing each half does not reproduce the interaction. ddmin can isolate it because it examines complements and additional granularities. Test count depends on order and algorithm; there is no general logarithmic guarantee for arbitrary interactions.

Slices and multiplicity

Slice error analysis seeks conditions where a model fails more: language, length, source, date, or intersections. Define population and denominator; 50% over two examples is very uncertain. A one-sided Fisher test compares errors inside and outside a group under equal rates. Fixed groups are enumerated and Benjamini-Hochberg (BH) is applied to their p-values. Control of expected false-discovery proportion has dependence assumptions; overlapping groups need caution and, under arbitrary dependence, a more conservative correction or appropriate calibration.

InteractiveFind and validate a slice
Groupn disc.q disc.q holdout
es6190.003<0.001
en5811.0001.000
long619<0.001<0.001
short5811.0001.000
web5770.8501.000
book6230.8820.057
new5990.2700.956
old6011.0000.764
es + long304<0.001<0.001

“Disc.” means discovery. The simulation deliberately increases the error of “es + long”; selection, dependence between tests and distribution shift affect interpretation. The holdout does not prove causality.

Discovery: error / BH q30.9 % / <0.001
Holdout: error / BH q31.5 % / <0.001
Simulated data with two independent splits. Error for long Spanish text was increased in generation; other differences are noise.

The holdout provides another check with data not used for search. If the same categories are explored on holdout and the minimum selected again, multiplicity returns; the figure calculates BH on both splits for nine fixed groups. A small adjusted value does not show why the model fails: inspect examples and counterexamples, review labels, and consider confounding factors. Clustering error embeddings proposes hypotheses without metadata, but test them outside the sample used to form and select groups.

Comparison with the complement asks whether the group has a higher rate than the rest of the sample, not whether it exceeds an absolute service threshold. A real increase for long Spanish text may also raise marginal Spanish and long-text rates; these findings overlap and are not three independent populations. Report group size, error count, rate difference, and interval alongside the adjusted value. If the model sees many examples from one document, independent-observation assumptions may also fail: splitting and resampling by document or entity better reflect the generalization unit.

To validate a finding, freeze slice rule and metric before opening holdout. A lower rate on holdout may be regression to the mean, distribution change, or chance; it does not automatically prove the original search wrong. If the group is chosen and redefined using holdout, that holdout ceases to be confirmatory for the decision. In a sensitive system, human example inspection needs a protocol and multiple evaluators; a geometric cluster is not itself an interpreted human category.

When it looks too good

A too-good-result audit starts with cheap checks: class proportions, metric formula, repeated IDs, and label-derived columns. A 99% score can be trivial with 99% of one class; report confusion matrix and baseline. Look for exact and near duplicates across splits, entity or project separation, and availability times. Fit normalization, feature selection, and imputation only on training, within each fold. Normalizing before splitting is leakage even if it does not always greatly raise accuracy. Kapoor and Narayanan document leakage forms in ML-based science and their reproducibility consequences.

InteractiveThe mysterious pipeline

The toy classifier achieves 100 % accuracy. Investigate before attributing it to capability.

    Each test reveals a clue about the case. Normalization fitted before splitting is also leakage, but does not guarantee high accuracy.

    Tests performed0
    DiagnosisPending
    A 1-nearest-neighbor classifier is evaluated on synthetic records. Choose tests and diagnose duplicates, temporal leakage, or label included as input.

    For pretraining contamination, a text match may require searching variants and analyzing provenance; absence from an incomplete search does not prove absence of exposure. Hold out a new test, restrict access, and document selection and queries. CheckList complements aggregate score with behavioral tests designed for specific capabilities.

    Temporal leakage is not limited to a column named date. A feature computed after the event, closing label, or statistic aggregated over the full period can reveal future information. To check it, reconstruct which variables were available at prediction time and train only on the past. With repeated patients, repositories, or users, random row splitting can share identity or near-identical examples; group by the unit expected to be new at deployment. Compare an identity-only baseline: if strong, examine the split and population before attributing the result to content.

    A responsible report distinguishes suspicion from confirmed diagnosis. Similarity between records is a clue; checking origin, time, and split membership determines whether it was inadmissible for the question. After correcting the pipeline, retain the previous measurement as invalid and reevaluate on a holdout not used for repair decisions.

    Lab 1: ddmin in NumPy training

    Training fits linear regression on synthetic data. Two changes together reverse gradient sign and increase step size: the criterion is final loss above 10. Failure definition and seeds are fixed before search. The cache counts only new evaluations. Run each removal to check 1-minimality. This is a controlled simulation, not evidence of a real network failure.

    [ ]Minimal training and oracleBrowser
    import numpy as np
    rng=np.random.default_rng(16)
    X=rng.normal(size=(100,3)); [email protected]([1.,-2.,.5])
    changes=tuple(range(12))
    def failure_oracle(active):
        active=set(active)
        rate=.3 if 2 in active else .001
        sign=-1 if 9 in active else 1
        w=np.zeros(3)
        for _ in range(20):
            grad=2*X.T@(X@w-y)/len(y)
            w-=sign*rate*grad
        loss=np.mean((X@w-y)**2)
        return bool(loss>10)
    print('vacío / completo:',failure_oracle(()),failure_oracle(changes))
    print('individuales fallidos:',[i for i in changes if failure_oracle((i,))])
    assert not failure_oracle(()) and failure_oracle(changes)
    [ ]ddmin with cacheBrowser
    def ddmin(changes,test):
        cache={}
        def fails(xs):
            key=tuple(sorted(xs))
            if key not in cache: cache[key]=bool(test(key))
            return cache[key]
        c=list(changes)
        if len(set(c))!=len(c) or not fails(c): raise ValueError('conjunto no válido o no fallido')
        if fails([]): return [],len(cache)
        n=2
        while len(c)>=2:
            size=(len(c)+n-1)//n; reduced=False
            for start in range(0,len(c),size):
                part=c[start:start+size]; rest=[x for x in c if x not in part]
                if fails(rest): c=rest; n=max(2,n-1); reduced=True; break
                if fails(part): c=part; n=2; reduced=True; break
            if not reduced:
                if n>=len(c): break
                n=min(len(c),2*n)
        return c,len(cache)
    minimal,calls=ddmin(changes,failure_oracle)
    print('mínimo 1:',minimal,'evaluaciones distintas:',calls)
    assert failure_oracle(minimal)
    assert all(not failure_oracle([v for v in minimal if v!=x]) for x in minimal)
    print('mitades fallan:',failure_oracle(changes[:6]),failure_oracle(changes[6:]))

    The cache is valid because the oracle is deterministic. For stochastic failures, store repetitions and seeds, not one definitive answer. The function can be saved as a researchkit extension; also test empty sets, invalid configurations, and another interaction before using it in an investigation.

    Lab 2: search and holdout

    We generate an artificial population with two binary metadata fields and deliberately increased error at an intersection. Discovery and holdout are generated independently. Fisher compares each group with its complement; BH adjusts the prespecified family of six tests.

    [ ]Slices and BH controlBrowser
    import numpy as np
    from scipy.stats import fisher_exact
    def population(seed,n=1200):
        g=np.random.default_rng(seed)
        language=g.integers(0,2,n); long=g.integers(0,2,n)
        err=g.random(n)<np.where((language==1)&(long==1),.34,.12)
        return language,long,err
    def groups(lang,long):
        return [lang==0,lang==1,long==0,long==1,(lang==1)&(long==1),(lang==0)&(long==0)]
    def bh(p):
        p=np.asarray(p); order=np.argsort(p); q=np.empty(len(p)); running=1.
        for rank in range(len(p),0,-1):
            i=order[rank-1]; running=min(running,p[i]*len(p)/rank); q[i]=running
        return q
    def scan(data):
        lang,long,err=data; out=[]
        for mask in groups(lang,long):
            a=int(err[mask].sum()); b=int(mask.sum()-a)
            c=int(err[~mask].sum()); d=int((~mask).sum()-c)
            p=fisher_exact([[a,b],[c,d]],alternative='greater').pvalue
            out.append((mask.sum(),a/mask.sum(),p))
        return out,bh([x[2] for x in out])
    found,q=scan(population(160)); held,qheld=scan(population(161))
    for i,(a,b) in enumerate(zip(found,held)):
        print(i,'n, error, q descubrimiento:',a[0],round(a[1],3),f'{q[i]:.2g}',
              '| reserva:',b[0],round(b[1],3),f'{qheld[i]:.2g}')

    A second method clusters synthetic error representations without group labels. Clusters are descriptive proposals, not causal categories. The center must be learned on discovery and applied without refitting on holdout.

    [ ]Cluster error embeddingsBrowser
    from sklearn.cluster import KMeans
    g=np.random.default_rng(17)
    train=np.r_[g.normal([-2,0],.5,(100,2)),g.normal([2,0],.5,(100,2))]
    reserve=np.r_[g.normal([-2,0],.5,(50,2)),g.normal([2,0],.5,(50,2))]
    cluster=KMeans(n_clusters=2,random_state=17,n_init=5).fit(train)
    print('centros:',np.round(cluster.cluster_centers_,2))
    print('tamaños descubrimiento:',np.bincount(cluster.labels_))
    print('tamaños reserva:',np.bincount(cluster.predict(reserve)))

    An informative negative result

    Negative-result reporting specifies the sought effect and margin, interval and sensitivity, data and versions, implementation controls, budget, and conditions. “Not significant” does not mean zero effect; a wide interval may be compatible with both a useful effect and none. Mark exploratory decisions and make configuration, seeds, and outputs accessible. A weak replication does not refute a whole method family; a reproducible negative result can delimit where a claim holds.

    Exercises

    Numeric
    With 16 differences, one independent cause, and endpoints already checked, how many half-tests does bisection require in the worst case?
    Numeric
    Causes A, B, and C have probabilities 0.5, 0.3, and 0.2, and perfect tests costing 4, 1, and 1 hours. What is the minimum expected cost in hours?
    Quiz
    A vulnerability detector reports 99% on test. Which cheap first check gives immediate information?
    Quiz
    Which negative report is more useful?
    Code
    Implement ddmin(changes, test), with caching, returning a 1-minimal failing subset. test is deterministic and receives a sorted tuple.
    def ddmin(changes, test):
      pass
    Shift+Enter to run
    Key idea
    Reduce the failure, test competing hypotheses, and retain controls. A surprising score, a selected slice, and a negative result need the same evidence discipline.