Amirhosein-gh98
Gnosis
Python

Can LLMs Predict Their Own Failures? Self-Awareness via Internal Circuits

Last updated Jul 15, 2026
46
Stars
12
Forks
0
Issues
0
Stars/day
Attention Score
56
Language breakdown
Python 99.5%
Cuda 0.3%
Jupyter Notebook 0.1%
Dockerfile 0.1%
Shell 0.0%
C++ 0.0%
โ–ธ Files click to expand
README

Can LLMs Predict Their Own Failures? Self-Awareness via Internal Circuits

     

Gnosis Demo

Overview of our Gnosis self-awareness mechanism and its performance.

Gnosis Overview Figure

Gnosis is a lightweight self-awareness head attached to a (frozen) LLM backbone that predicts a scalar correctness probability for a generated response by reading the modelโ€™s hidden states + attention maps.


๐Ÿšจ NEW RELEASE ๐Ÿšจ

Multi-Head Latent Control

From predicting failures to actively controlling agents

Building on Gnosis, our new work turns latent self-awareness into real-time deployment decisions. Multi-Head Latent Control reads the internal states of frozen LLMs to decide when to answer, continue reasoning, ask for clarification, use tools, abstain, or route to a stronger modelโ€”achieving higher success while reducing plotted API cost by up to ~90% in our reported AndroidWorld settings.


๐Ÿ“ Repository layout

  • transformers/ โ€” local Transformers fork with Gnosis integrated into the model architecture
- Implemented under: - transformers/src/transformers/models/gpt_oss - transformers/src/transformers/models/qwen3
  • trl/ โ€” local TRL fork with a modified SFTTrainer to train the Gnosis head
- Key change: - trl/trl/trainer/sft_trainer.py
  • open-r1/ โ€” training code + configs
  • src/ โ€” inference + data tools (quickstart, scoring, preprocessing scripts)

๐Ÿงฉ Installation

โœ… Option A: One-command setup

From repo root:

chmod +x scripts/setupgnosisenv.sh
bash scripts/setupgnosisenv.sh
conda activate Gnosis

๐Ÿ› ๏ธ Option B: Manual install (exact steps)

<pre><code class="lang-bash">conda create -n Gnosis python=3.11 -y conda activate Gnosis

pip install --upgrade pip wheel setuptools pip install vllm==0.8.5.post1

python - &lt;&lt;&#39;PY&#39; import torch; print(&quot;Torch:&quot;, torch.version) PY

pip install flash-attn --no-build-isolation

pip uninstall -y transformers || true pip install -e ./transformers pip install -e &quot;./trl[vllm]&quot;

cd open-r1 GITLFSSKIP_SMUDGE=1 pip install -e &quot;.[dev]&quot; --no-deps cd ..

python - &lt;&lt;&#39;PY&#39; import pathlib, transformers, trl print(&quot;transformers โ†’&quot;, pathlib.Path(transformers.file).resolve()) print(&quot;trl โ†’&quot;, pathlib.Path(trl.file).resolve()) PY

export TOKENIZERS_PARALLELISM=false</code></pre>


โšก Quickstart: Use Gnosis on a single question

In this example, we first generate a solution for a single question (via vLLM or HF generation), then run Gnosis on (prompt + answer) to output a scalar correctness probability.

Task options: math, trivia, mmlu_pro

  • math / reasoning โ†’ step-by-step; final in \boxed{}
  • trivia โ†’ short factoid; final in \boxed{}
  • mmlu_pro โ†’ multiple-choice; final is only the letter in \boxed{}
<pre><code class="lang-python">import torch from transformers import AutoTokenizer, AutoModelForCausalLM from vllm import LLM from src.demo import ( buildchatprompt, makevllmsampling_params, generatewithvllm, generatewithhf, correctness_prob, )

GNOSISMODELID = &quot;Trainedgnosismodel&quot; VLLMMODELID = &quot;Qwen/Qwen3-1.7B&quot; USE_VLLM = False

SYSTEM_PROMPTS = { &quot;math&quot;: &quot;Please reason step by step, and put your final answer within \\boxed{}.&quot;, &quot;trivia&quot;: &quot;This is a trivia question. Put your final answer within \\boxed{}.&quot;, &quot;mmlu_pro&quot;: &quot;You are solving multiple-choice questions. Please reason step by step, and put your final answer with only the choice letter within \\boxed{}.&quot; }

tokenizer = AutoTokenizer.frompretrained(GNOSISMODELID, trustremote_code=True) model = AutoModelForCausalLM.from_pretrained( GNOSISMODELID, torch_dtype=torch.bfloat16, trustremotecode=True, ).cuda().eval()

prompt = buildchatprompt( tokenizer, question=&quot;How many r&#39;s are in strawberry?&quot;, systemprompt=SYSTEMPROMPTS[&quot;math&quot;], )

if USE_VLLM: llm = LLM( VLLMMODELID, **{ &quot;tensorparallelsize&quot;: 1, &quot;maxmodellen&quot;: 12000, &quot;dtype&quot;: &quot;bfloat16&quot;, &quot;gpumemoryutilization&quot;: 0.50, &quot;trustremotecode&quot;: True, }, ) sp = makevllmsamplingparams(temperature=0.6, topp=0.95, maxtokens=10000) answer = generatewithvllm(llm, prompt, sp) else: answer = generatewithhf( model, tokenizer, prompt, torch.device(&quot;cuda&quot;), maxnewtokens=10000, temperature=0.6, topp=0.95 )

pcorrect = correctnessprob( model, tokenizer, prompt + answer, torch.device(&quot;cuda&quot;), maxlenfor_scoring=None )

print(&quot;Answer:\n&quot;, answer) print(&quot;Gnosis correctness probability:&quot;, f&quot;{p_correct:.4f}&quot;)</code></pre>


๐Ÿ‹๏ธ Training Gnosis

๐Ÿงช Step 1 โ€” Data generation

Training begins with a simple pipeline: generate model completions (per dataset/benchmark) โ†’ verify them into binary correctness labels โ†’ merge + rebalance tasks (e.g., math + trivia) into one SFT-ready Parquet dataset.

โžก๏ธ Full, step-by-step instructions is provided in DATA_PREPROCESS.md.

๐Ÿš€ Step 2 โ€” Train with open-r1

Training configs live under:

open-r1/recipes/training/ (per-backbone YAMLs, e.g., Qwen3 / GPT-OSS, etc.)*

Example config:

  • open-r1/recipes/training/Qwen3/Qwen3-1.7Bhybridgnosis.yaml
To train:

<pre><code class="lang-bash">accelerate launch --configfile recipes/accelerateconfigs/zero2.yaml \ src/open_r1/sft.py \ --config recipes/training/Qwen3/Qwen3-1.7Bhybridgnosis.yaml</code></pre>

Note: This setup is currently configured for 2ร— A100 GPUs. Adjust the Accelerate/DeepSpeed config (and batch sizes, gradient accumulation, etc.) to match your available hardware.

๐Ÿ“Š Evalution

We provide a convenience wrapper script to run the scorer on multiple benchmark shard directories (e.g., Math / TriviaQA / MMLU-Pro) and write all outputs under one folder.

Script: src/evaluation/scripts/Gnosisrunall_scoring.sh It calls: src/evaluation/scorecompletionsGnosisoutputscoresscript_version.py

Edit these paths

  • MODEL="Pathtotrainedgnosisbackbone"
MATH10DIR=..., TRIVIADIR=..., MMLUPRO_DIR=... (dirs that contain shard-.parquet)
  • OUTBASE="outputs/scoredruns/Gnosis"

Run

<pre><code class="lang-bash">bash src/evaluation/scripts/Gnosisrunall_scoring.sh</code></pre>

Outputs are saved in: outputs/scoredruns/Gnosis/scored/name>/`


Star History

Star History Chart

Citation

If you find our work useful, please consider citing our paper in your research.
@article{ghasemabadi2025can,
  title={Can LLMs Predict Their Own Failures? Self-Awareness via Internal Circuits},
  author={Ghasemabadi, Amirhosein and Niu, Di},
  journal={arXiv preprint arXiv:2512.20578},
  year={2025}
}
๐Ÿ”— More in this category

ยฉ 2026 GitRepoTrend ยท Amirhosein-gh98/Gnosis ยท Updated daily from GitHub