Conformal beyond exchangeability: conditional coverage, shift and risk control
Explore conditional coverage limitations and extensions of conformal prediction: group and function-class guarantees, weighting under covariate shift, adaptive conformal inference, monotone risk control, and LLM claim filtering.
After this lesson you can
- State the impossibility of distribution-free exact conditional coverage and explain its practical consequences.
- Implement Mondrian group conformal and weighted conformal under covariate shift with an estimated density ratio.
- Prove the ACI long-run average coverage guarantee for arbitrary sequences.
- Apply conformal risk control to a monotone loss such as false negative rate.
- Calibrate an LLM claim filter with a factuality guarantee on a labeled set.
Before you start
Ninety percent may not be enough
In the previous lesson we obtained marginal coverage averaged over calibration and one future case. If a minority population is much noisier, a global interval may often fail there even when the overall average is near target. Nor is there a guarantee if the destination hospital no longer resembles the calibration hospital. Before choosing a method, decide which unit, population, and error you want to protect.
Exact conditional coverage would require for almost every . Without distributional assumptions, requiring this for every distribution generally leads to trivial or infinitely long intervals; there is no useful universal repair. The result does not say coverage is impossible under a correct model or for a specific distribution: it says there is no finite, useful, distribution-free guarantee in general. Barber and colleagues formalize the limitation.
An intermediate guarantee fixes groups before calibration and requires marginal coverage within each. Mondrian applies the split quantile separately: calibration and the new case within each group need exchangeability, also conditional on training decisions. If the group has examples, ; for the threshold is infinite. Groups defined after inspecting errors do not automatically inherit the guarantee. Group coverage does not imply coverage at each point. A guarantee over a class of nonnegative functions can be stated as for each in the class with positive expectation. With it recovers group coverage; a richer class requires its own method, assumptions, and sample (Gibbs and colleagues).
Covariate shift: changing the measure
In weighted conformal prediction, suppose and that is absolutely continuous with respect to . With known ratio , for query use quantile of calibration scores with masses and an additional mass at , normalized by their sum. The new point is more likely to occupy a high-weight position: weighted ranks replace the rank argument. The theorem gives target-distribution marginal coverage, including calibration randomness; it does not promise coverage at each (Tibshirani and colleagues).
With a domain classifier fitted on additional covariates, is approximated by target-membership odds corrected for sampling proportions. This estimate does not automatically restore the exact guarantee. Kish effective sample size, , measures weight concentration and is not itself proof of validity. An excessively large query weight sends the quantile to infinity: that lack of information is a useful signal, not an implementation error.
ACI: accounting over time
For adaptive conformal inference, construct before observing , then receive and, for , update
When use the full set; when use the empty set. With , those rules force . Summing the update gives , so for any sequence
The accounting does not need exchangeability, but does require observing each outcome before updating and applying the extreme rules. It guarantees long-run error frequency, not coverage probability at each instant or informative intervals: sets may be empty or infinite. A large step reacts quickly and oscillates; a small one needs more time. Variants combine rates with their own analyses (Gibbs and Candès).
Controlling a loss, not only coverage
In conformal risk control, choose a nested family with loss nonincreasing as grows. For exchangeable loss functions under the theorem’s continuity and safe-endpoint conditions, take the smallest whose corrected risk satisfies
If no threshold exists on a finite grid, use the zero-loss safe endpoint. Then , where expectation includes calibration and the future example; this is not a high-probability bound for each calibration and does not guarantee every label. For multilabel prediction, define per-example FNR as the fraction of omitted true labels; enlarging the set decreases that loss. Label-aggregated FNR or F1 is not automatically the same quantity. Angelopoulos and colleagues establish the guarantee and its extensions.
If high-probability guarantees or selection among parameters are required, Learn then Test tests risk hypotheses and controls multiple errors; retrospectively choosing the best threshold without correction is insufficient (Angelopoulos and colleagues).
Lab: weights and volatility
The first experiment has one calibration per shift: the known-weight guarantee is marginal and an individual coverage can be below 90%. Logistic regression uses independent balanced domain samples, so its odds need no additional proportion factor. The second uses synthetic GARCH with an added shock and shows the extreme result when the quantile is infinite or the set empty.
import numpy as np
from sklearn.linear_model import LogisticRegression
def weighted_quantile(scores, weights, w_test, alpha):
scores=np.asarray(scores); weights=np.asarray(weights)
if not (0 < alpha < 1) or np.any(weights < 0) or w_test < 0 or weights.sum()+w_test <= 0:
raise ValueError('pesos o nivel inválidos')
order=np.argsort(scores); cum=np.cumsum(weights[order])
j=np.searchsorted(cum,(1-alpha)*(weights.sum()+w_test),side='left')
return scores[order[j]] if j<len(scores) else np.inf
def split_quantile(scores, alpha):
scores=np.sort(scores); k=int(np.ceil((len(scores)+1)*(1-alpha)))
return scores[k-1] if k<=len(scores) else np.inf
rng=np.random.default_rng(47)
for mu in [0,.5,1,1.5,2]:
x=rng.normal(size=300); xt=rng.normal(mu,1,size=1500)
r=np.abs(rng.normal(size=len(x)))*np.exp(.4*x)
rt=np.abs(rng.normal(size=len(xt)))*np.exp(.4*xt)
u=rng.normal(size=500); v=rng.normal(mu,1,size=500)
clf=LogisticRegression(C=1000).fit(np.r_[u,v].reshape(-1,1),np.r_[np.zeros(500),np.ones(500)])
true=np.exp(mu*x-mu*mu/2); true_t=np.exp(mu*xt-mu*mu/2)
est=np.exp(clf.decision_function(x.reshape(-1,1))); est_t=np.exp(clf.decision_function(xt.reshape(-1,1)))
q0=split_quantile(r,.1)
q1=np.array([weighted_quantile(r,true,w,.1) for w in true_t])
q2=np.array([weighted_quantile(r,est,w,.1) for w in est_t])
ess=(true.sum()**2)/(true@true)
print(f'mu={mu:.1f}: cobertura fija={np.mean(rt<=q0):.3f}, verdadera={np.mean(rt<=q1):.3f}, estimada={np.mean(rt<=q2):.3f}, ESS={ess:.1f}, infinitos={np.mean(np.isinf(q1)):.3f}')import numpy as np
rng=np.random.default_rng(71)
# GARCH(1,1), seguido por un choque temporal de volatilidad.
n=1200; z=rng.normal(size=n); sigma2=np.empty(n); e=np.empty(n); sigma2[0]=1; e[0]=z[0]
for t in range(1,n):
sigma2[t]=.04+.12*e[t-1]**2+.84*sigma2[t-1]
e[t]=z[t]*np.sqrt(sigma2[t])
e[650:900]*=3
scores=np.abs(e); alpha=.1; gamma=.03; a=alpha; errors=[]; fixed=[]; finite=[]
base=np.sort(scores[:200]); k=int(np.ceil((len(base)+1)*(1-alpha))); q_fixed=base[k-1]
for t in range(200,n):
past=np.sort(scores[t-200:t]); k=int(np.ceil((len(past)+1)*(1-a)))
if a<=0: q=np.inf
elif a>=1: q=-np.inf
else: q=past[k-1] if k<=len(past) else np.inf
err=int(scores[t]>q); errors.append(err); fixed.append(int(scores[t]>q_fixed))
if np.isfinite(q): finite.append(q)
a+=gamma*(alpha-err)
print('ACI cobertura:',round(1-np.mean(errors),4),'fijo:',round(1-np.mean(fixed),4))
print('cota determinista:',round((max(alpha,1-alpha)+gamma)/(gamma*len(errors)),4),'desviación:',round(abs(np.mean(errors)-alpha),4))
print('semianchura media solo finita:',round(np.mean(finite),4),'fracción de infinitos o vacíos:',round(1-len(finite)/len(errors),4))Local lab: filtering language-model claims
Conformal factuality requires an exact definition of correctness. Mohri and Hashimoto study gradually less specific responses with annotations; Quach and colleagues study answer sets. Here the scope is narrower: Qwen2.5-1.5B-Instruct answers questions with the SQuAD passage visible, and four short samples are mechanically split into sentences: the first is the candidate claim, the most frequent is chosen, and that frequency is the self-consistency score. A sentence may contain more than one fact: this approximate decomposition does not replace semantic claim annotation.
Download and run llm_generate.py and then llm_calibrate.py. You need CUDA, PyTorch, Transformers, SciPy, and NumPy; the first run downloads the model (revision 989aa7980e4cf806f80c7fef2b1adb7bc71aa306) and official SQuAD file if unavailable. The code takes one question per paragraph, shuffles with seed 2026, generates 300 answers, and reserves 200 for calibration and 100 for test. The label is normalized exact match with a reference answer: it may reject semantically correct answers and does not verify facts outside the passage. SQuAD is a fixed corpus, not a random sample of the world.
The filter tests four predetermined frequencies, computes a one-sided binomial bound per threshold, and uses Bonferroni for simultaneous selection. Under iid examples from the same process with correct labels, with at least 95% confidence each selected threshold has conditional error among accepted answers at most 10%. If none passes, abstain entirely; a conditional rate with zero answers is undefined. This is a Learn then Test-style test and does not claim a semantic guarantee on SQuAD or another deployment. Report retention, test accuracy, and fraction of words retained from the chosen answer: filtering and discarding sentences can lose content. In a real run, simultaneous calibration error bounds for frequencies 0.25, 0.5, 0.75, and 1 were 0.352, 0.305, 0.261, and 0.199: none reached 0.10. The procedure abstained across the test; unfiltered textual accuracy was 0.74. Sampling and CUDA can vary across runs.
import json,os,re,random,collections,sys,urllib.request
import numpy as np,torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from pathlib import Path
from scipy.stats import beta
MODEL='Qwen/Qwen2.5-1.5B-Instruct'; REVISION='989aa7980e4cf806f80c7fef2b1adb7bc71aa306'; N=int(os.environ.get('ORYON_N','300')); B=int(os.environ.get('ORYON_BATCH','4')); S=4
rng=random.Random(2026)
dataset=Path(os.environ.get('ORYON_SQUAD','dev-v1.1.json'))
if not dataset.exists(): urllib.request.urlretrieve('https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v1.1.json',dataset)
raw=json.loads(dataset.read_text(encoding='utf8'))
# One question per paragraph: reduce repeated contexts, still a fixed convenience corpus.
rows=[]
for article in raw['data']:
for p in article['paragraphs']:
if len(p['context'].split())>300: continue
q=p['qas'][0]; rows.append((p['context'],q['question'],[a['text'] for a in q['answers']]))
rng.shuffle(rows); rows=rows[:N]
torch.manual_seed(2026); torch.cuda.manual_seed_all(2026)
tok=AutoTokenizer.from_pretrained(MODEL,revision=REVISION,padding_side='left'); model=AutoModelForCausalLM.from_pretrained(MODEL,revision=REVISION,dtype=torch.float16).to('cuda').eval(); model.generation_config.pad_token_id=tok.eos_token_id
def norm(s):
s=s.lower(); s=re.sub(r'[^\w\s]',' ',s); s=re.sub(r'\b(a|an|the)\b',' ',s); return ' '.join(s.split())
result=[]
for start in range(0,len(rows),B):
batch=rows[start:start+B]; prompts=[]
for context,q,answers in batch:
messages=[{'role':'system','content':'Answer the question using the passage. Give only a short answer, with no explanation.'},{'role':'user','content':f'Passage: {context}\nQuestion: {q}\nShort answer:'}]
prompts.append(tok.apply_chat_template(messages,tokenize=False,add_generation_prompt=True))
inp=tok(prompts,return_tensors='pt',padding=True,truncation=True,max_length=700).to('cuda')
with torch.inference_mode():
out=model.generate(**inp,do_sample=True,temperature=.7,top_p=.9,max_new_tokens=24,num_return_sequences=S)
new=tok.batch_decode(out[:,inp.input_ids.shape[1]:],skip_special_tokens=True)
for j,(_,q,answers) in enumerate(batch):
candidates=new[j*S:(j+1)*S]; normalized=[norm(v) for v in candidates]; counts=collections.Counter(normalized); best=max(counts,key=lambda x:(counts[x],-normalized.index(x))); chosen=candidates[normalized.index(best)]
result.append({'question':q,'references':answers,'candidates':candidates,'answer':chosen,'agreement':counts[best]/S,'correct_exact':bool(best and best in {norm(a) for a in answers})})
print('done',len(result),'/',len(rows),flush=True)
Path(os.environ.get('ORYON_OUT','llm_outputs.json')).write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf8')
print('accuracy',np.mean([r['correct_exact'] for r in result]),flush=True)npm run lab and open the connection link.import json,os,re,collections,numpy as np
from scipy.stats import beta
from pathlib import Path
rows=json.loads(Path(os.environ.get('ORYON_OUT','llm_outputs.json')).read_text(encoding='utf8'))
def norm(s):
s=s.lower(); s=re.sub(r'[^\w\s]',' ',s); s=re.sub(r'\b(a|an|the)\b',' ',s)
return ' '.join(s.split())
def first_claim(s):
# Aproximación mecánica: una oración no tiene por qué ser atómica.
parts=[p.strip() for p in re.split(r'(?<=[.!?])\s+',s.strip()) if p.strip()]
return parts[0] if parts else ''
for row in rows:
claims=[first_claim(s) for s in row['candidates']]
keys=[norm(s) for s in claims]; counts=collections.Counter(keys)
key=max(counts,key=lambda k:(counts[k],-keys.index(k))); i=keys.index(key)
row['claim']=claims[i]; row['agreement']=counts[key]/len(keys)
row['correct_exact']=bool(key and key in {norm(x) for x in row['references']})
row['fraction_words_kept']=len(claims[i].split())/max(1,len(row['candidates'][i].split()))
assert len(rows)>=300, 'Genera al menos 300 preguntas para este reparto.'
cal,test=rows[:200],rows[200:300]; levels=[.25,.5,.75,1.]; delta=.05; valid=[]
for threshold in levels:
accepted=[x for x in cal if x['agreement']>=threshold]; m=len(accepted); errors=sum(not x['correct_exact'] for x in accepted)
upper=1. if m==0 or errors==m else beta.ppf(1-delta/len(levels),errors+1,m-errors)
print('umbral',threshold,'aceptadas',m,'errores',errors,'cota simultánea',round(upper,4))
if m and upper<=.1: valid.append(threshold)
print('exactitud global test',np.mean([x['correct_exact'] for x in test]))
if not valid:
print('retención test',0.)
print('Ningún umbral certificado: se abstiene siempre; no hay precisión condicional observable.')
else:
threshold=min(valid); chosen=[x for x in test if x['agreement']>=threshold]
print('umbral elegido',threshold,'retención test',len(chosen)/len(test),'exactitud test',sum(x['correct_exact'] for x in chosen)/len(chosen) if chosen else float('nan'))
print('fracción media de palabras retenidas en respuestas aceptadas',np.mean([x['fraction_words_kept'] for x in chosen]) if chosen else float('nan'))npm run lab and open the connection link.Exercises
Step 1 of 3. What prevents αₜ from decreasing while nonpositive?
def weighted_quantile(scores, weights, w_test, alpha):
passSummary of guarantees
| Method | Key assumption | Guarantee and limitation |
|---|---|---|
| Mondrian | predefined groups, within-group exchangeability | marginal group coverage, not individual coverage |
| Weighted | change only in X, overlap, known ratio | target marginal coverage; estimated weights do not ensure it exactly |
| ACI | sequential feedback and extreme-set rules | long-run error frequency, no pointwise coverage |
| CRC | exchangeable, bounded, monotone losses; safe endpoint | expected risk, not a bound for every calibration |
| LTT | valid hypotheses and tests with multiple correction | confidence-based risk control, conditional on label definition and population |