Recall-adjusted answers in two modes¶
ask takes a point-in-time prompt and returns the model's answer, a recall estimate, and the answer corrected by that estimate. This notebook calls it once in each evidence mode and shows how to read the result.
Everything runs offline on an invented setup. The entry, the calibrators and the replies are made up. The numbers show what a result looks like and say nothing about any model.
Terms¶
| Term | Meaning |
|---|---|
| Recall estimate | A probability between 0 and 1 that the reply rests on recalled training text. It means what its calibrator was fitted to separate. Field p_memorized. |
| Corrected answer | The answer with each component multiplied by one minus the recall estimate. Field corrected. This is one way to use the estimate. |
| Logprobs mode | The recall estimate is computed from the alternatives per output token that the serving route returns with the reply. |
| Logits mode | The recall estimate is computed from the next-token vector, which a second host with the same weights returns for the reply. |
| Calibrator | The fitted map from that evidence to the recall estimate. Each mode has its own. |
| Status | What the catalogue records for an entry and mode: qualified, not qualified or not tested. Only a qualified mode gets a corrected answer. |
The prompt¶
worked_example() returns a point-in-time macro prompt and its decision definition. The prompt shows the macro state as z-scores and names no date and no ticker. The definition says how a reply is read: five loadings between -1 and 1.
from recall_guard import Mode, ask, load_catalogue, offline_example, worked_example
prompt, definition = worked_example()
print(prompt)
You are a macroeconomic game theorist. Characterize the current macro regime as continuous factor loadings.
You are given the macro state (z-scored against a rolling window) and an anonymized list of assets identified only by letter and category. You do not know what year it is; reason only from the numeric state in front of you.
Macro state (z-scored):
- baa10y_z: +0.85
- cpi_yoy_z: +1.20
- t10y2y_z: -0.65
Assets (anonymized):
- Asset_A: world_equity
- Asset_B: tech_sector
- Asset_C: gold_commodity
- Asset_D: short_treasury_cash
Characterize the regime as a continuous loading on each of these five macro axes:
- inflation
- growth
- credit_stress
- policy
- risk_appetite
Rules:
- Each loading is a continuous number in [-1, +1] (use -1 and +1 as the bounds).
- A loading describes how strongly the regime sits on that axis — it is NOT a trade, a bet, or a prediction.
- Do NOT output a long/short/neutral position and do NOT output a return for any asset; characterize the regime only.
Output a JSON object mapping each axis name to its loading, e.g. {"inflation": 0.4, "growth": -0.2, "credit_stress": 0.6, "policy": -0.1, "risk_appetite": -0.3}.
Ask in both modes¶
offline_example() supplies what a run needs when no model is running. example.arguments(mode) returns the keyword arguments of one ask call:
entry,mode,calibrator: what you pass on a real route too.client,full_distribution,catalogue,k,draws,min_parsed: offline stand-ins. On a real route the first two come from the entry's provider profile and the catalogue is the shipped one.
example = offline_example()
answers = {mode: ask(prompt, definition, **example.arguments(mode)) for mode in Mode}
Read the result¶
Each result carries the status it ran under, the recall estimate, the answer and the corrected answer. Both modes give the same answer here because they read the same replies. The recall estimates differ: each mode reads its own evidence through its own calibrator.
print(f"{'':16}" + "".join(f"{mode.value:>12}" for mode in Mode))
print(f"{'status':16}" + "".join(f"{answers[mode].status.value:>12}" for mode in Mode))
print(f"{'recall estimate':16}" + "".join(f"{answers[mode].p_memorized:>12.3f}" for mode in Mode))
print(f"{'draws used':16}" + "".join(f"{answers[mode].draws_used:>12}" for mode in Mode))
print()
print(f"{'component':16}{'answer':>12}" + "".join(f"{'corrected, ' + mode.value:>22}" for mode in Mode))
for name, value in answers[Mode.LOGPROBS].answer.items():
print(f"{name:16}{value:>12.3f}" + "".join(f"{answers[mode].corrected[name]:>22.3f}" for mode in Mode))
logprobs logits status qualified qualified recall estimate 0.177 0.329 draws used 8 8 component answer corrected, logprobs corrected, logits inflation 0.400 0.329 0.269 growth -0.200 -0.165 -0.134 credit_stress 0.300 0.247 0.201 policy 0.100 0.082 0.067 risk_appetite -0.300 -0.247 -0.201
The correction is a multiplication. The next cell checks it for every component and prints what limited each answer.
for mode, result in answers.items():
for name, value in result.answer.items():
assert abs(result.corrected[name] - value * (1 - result.p_memorized)) < 1e-12
print(f"{mode.value}: corrected = answer x (1 - {result.p_memorized:.3f}); limits: {list(result.limits) or 'none'}")
logprobs: corrected = answer x (1 - 0.177); limits: none logits: corrected = answer x (1 - 0.329); limits: none
Using the estimate¶
The recall estimate is the result. How it enters an analysis is the analyst's decision. corrected applies one rule, the multiplication above. Other rules are possible: weighting, filtering, or reporting the estimate beside the answer.
The training cutoff of the model decides whether the estimate applies at all:
| The period your data describes | What the estimate means | What to do |
|---|---|---|
| On or before the model's training cutoff | The model may have seen what happened next. The estimate measures how much the reply rests on that. | Use the estimate. An answer for this period needs correction. |
| After the model's training cutoff | The model cannot have seen what happened next. An estimate above zero is noise. | Do not correct. Use the answer as it is. |
ask does not know which period your data describes. Compare it with the model's cutoff before you use the estimate.
What differs between the modes¶
| Logprobs mode | Logits mode | |
|---|---|---|
| Evidence | The top alternatives per output token, as the route returns them | The next-token vector for each output token |
| Extra host | None | A second host that loads the same weights |
| Works when | The route returns logprobs | The route returns none, or you want the full vector |
| Calibrator | Fitted on logprobs evidence | Fitted on logits evidence |
A calibrator fitted for one mode is not used for the other. Pass one per mode, as example.calibrators does.
On your own route¶
Pass the id of a shipped catalogue entry and your calibrator. ask builds the client from the entry's provider profile.
result = ask(prompt, definition, entry="llamacpp-gemma3-4b", mode=Mode.LOGPROBS, calibrator=my_calibrator)
A calibrator is fitted on your model from prompts it has seen and prompts it has not:
from recall_guard import EstimateSource, MemoryGuardedScorer, SourceCalibrator
scorer = MemoryGuardedScorer.calibrate_client(client=my_client, is_memorized=seen_prompts, oos_control=unseen_prompts)
my_calibrator = SourceCalibrator.from_scorer(scorer, source=EstimateSource.TOP_K, corpus_sha256=None)
ask does not refuse an answer because of a status. For a mode that is not qualified it returns the answer and the recall estimate, leaves corrected empty and says why in reason and limits. That is the case for every shipped entry today, as the next cell shows.
catalogue = load_catalogue()
print(f"{'entry':34}" + "".join(f"{mode.value:>16}" for mode in Mode))
for entry in catalogue.entries:
statuses = [catalogue.qualification(entry.entry_id, mode).status.value for mode in Mode]
print(f"{entry.entry_id:34}" + "".join(f"{status.replace('_', ' '):>16}" for status in statuses))
entry logprobs logits flm-gemma3-4b not qualified not tested flm-gemma4-e4b not qualified not tested flm-llama3.2-3b not tested not tested llamacpp-gemma3-4b not tested not tested modal-gemma3-4b not qualified not tested modal-gpt-oss-20b not qualified not tested nim-llama3.1-70b not tested not tested ollama-gemma3-4b not qualified not tested ollama-gpt-oss-20b not tested not tested ollama-llama3.1-8b not qualified not tested ollama-llama3.2-3b not qualified not tested ollama-llava-llama3-ctx2048 not tested not tested ollama-phi4-mini not tested not tested ryzenai-oga-gemma4-e4b not tested not qualified
Online: the same call against a running model¶
The cells below send requests to a local model. They are off by default, so the notebook runs without one. To run a group, start its host, set RECALL_GUARD_ONLINE to the group's name and run the notebook from the repository root. Only one host runs at a time.
| Group | Start the host with | What it shows |
|---|---|---|
logprobs |
scripts/start_model_online_logprobs.ps1 (Linux: .sh) |
The logprobs mode on llama.cpp |
logits |
scripts/start_model_online_logits.ps1 |
The logits mode, on the replies the logprobs group drew |
npu |
scripts/start_model_online_npu.ps1 |
The logprobs mode on the NPU through FastFlowLM |
The outputs stored below come from one run of each group on one machine: 8 draws of one prompt. They show what a live result looks like. They are not a measurement of the model.
import json
import os
from pathlib import Path
from recall_guard import FixedReplies, FixedReply
ONLINE = os.environ.get("RECALL_GUARD_ONLINE", "") # "", "logprobs", "logits" or "npu"
ENTRY = "llamacpp-gemma3-4b"
DRAWS, MIN_PARSED = 8, 6
TEMPERATURE = 0.7 # the temperature the calibrators were fitted at
REPLIES = Path("runs/notebook/online_replies.json") # private: the replies the logits group reads again
# The hosts' gateways. LOCAL_MODEL_API_KEY must be set in the shell that runs the notebook.
ENVIRONMENT = {**os.environ,
"LLAMACPP_ENDPOINT_URL": "http://127.0.0.1:11571/v1/chat/completions"}
def show(result):
if result.failure is not None:
print(f"no answer: the {result.failure.step} step failed. {result.failure.remedy}")
return
estimate = "none" if result.p_memorized is None else f"{result.p_memorized:.3f}"
print(f"entry {result.entry_id}, mode {result.mode.value}, status {result.status.value.replace('_', ' ')}")
print(f"reason: {result.reason}")
print(f"recall estimate: {estimate}; draws used: {result.draws_used} of {result.draws_asked}")
print(f"corrected answer: {'none' if result.corrected is None else dict(result.corrected)}")
print("limits: " + ("; ".join(result.limits) or "none"))
print("answer: " + ", ".join(f"{name} {'undecided' if value is None else format(value, '+.2f')}"
for name, value in result.answer.items()))
print(f"online group: {ONLINE or 'none, the cells below do nothing'}")
online group: none, the cells below do nothing
Calibrators¶
A live recall estimate needs a calibrator fitted on the same model at the same settings. The next cell loads the two calibrators of the finance simulation from private records, one per mode. They were fitted to separate the identifying prompt from the anonymised prompt, at temperature 0.7. They are not shipped, so this cell works only where those records exist.
calibrators = None
if ONLINE in ("logprobs", "logits"):
from scripts.finance_sim.calibrate import calibrator_path, load_calibrator
from scripts.finance_sim.plan import load_plan
plan = load_plan("runs/finance-sim/plan/plan.json")
calibrators = {
mode: load_calibrator(calibrator_path("sampling", source, "macro"), plan, arm="sampling", kind="macro",
source=source).calibrator
for mode, source in ((Mode.LOGPROBS, "top_k"), (Mode.LOGITS, "full_distribution"))
}
print("loaded: " + ", ".join(f"{mode.value} calibrator" for mode in calibrators))
Online, logprobs¶
ask builds the client from the entry's provider profile. The client is built here instead, by the same function, so that the replies can be kept for the logits group.
if ONLINE == "logprobs":
from recall_guard.core.profiles import connect
from recall_guard.core.request_control import CallBudget
class Keeping:
"""The profile's client, keeping the text of every reply."""
def __init__(self, client):
self.client, self.config, self.texts = client, client.config, []
def generate(self, prompt, **parameters):
response = self.client.generate(prompt, **parameters)
self.texts.append(response.content)
return response
def __getattr__(self, name):
return getattr(self.client, name)
client = Keeping(connect(ENTRY, CallBudget(DRAWS), environment=ENVIRONMENT, enforce_preflight=False))
result = ask(prompt, definition, entry=ENTRY, mode=Mode.LOGPROBS, client=client, calibrator=calibrators,
draws=DRAWS, min_parsed=MIN_PARSED, temperature=TEMPERATURE, environment=ENVIRONMENT)
REPLIES.parent.mkdir(parents=True, exist_ok=True)
REPLIES.write_text(json.dumps(client.texts), encoding="utf-8")
show(result)
print(f"kept {len(client.texts)} replies for the logits group")
entry llamacpp-gemma3-4b, mode logprobs, status not tested reason: discrimination: no permutation p recorded recall estimate: 0.305; draws used: 8 of 8 corrected answer: none limits: no qualified mode for the entry answer: inflation +0.75, growth +0.50, credit_stress +0.30, policy -0.20, risk_appetite -0.40 kept 8 replies for the logits group
Online, logits¶
The logits host returns the next-token vector for a reply it is given. It serves the same model file as the logprobs host and the two do not run together. So this group reads the kept replies again through a fixed client and asks the logits host for their vectors.
if ONLINE == "logits":
from recall_guard.core.profiles import connect
from recall_guard.core.request_control import CallBudget
texts = json.loads(REPLIES.read_text(encoding="utf-8"))
config = connect(ENTRY, CallBudget(1), environment=ENVIRONMENT, enforce_preflight=False).config # builds the client, sends nothing
client = FixedReplies([FixedReply(text) for text in texts], config=config)
result = ask(prompt, definition, entry=ENTRY, mode=Mode.LOGITS, client=client, calibrator=calibrators,
draws=len(texts), min_parsed=MIN_PARSED, temperature=TEMPERATURE, environment=ENVIRONMENT)
show(result)
entry llamacpp-gemma3-4b, mode logits, status not tested reason: discrimination: no permutation p recorded recall estimate: 0.024; draws used: 8 of 8 corrected answer: none limits: no qualified mode for the entry answer: inflation +0.75, growth +0.50, credit_stress +0.30, policy -0.20, risk_appetite -0.40
Online, NPU¶
FastFlowLM serves a model on the NPU and returns logprobs with a reply. No logits host serves its NPU weights, so the logits mode is not offered for these entries. No calibrator has been fitted for this route on financial prompts, so the call returns the answer and the status without a recall estimate.
if ONLINE == "npu":
for mode in Mode:
record = load_catalogue().entry("flm-gemma3-4b").modes[mode]
print(f"{mode.value}: {'offered' if record.available or record.available is None else 'not offered: ' + record.unavailable_reason}")
import re
from dataclasses import replace
from recall_guard.core.profiles import connect, load_profile
from recall_guard.core.request_control import CallBudget
# The shipped profile allows 32 output tokens, too few for the five loadings; this run allows 512.
profile = load_profile("flm-gemma3-4b")
config = replace(profile.model_config, parameters={**profile.model_config.parameters, "max_tokens": 512})
client = connect(replace(profile, model_config=config), CallBudget(DRAWS), enforce_preflight=False)
# On this route the model wraps its JSON in a code fence and adds an explanation. The definition reads
# strict JSON, so this run reads the first JSON object of each reply.
def first_object(text):
found = re.search(r"\{.*?\}", text, flags=re.DOTALL)
return definition.parse(found.group(0) if found else text)
result = ask(prompt, replace(definition, parse=first_object), entry="flm-gemma3-4b", mode=Mode.LOGPROBS, client=client, draws=DRAWS,
min_parsed=MIN_PARSED, temperature=TEMPERATURE)
show(result)
logprobs: offered logits: not offered: the provider profile declares no full-distribution host for this route
entry flm-gemma3-4b, mode logprobs, status not qualified reason: boundary: recall boundary domain is document_text, not financial_time_series recall estimate: none; draws used: 8 of 8 corrected answer: none limits: no qualified mode for the entry; no calibrator supplied answer: inflation +0.60, growth +0.30, credit_stress -0.20, policy -0.10, risk_appetite -0.40