How to use from the
Use from the
Transformers library
# pip install -U transformers accelerate
# Load model directly
from transformers import AutoTokenizer, AutoModelForCausalLM

tokenizer = AutoTokenizer.from_pretrained("llavapp/llav-4b")
model = AutoModelForCausalLM.from_pretrained("llavapp/llav-4b", device_map="auto")
Quick Links

llav 4B

One model, several capabilities: retrieval evidence judging (used by llavRAG) and coding-agent action safety (used by llav-gate).

A decision model: a question in, a probability out. llav 4B answers one question about a passage: is this passage evidence that the question needs? It returns a probability instead of generated text. The model can also take the evidence already found and decide in that context.

llav 4B is the judge of llavRAG, an open retrieval engine that builds each search round from the passages the judge has ranked highest so far. llav Pro, our flagship decision model (llav 27B), is not released; it is coming soon as a managed API, by waitlist. llav 4B is the first llav model with released weights; the v0.4 research checkpoints were never published on Hugging Face.

Capabilities. You download one model; everything it can do ships in this repository:

capability what it decides how it runs used by
Retrieval: evidence judging is this passage evidence that the question needs? the weights below, as they are llavRAG
Coding agents: action safety is this shell command, as it would really run on this machine, destructive? the same weights plus two small LoRA adapters in skills/coding/, switched per call llav-gate

The coding-agent files are additions: the weights and every file llavRAG pins are byte-identical. Patch-review decisions (does this diff resolve the issue?) are not a skill of this model.

Developed by LLav Lab
Contact llachat.co@gmail.com
Model type Qwen3 causal LM (36 blocks, hidden size 2,560) used as a yes/no cross-encoder
Base model Qwen/Qwen3-Reranker-4B, Apache-2.0, Qwen team (Alibaba Cloud)
Modifications three LoRA fine-tuning stages and one checkpoint average, all merged into the base weights (no adapter needed at inference)
Weights model.safetensors, bf16, about 8 GB
Coding-agent files skills/coding/r3/ and skills/coding/l4r2/: LoRA rank 16 on every block, about 130 MB each (fp32), see Coding agents: action safety
Extra file calib.json: Platt parameters round0 (no evidence) and rounds (with evidence)
Language English
Licence Apache-2.0
Paper llavRAG: Evidence-Conditioned Multi-Hop Retrieval with an Open 4B Decision Model (Mengyi Sing, LLav Lab, preprint v0.3.1), DOI 10.5281/zenodo.24687037, llav.app/llavrag#paper

Input and output

Each decision uses one prompt in the Qwen3-Reranker format:

<|im_start|>system
Judge whether the Document meets the requirements based on the Query and the Instruct provided. Note that the answer can only be "yes" or "no".<|im_end|>
<|im_start|>user
<Instruct>: Given a multi-hop question, judge whether the passage states a fact that is necessary to answer it (including a fact that identifies an intermediate entity in the answer chain).
<Query>: {question}
Already retrieved evidence (context only): {title 1}: {text 1, first 300 characters} || {title 2}: {text 2, first 300 characters} || ...
<Document>: {candidate title}
{candidate text}<|im_end|>
<|im_start|>assistant
<think>

</think>
  • The Already retrieved evidence line is left out when no evidence has been found yet (the first round). At most ten evidence passages are included. llavRAG sends five.
  • Inputs longer than 2,048 tokens are truncated: the first 2,008 tokens and the last 39 are kept.
  • Raw output: P(yes) is the softmax over the logits of the tokens no and yes at the last position.
  • Platt mapping: p = sigmoid(a * logit(P(yes)) + b), with P(yes) clipped to [1e-6, 1 - 1e-6]. (a, b) comes from calib.json: round0 for requests without evidence, rounds for requests with evidence. Both pairs were fitted on loop states of 30 MuSiQue training questions that the last training stage did not train on. No benchmark question was used. llavRAG applies this mapping and so does the example below. Read the result as a ranking signal, and only roughly as a frequency on your own documents.
  • A second instruction for free-form yes/no questions exists (<Instruct>: Given a yes/no question about the Document, judge whether the correct answer is yes., with the question as <Query> and the text as <Document>). This mode was part of training but is not evaluated here and has no Platt mapping ("general": null).

How to use

With llavRAG (recommended). llavRAG downloads this model, indexes your documents and runs the multi-round search (uv tool install --python 3.12 llavrag, then llavrag download). It runs on Apple silicon (MLX) or an NVIDIA GPU; the verified machines are an Apple M5 Max 128 GB (about 13 s per question, median, measured with the reference implementation of the same core, not the package) and an NVIDIA RTX 3060 12 GB (about 65 s per question, with the embedder and this model taking turns on the GPU). See the llavRAG repository.

With transformers. This example scores one candidate. It follows the prompt and readout above (requires transformers>=4.51).

import json, math
import torch
from huggingface_hub import snapshot_download
from transformers import AutoModelForCausalLM, AutoTokenizer

path = snapshot_download("llavapp/llav-4b")
device = "cuda" if torch.cuda.is_available() else "cpu"
tok = AutoTokenizer.from_pretrained(path)
model = AutoModelForCausalLM.from_pretrained(
    path, torch_dtype=torch.float16 if device == "cuda" else torch.float32).to(device).eval()
calib = json.load(open(f"{path}/calib.json"))
YES = tok.encode("yes", add_special_tokens=False)[0]
NO = tok.encode("no", add_special_tokens=False)[0]

SYSTEM = ('Judge whether the Document meets the requirements based on the Query and the Instruct provided. '
          'Note that the answer can only be "yes" or "no".')
INSTRUCT = ("Given a multi-hop question, judge whether the passage states a fact that is necessary to answer it "
            "(including a fact that identifies an intermediate entity in the answer chain).")

def build_prompt(question, title, text, evidence=()):
    query = question
    if evidence:  # (title, text) pairs found so far: at most 10, each cut to 300 characters
        query += "\nAlready retrieved evidence (context only): " + " || ".join(
            f"{t}: {x[:300]}" for t, x in evidence[:10])
    return ("<|im_start|>system\n" + SYSTEM + "<|im_end|>\n<|im_start|>user\n"
            f"<Instruct>: {INSTRUCT}\n<Query>: {query}\n<Document>: {title}\n{text}"
            "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n")

def platt(p, ab):
    p = min(max(p, 1e-6), 1 - 1e-6)
    return 1 / (1 + math.exp(-(ab[0] * math.log(p / (1 - p)) + ab[1])))

@torch.inference_mode()
def p_evidence(question, title, text, evidence=()):
    ids = tok.encode(build_prompt(question, title, text, evidence), add_special_tokens=False)
    if len(ids) >= 2048:
        ids = ids[:2008] + ids[-39:]
    logits = model(input_ids=torch.tensor([ids], device=device), logits_to_keep=1).logits[0, -1]
    p_yes = torch.softmax(logits[[NO, YES]].float(), dim=-1)[1].item()
    return platt(p_yes, calib["rounds" if evidence else "round0"])

q = "Who directed the film that won Best Picture at the 1995 Academy Awards?"
title, text = "Forrest Gump", "Forrest Gump is a 1994 American film directed by Robert Zemeckis."
print(p_evidence(q, title, text))  # about 0.05: on its own, the passage does not show which film won
print(p_evidence(q, title, text, evidence=[("67th Academy Awards",
      "The 67th Academy Awards honored films of 1994. Forrest Gump won Best Picture.")]))  # about 0.92

The two calls show the evidence conditioning: the same passage becomes needed once the evidence names the film.

To rank candidates, score each one and sort by the probability. For many candidates that share one question, batch them. llavRAG also reuses the shared prompt prefix. Small fp16 differences between backends can reorder near-ties.

Coding agents: action safety

llav-gate is a local approval gate for coding agents (Claude Code and Codex hooks, and a command line). It loads this model once with both coding adapters and switches between them on each call. You do not pick a model: uv tool install --python 3.12 llav-gate, then llav-gate setup, uses the llav 4B that llavRAG uses (same folder) and adds only these files.

adapter what it reads file sha256
r3 the gate's expanded state: what the command really runs (task-runner scripts, aliases, inline code) with the file and line each came from, short local docs, and read-only facts about the files it touches; also each expanded command on its own 1d323bed711b23d800d1c65624cc80a7d6f31600470bd34742516c5da0bcf02a
l4r2 the command and the task only; trained further on shell commands labelled by their observed effects in a sandbox 21f41c1fb71f8061f5bc1b8dcef017ac2a3126aebb3dad24d198b17ca9bd3b99
  • Output: each adapter gives P(yes) for the question "Is this action destructive?" (same prompt format and readout as above, raw probability, no Platt mapping).
  • Combined score: llav-gate takes the higher of the two scores. Evidence can lower r3's score only to a quarter of its score on the command text alone. Unknown tools without docs, and code that would run but cannot be read, raise the score to at least 0.5.
  • Use it through llav-gate. The adapters are not meant to be used without the gate's expansion and rule.

Evaluation. The configuration was frozen first (both adapters, the rule, the thresholds), then scored once on a sealed exam written by a separate author:

  • 160 pairs, each a dangerous command and a safe twin that looks like it, with a description of the machine each runs on;
  • 96 pairs from command families the exam author found nowhere in the training data;
  • 32 pairs that differ only in machine state.

The baseline is a strong existing approval model for coding agents, scored on the command and the task (its inputs).

149 command pairs llav 4B (llav-gate) baseline
dangerous commands scored ≤ 0.10 ("confident misses") 19 29
AUROC 0.732 [0.693, 0.773] 0.682 [0.648, 0.723]
  • Difference: AUROC +0.049 [+0.006, +0.091] (paired bootstrap, 95%). On all 160 pairs: 19 vs 29 misses, +0.052 [+0.013, +0.093].
  • Excluded from the 149, before scoring: 4 pairs where only a note revealed the danger, and 7 pairs that overlap the skill's training files.
  • Caveats:
    • On unseen tools the separation is level with the baseline (strict-unseen −0.005 [−0.059, +0.050]; non-adjacent part −0.036 [−0.107, +0.033]), though with fewer misses.
    • Cases that hinge on machine state are near chance for both.
    • 19 of 160 dangerous commands were still scored ≤ 0.10. One would have passed without a question: direnv allow on a downloaded .envrc.
    • The gate asks often, and no claim is made about how often it interrupts.

Full tables: llav-gate's RESULTS.md.

Intended use

  • Deciding whether a passage is evidence needed for a question, with or without evidence already found, as the judge inside llavRAG or inside your own retrieval or RAG pipeline.
  • Ranking or filtering candidate passages before they go to a reader, an LLM or a person.
  • Research on retrieval built from decisions.
  • Judging whether a coding agent's shell command is destructive, through llav-gate, as one layer next to your agent's own permission prompts and sandboxing.

Out-of-scope use

  • Generating text or answers. The model outputs a yes/no probability only.
  • Patch-review decisions (does this diff resolve the issue?). Not trained.
  • Command-safety decisions without llav-gate's expansion and coding-agent adapters, or as the only safeguard: it still misses dangerous commands (see Coding agents: action safety).
  • General-purpose yes/no or classification decisions. The free-form mode is not evaluated.
  • Decisions about people (for example credit, employment, housing, medical or legal matters) without qualified human review.
  • Content moderation or safety filtering. Toxicity datasets are part of the training mix, but the model is not evaluated for moderation.
  • Non-English text. The model was trained and evaluated on English only.
  • Reading the probability as a guaranteed frequency on your own data.

Evaluation

All numbers come from the paper. They are retrieval results of the frozen llavRAG v0.3 system with llav 4B as its only judge (the standard tier), so they measure the whole system with this model inside, not the model alone. llav 4B ran in fp16 with MLX on one Apple M5 Max laptop.

Test set: fresh-2. 1,200 multi-hop test questions that none of our runs or training files had used: 600 MuSiQue questions from the MuSiQue training split, plus 300 2WikiMultiHopQA and 300 HotpotQA questions from the development splits. Any question whose identifier, normalised text or any word 13-gram occurs in any of our training or evaluation files was excluded. Each dataset has its own closed corpus of English Wikipedia paragraphs (13,977, 6,186 and 9,841 passages). The set was built before any result of llavRAG v0.3 existed, and the frozen system was run on it once.

setting R@10 AE@10
llavRAG v0.3 with llav 4B only, all 1,200 questions 95.0 87.6
llavRAG v0.3 with llav 4B only, MuSiQue (600 questions) 91.0 77.2
one pass (round 0 only): hybrid BM25 + dense pool ranked by llav 4B, all 1,200 questions 83.9 63.5
  • R@10: share of a question's gold supporting passages among the first 10 distinct documents, averaged over questions.
  • AE@10: share of questions with all gold supporting passages in the top 10.
  • The one-pass row comes from the same run's logged decisions (no new model calls). It is the question-weighted mean over the three datasets. It costs 100 judgments per question; llavRAG costs about 318 (243-390), about 3× as many. With the same budget spent on one pass over a deeper hybrid pool, R@10 reaches 79.4 on MuSiQue-f2 and 79.3 on 2WikiMultiHopQA-f2; the same loop with the untuned base Qwen3-Reranker-4B as judge reaches 77.3 on MuSiQue-f2 (paper, Table 9). Other off-the-shelf rerankers were not compared.
  • llav 4B is fine-tuned on the training splits of these three datasets. The test questions were excluded from all training data, but passages overlap; see Limitations.
  • On 2WikiMultiHopQA and HotpotQA the system is close to 100%, so MuSiQue carries most of the information.

Training

Labels come only from the datasets' gold annotations (supporting-paragraph flags or class labels), converted to yes/no by our own scripts. No label was produced by an external or hosted model. No question from the evaluation sets above is in any training file: exact question matches 0, word 13-gram question matches 0.

stage what data
1. listwise retrieval LoRA (rank 8) on the last 16 of 36 blocks, pointwise yes/no cross-entropy plus listwise cross-entropy over each question's candidate group, 1,750 steps MuSiQue training split (BM25 hard negatives and gold paragraphs); 1,000 HotpotQA (distractor, train) and 1,000 2WikiMultiHopQA (train) questions
2. average uniform average of the stage-1 checkpoints at steps 250, 1,250 and 1,750, merged none
3. general decisions LoRA (rank 16) on all blocks, binary cross-entropy, 1,000 steps, merged 127,683 rows: MNLI 23,850; MuSiQue retrieval rows 19,850; FEVER 19,847; CLINC150 15,850; Banking77 13,850; Civil Comments 11,850; SNLI 7,850; toxic_conversations 7,780; BoolQ 6,956
4. on-policy states the stage-3 model runs an earlier prototype of the retrieval loop, and every round's state and candidate pool is logged 2,099 (question, round) groups from MuSiQue training questions
5. own loop states LoRA (rank 8) on the last 16 blocks, groups of 16 candidates, pointwise plus listwise loss, 1,200 steps, merged the stage-4 groups, labelled with MuSiQue supporting-paragraph flags
6. selection and Platt mapping checkpoint 1,200 chosen over 600 by end-to-end retrieval; Platt parameters fitted on round states 50 MuSiQue training questions that stage 5 did not train on (Platt: 30 of them)

Datasets and licences

dataset licence stage
MuSiQue (Trivedi et al., 2022), official release (StonyBrookNLP) CC BY 4.0 1, 3, 4-6
HotpotQA (Yang et al., 2018), distractor setting, via the Hub copy hotpotqa/hotpot_qa CC BY-SA 4.0 1
2WikiMultiHopQA (Ho et al., 2020), via the Hub mirror xanhho/2WikiMultihopQA Apache-2.0 1
MultiNLI (Williams et al., 2018) OANC; fiction genre partly CC BY-SA 3.0 / CC BY 3.0 3
SNLI (Bowman et al., 2015) CC BY-SA 4.0 3
BoolQ (Clark et al., 2019) CC BY-SA 3.0 3
FEVER (Thorne et al., 2018), copenlu/fever_gold_evidence CC BY-SA 3.0 (FEVER / Wikipedia terms) 3
Civil Comments; SetFit/toxic_conversations_50k (Jigsaw Unintended Bias text) CC0-1.0 3
CLINC150 (Larson et al., 2019) CC BY 3.0 3
Banking77 (Casanueva et al., 2020) CC BY 4.0 3

Several sources are ShareAlike, and MuSiQue, HotpotQA, 2WikiMultiHopQA, BoolQ and FEVER reuse Wikipedia text (CC BY-SA). The licence audit, with per-source notes, is published with llavRAG (LICENSE-AUDIT.md). fresh-2 data record released with the paper (identifiers and scores, no text): CC BY 4.0 (DOI 10.5281/zenodo.24687039); full per-question decision traces are not yet released (CC BY-SA 4.0 if released).

Coding agents: training.

  • Both adapters are LoRA (rank 16, all blocks) trained on top of these weights. KL anchors come from this model's own probabilities.
  • r3: coding-agent decision states in three stages (2,481 + 468 + 214 steps).
  • l4r2: continues r3 for 1,216 steps, on rows labelled by observed sandbox effects plus rehearsal and replay rows.
  • Sources:
    • tldr-pages (CC BY 4.0: command templates filled in and run in a sandbox, page excerpts quoted);
    • SWE-smith and SWE-smith-trajectories (MIT);
    • SWE-bench-extra (CC BY 4.0);
    • SWE-Gym (MIT / Apache-2.0);
    • code excerpts from 75+ permissively licensed repositories;
    • the general replay mix above.
  • Labels come from sandbox execution effects, documented command semantics, tests and dataset gold. None comes from an external model.
  • Some inputs (task lines and previous agent steps from SWE-smith trajectories) were written by language models (Claude 3.7 Sonnet, Claude 3.5 Sonnet, GPT-4o, and an unnamed model for SWE-smith issue texts). They were used only as inputs.
  • No evaluation item and no Llama-generated text was used.
  • Provenance: llav-gate's LICENSE-AUDIT.md.

Limitations

  • Coding agents. Action safety is evaluated on one sealed exam of 160 command pairs; see the caveats under Coding agents: action safety. It reads the command, local files and docs, not remote state (servers, cloud resources, remote git branches).

  • Scale and domain. Every evaluation corpus has 6,000 to 14,000 passages of English Wikipedia text, and the questions are public multi-hop benchmark questions. We have not measured the model on large or non-Wikipedia collections or on business documents.

  • In-domain fine-tuning and passage overlap. The model is fine-tuned on the training splits of MuSiQue, HotpotQA and 2WikiMultiHopQA. The MuSiQue part of fresh-2 comes from MuSiQue's training split: 597 of its 600 questions have a gold passage in the fine-tuning data, even though the questions themselves are not in it. The paper's overlap analyses are inconclusive, and MuSiQue-f2 is not independent of the judge's training data.

  • Public benchmarks and pretraining. The pretraining data of the base model is not public and was not audited. Public benchmark data may be part of it.

  • Training states. Stage 5 used states from an earlier prototype of the retrieval loop, not from llavRAG v0.3.

  • Platt mapping. Both Platt pairs rest on the round states of 30 training questions from one dataset. On other data, read the probabilities as a ranking signal.

  • Numerics. Rankings can change slightly across backends and batch sizes (fp16 rounding). In a multi-round loop, a changed near-tie can move a passage into or out of the top 10.

  • Cost. In llavRAG the model makes about 300 decisions per question, so latency depends heavily on the hardware: about 13 s per question (median) on an Apple M5 Max, measured with the reference implementation of the same core, not the package, and about 65 s on an NVIDIA RTX 3060 12 GB. Other hardware has not been verified.

  • Bias. The model inherits biases of its base model and training datasets. It was not evaluated for fairness.

Citation

@misc{sing2026llavrag,
  title  = {llavRAG: Evidence-Conditioned Multi-Hop Retrieval with an Open 4B Decision Model},
  author = {Sing, Mengyi},
  year   = {2026},
  note   = {LLav Lab. Preprint v0.3.1},
  doi    = {10.5281/zenodo.24687037},
  url    = {https://doi.org/10.5281/zenodo.24687037}
}

Base model:

@article{zhang2025qwen3embedding,
  title   = {Qwen3 Embedding: Advancing Text Embedding and Reranking Through Foundation Models},
  author  = {Zhang, Yanzhao and Li, Mingxin and Long, Dingkun and Zhang, Xin and Lin, Huan and Yang, Baosong and Xie, Pengjun and Yang, An and Liu, Dayiheng and Lin, Junyang and Huang, Fei and Zhou, Jingren},
  journal = {arXiv preprint arXiv:2506.05176},
  year    = {2025}
}

Licence

Apache-2.0. llav 4B is a modified version of Qwen3-Reranker-4B (Apache-2.0, Qwen team, Alibaba Cloud). If you redistribute it, keep the licence and the attribution notice. The training datasets keep their own licences (see above).

Downloads last month
53
Safetensors
Model size
4B params
Tensor type
BF16
·
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support

Model tree for llavapp/llav-4b

Finetuned
(23)
this model

Datasets used to train llavapp/llav-4b

Paper for llavapp/llav-4b