SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2310.11511 · 2023

Self-RAG: Learning to Retrieve, Generate, and Critique through Self-Reflection

arXiv · PDF · Open in the Atlas

Code that ran

11 of 14 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (0 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 1 violated it and 0 have no contract verdict; 10 failures of our instrument; 3 no recorded run), measured 2026-11-23; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2310.11511.json · badge: /api/ran/2310.11511.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
AkariAsai/self-rag canonical (classifier label)
classifier basis: plan_row
8 ran · 2 no recorded run
copy not recorded community
not in the paper's declared repositories
2 ran · 0 no recorded run
fate-ubw/raglab extension (classifier label)
classifier basis: classifier_2025
1 ran · 0 no recorded run
ShayekhBinIslam/openrag extension (classifier label)
classifier basis: classifier_2025
0 ran · 1 no recorded run
FunctionStatusWhere it lives
accuracy Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
AkariAsai/self-rag/retrieval_lm/metrics.py
pointer only (licence: MIT); the stored copy get_code serves, from Haoang97/CausalProbe-2024, is pointer only (licence: NONE) · get_code("e76cf27d36723be3")
How it ran

The body of this sample is withheld: this paper's link allows the body inline (MIT), but get_code serves the stored copy, first harvested from Haoang97/CausalProbe-2024, and GitHub detected no licence in that repository when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

apply_rotary_pos_emb Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
this paper's copy was not recorded; identical code first harvested from shaochenze/patchtrain
pointer only · get_code("f725bc2d76076485")
How it ran

The body of this sample is withheld: this paper's copy of the code was not recorded (its link names no repository or source path), so no licence was read for it. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

encode_with_messages_format Ran
ran; our contract draft was wrong, not the code
AkariAsai/self-rag/retrieval_lm/finetune.py
code served (permissive licence) · get_code("1cb0eeb16cf04ee3")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned dict. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
from unittest.mock import Mock

torch.manual_seed(0)

class MockTokenizer:
    def __init__(self):
        self.eos_token = '<|end|>'
    
    def __call__(self, text, return_tensors=None, max_length=None, truncation=None):
        # Return a mock tokenization result with input_ids
        # We need to return different lengths based on the text to simulate real tokenization
        text_len = len(text.split())
        token_count = min(text_len + 5, max_length) if max_length else text_len + 5
        
        result = Mock()
        result.input_ids = torch.randint(0, 1000, (1, token_count))
        return result

example = {
    'messages': [
        {
            'role': 'system',
            'content': 'You are a helpful assistant.'
        },
        {
            'role': 'user',
            'content': 'Hello, how are you?'
        },
        {
            'role': 'assistant',
            'content': 'I am doing well, thank you for asking.'
        }
    ]
}

tokenizer = MockTokenizer()
max_seq_length = 128

ARGS = {
    'example': example,
    'tokenizer': tokenizer,
    'max_seq_length': max_seq_length
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type dict — a dict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dict output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
exact_match_score Ran
ran, violated the contract we drafted
AkariAsai/self-rag/retrieval_lm/metrics.py
pointer only (licence: MIT); the stored copy get_code serves, from Haoang97/CausalProbe-2024, is pointer only (licence: NONE) · get_code("d97ab73d08dfa3b9")
How it ran

The body of this sample is withheld: this paper's link allows the body inline (MIT), but get_code serves the stored copy, first harvested from Haoang97/CausalProbe-2024, and GitHub detected no licence in that repository when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

jload Ran
ran; our contract draft was wrong, not the code
AkariAsai/self-rag/data_creation/train_special_tokens.py
code served (permissive licence) · get_code("3ca38f9acc00194b")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned dict. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import json
import io
import tempfile
import os

# Create a temporary JSON file for testing
temp_dir = tempfile.mkdtemp()
temp_file = os.path.join(temp_dir, "test.json")

# Write a simple test dictionary to the file
test_dict = {"key1": "value1", "key2": [1, 2, 3], "key3": {"nested": "dict"}}
with open(temp_file, 'w') as f:
    json.dump(test_dict, f)

ARGS = {
    "f": temp_file,
    "mode": "r"
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type dict — a dict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dict output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
load_data Ran
ran; our contract draft was wrong, not the code
AkariAsai/self-rag/retrieval_lm/passage_retrieval.py
code served (permissive licence) · get_code("0c3de3890cd0b382")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned list, ndim 1, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import json
import tempfile
import os

# Create temporary JSON file
temp_dir = tempfile.mkdtemp()
json_file = os.path.join(temp_dir, "test_data.json")

# Write test data to JSON file
test_data = [
    {"id": 1, "text": "hello"},
    {"id": 2, "text": "world"}
]
with open(json_file, 'w') as f:
    json.dump(test_data, f)

ARGS = {
    "data_path": json_file
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type list, ndim 1, dtype family float — a list output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
metric_max_over_ground_truths Ran
ran; our contract draft was wrong, not the code
AkariAsai/self-rag/retrieval_lm/metrics.py
code served (permissive licence) · get_code("6829ceb72569fa12")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned float, ndim 0, dtype family float, shape () as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import numpy as np

torch.manual_seed(0)

def simple_metric_fn(prediction, ground_truth):
    """A simple metric function that computes similarity between two tensors."""
    if isinstance(prediction, torch.Tensor) and isinstance(ground_truth, torch.Tensor):
        return float(torch.nn.functional.cosine_similarity(
            prediction.unsqueeze(0), 
            ground_truth.unsqueeze(0)
        ).item())
    return 0.0

prediction = torch.randn(4)
ground_truths = [torch.randn(4), torch.randn(4), torch.randn(4)]

ARGS = {
    "metric_fn": simple_metric_fn,
    "prediction": prediction,
    "ground_truths": ground_truths,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type float, ndim 0, dtype family float, shape () — shape () as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
preprocess Ran
ran; our contract draft was wrong, not the code
AkariAsai/self-rag/data_creation/train_special_tokens.py
code served (permissive licence) · get_code("342f5e0ec01b9ed8")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned dict. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import transformers
from typing import Sequence

torch.manual_seed(0)

class MockTokenizer:
    def __init__(self):
        self.model_max_length = 512
        self.pad_token_id = 0
    
    def __call__(self, text, return_tensors=None, padding=None, max_length=None, truncation=None):
        # Simple mock: tokenize text into token IDs
        # Use deterministic token generation based on text length
        tokens = [i + 1 for i in range(len(text.split()) + 2)]
        input_ids = torch.tensor([tokens], dtype=torch.long)
        
        class MockTokenizerOutput:
            def __init__(self, ids):
                self.input_ids = ids
            
            def ne(self, pad_id):
                # Return a tensor of bools indicating non-pad tokens
                return (self.input_ids != pad_id).long()
        
        return MockTokenizerOutput(input_ids)

tokenizer = MockTokenizer()

sources = [
    "This is source one.",
    "This is source two."
]

targets = [
    "This is target one.",
    "This is target two."
]

skip_tokens = [5, 6]

context_markups = [10, 11]

ARGS = {
    "sources": sources,
    "targets": targets,
    "tokenizer": tokenizer,
    "skip_tokens": skip_tokens,
    "context_markups": context_markups
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type dict — a dict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dict output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
randomcrop Ran
ran; our contract draft was wrong, not the code
AkariAsai/self-rag/retrieval_lm/src/data.py
pointer only (licence: MIT); the stored copy get_code serves, from facebookresearch/contriever, is pointer only (licence: NOASSERTION) · get_code("e037474365501512")
How it ran

The body of this sample is withheld: this paper's link allows the body inline (MIT), but get_code serves the stored copy, first harvested from facebookresearch/contriever, and GitHub could not classify the licence of that repository (NOASSERTION). The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

read_jsonl Ran
ran; our contract draft was wrong, not the code
fate-ubw/raglab/raglab/rag/train_alg/finetune.py
code served (permissive licence) · get_code("6242dd60b264c96f")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned list, ndim 1, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import json
import tempfile
import os

# Create a temporary JSONL file with valid JSON lines
temp_dir = tempfile.mkdtemp()
temp_file = os.path.join(temp_dir, "test.jsonl")

# Write some valid JSON lines to the temporary file
with open(temp_file, 'w', encoding='utf-8') as f:
    f.write(json.dumps({"id": 1, "text": "hello"}) + "\n")
    f.write(json.dumps({"id": 2, "text": "world"}) + "\n")
    f.write("invalid json line\n")
    f.write(json.dumps({"id": 3, "text": "test"}) + "\n")

ARGS = {
    "file_path": temp_file
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type list, ndim 1, dtype family float — a list output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
rotate_half Ran
ran; our contract draft was wrong, not the code
this paper's copy was not recorded; identical code first harvested from fe1ixxu/ALMA
pointer only · get_code("b99eea6376d1e212")
How it ran

The body of this sample is withheld: this paper's copy of the code was not recorded (its link names no repository or source path), so no licence was read for it. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

encode_with_prompt_completion_format Not yet run
unverified (harvested, no recorded run)
AkariAsai/self-rag/retrieval_lm/finetune.py
code served (permissive licence) · get_code("aac14d7de4178849")
How it ran

no invocation recorded.

load_balancing_loss_func Not yet run
unverified (harvested, no recorded run)
ShayekhBinIslam/openrag/openrag/modeling_openrag.py
pointer only (licence: CC-BY-4.0) · get_code("d9308d9bf18cd072")
How it ran

The body of this sample is withheld: CC-BY-4.0, as GitHub detects it on this paper's repository, ShayekhBinIslam/openrag, is not in the permissive set Syntology serves inline. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. No invocation recorded.

make_supervised_data_module Not yet run
unverified (harvested, no recorded run)
AkariAsai/self-rag/data_creation/train_special_tokens.py
code served (permissive licence) · get_code("c22fc64f9f9730e4")
How it ran

no invocation recorded.

Also present in other papers' code

Of 14 samples lifted from this paper's linked repositories, 14 carry a function identity and 0 do not. Of the 14 distinct functions with an identity, 10 are also present in other papers whose code we hold (5 with at least one paper dated earlier, 4 the same month, 10 later) and 4 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

FunctionAlso present inEarliest-datedOthers named
rotate_half 360 other papers
28 dated earlier, 10 the same month, 319 later, 3 undated · 30 only as an assembly brick
1901.02860 (2019-01)
Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context
2203.08913 (2022-03)
Memorizing Transformers
2302.13971 (2023-02)
LLaMA: Open and Efficient Foundation Language Models
and 357 more not named here
apply_rotary_pos_emb 83 other papers
6 dated earlier, 2 the same month, 75 later · 6 only as an assembly brick
2306.15595 (2023-06)
Extending Context Window of Large Language Models via Positional Interpolation
2307.05695 (2023-07)
ReLoRA: High-Rank Training Through Low-Rank Updates
2307.06945 (2023-07)
In-context Autoencoder for Context Compression in a Large Language Model
and 80 more not named here
exact_match_score 56 other papers
37 dated earlier, 16 later, 3 same year, order not determinable
1508.06615 (2015-08)
Character-Aware Neural Language Models
1606.05250 (2016-06)
SQuAD: 100,000+ Questions for Machine Comprehension of Text
1608.07905 (2016-08)
Machine Comprehension Using Match-LSTM and Answer Pointer
and 53 more not named here
jload 46 other papers
11 dated earlier, 2 the same month, 33 later
2302.13971 (2023-02)
LLaMA: Open and Efficient Foundation Language Models
2305.12870 (2023-05)
Lion: Adversarial Distillation of Proprietary Large Language Models
2305.13068 (2023-05)
Making Language Models Better Tool Learners with Execution Feedback
and 43 more not named here
encode_with_messages_format 8 other papers
1 the same month, 7 later
2310.08491 (2023-10)
Prometheus: Inducing Fine-grained Evaluation Capability in Language Models
2311.05657 (2023-11)
Agent Lumos: Unified and Modular Training for Open-Source Language Agents
2401.08565 (2024-01)
Tuning Language Models by Proxy
and 5 more not named here
load_balancing_loss_func 7 other papers
7 later
2405.13845 (2024-05)
Semantic Density: Uncertainty Quantification for Large Language Models through Confidence Measurement in Semantic Space
2408.00264 (2024-08)
Clover-2: Accurate Inference for Regressive Lightweight Speculative Decoding
2507.22424 (2025-07)
Spec-VLA: Speculative Decoding for Vision-Language-Action Models with Relaxed Acceptance
and 4 more not named here
randomcrop 7 other papers
7 later
2402.03216 (2024-02)
M3-Embedding: Multi-Linguality, Multi-Functionality, Multi-Granularity Text Embeddings Through Self-Knowledge Distillation
2402.07867 (2024-02)
PoisonedRAG: Knowledge Corruption Attacks to Retrieval-Augmented Generation of Large Language Models
2403.06840 (2024-03)
RA-ISF: Learning to Answer and Understand from Retrieval Augmentation via Iterative Self-Feedback
and 4 more not named here
metric_max_over_ground_truths 6 other papers
2 dated earlier, 4 later
2104.08773 (2021-04)
Cross-Task Generalization via Natural Language Crowdsourcing Instructions
2210.10861 (2022-10)
QA Domain Adaptation using Hidden Space Augmentation and Self-Supervised Contrastive Adaptation
2402.03216 (2024-02)
M3-Embedding: Multi-Linguality, Multi-Functionality, Multi-Granularity Text Embeddings Through Self-Knowledge Distillation
and 3 more not named here
accuracy 3 other papers
3 later
2402.03216 (2024-02)
M3-Embedding: Multi-Linguality, Multi-Functionality, Multi-Granularity Text Embeddings Through Self-Knowledge Distillation
2406.11357 (2024-06)
Refiner: Restructure Retrieval Content Efficiently to Advance Question-Answering Capabilities
2506.21215 (2025-06)
Unveiling Causal Reasoning in Large Language Models: Reality or Mirage?
load_data 3 other papers
3 later
2025.emnlp-main.192 (2025 (year only))
RAG-Instruct: Boosting LLMs with Diverse Retrieval-Augmented Instructions
2501.00353 (2025-01)
RAG-Instruct: Boosting LLMs with Diverse Retrieval-Augmented Instructions
2506.21215 (2025-06)
Unveiling Causal Reasoning in Large Language Models: Reality or Mirage?

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-23.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Despite their remarkable capabilities, large language models (LLMs) often produce responses containing factual inaccuracies due to their sole reliance on the parametric knowledge they encapsulate. Retrieval-Augmented Generation (RAG), an ad hoc approach that augments LMs with retrieval of relevant knowledge, decreases such issues. However, indiscriminately retrieving and incorporating a fixed number of retrieved passages, regardless of whether retrieval is necessary, or passages are relevant, diminishes LM versatility or can lead to unhelpful response generation. We introduce a new framework called Self-Reflective Retrieval-Augmented Generation (Self-RAG) that enhances an LM's quality and factuality through retrieval and self-reflection. Our framework trains a single arbitrary LM that adaptively retrieves passages on-demand, and generates and reflects on retrieved passages and its own generations using special tokens, called reflection tokens. Generating reflection tokens makes the LM controllable during the inference phase, enabling it to tailor its behavior to diverse task requirements. Experiments show that Self-RAG (7B and 13B parameters) significantly outperforms state-of-the-art LLMs and retrieval-augmented models on a diverse set of tasks. Specifically, Self-RAG outperforms ChatGPT and retrieval-augmented Llama2-chat on Open-domain QA, reasoning and fact verification tasks, and it shows significant gains in improving factuality and citation accuracy for long-form generations relative to these models.

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2310.11511")
get_code_for_paper("2310.11511")
have("2310.11511")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2310.11511.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2310.11511.svg)](https://syntology.ai/paper/2310.11511)

Connect an agent — have() is free.