SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2207.05987 · ICLR · 2023

DocPrompting: GENERATING CODE BY RETRIEVING THE DOCS

Graham Neubig, Uri Alon, Frank Xu, Shuyan Zhou, Zhiruo Wang, Zhengbao Jiang

arXiv · PDF · Open in the Atlas

Code that ran

4 of 9 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (1 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 2 have no contract verdict; 2 failures of our instrument; 5 no recorded run), measured 2026-11-22; 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/2207.05987.json · badge: /api/ran/2207.05987.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
shuyanzhou/docprompting canonical (classifier label)
classifier basis: classifier_2025
2 ran · 5 no recorded run
shuyanzhou/doccoder marked official in Papers with Code
Papers with Code archive
2 ran · 0 no recorded run
FunctionStatusWhere it lives
Retriever Ran
ran on a synthesized input
shuyanzhou/doccoder/generator/fid/src/model.py
code served (permissive licence) · get_code("e6e89b2e0804678e")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned tuple. 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 torch import nn
import numpy as np

# Minimal config for testing
class MinimalBertConfig(transformers.BertConfig):
    def __init__(self):
        super().__init__(
            vocab_size=1000,
            hidden_size=4,
            num_hidden_layers=2,
            num_attention_heads=2,
            intermediate_size=8,
            hidden_act="gelu",
            hidden_dropout_prob=0.1,
            attention_probs_dropout_prob=0.1,
            max_position_embeddings=512,
            type_vocab_size=2,
            initializer_range=0.02,
            layer_norm_eps=1e-12,
        )

class RetrieverConfig(transformers.BertConfig):
    def __init__(self, indexing_dimension=768, apply_question_mask=False, apply_passage_mask=False, extract_cls=False, passage_maxlength=200, question_maxlength=40, projection=True, **kwargs):
        super().__init__(**kwargs)
        self.indexing_dimension = indexing_dimension
        self.apply_question_mask = apply_question_mask
        self.apply_passage_mask = apply_passage_mask
        self.extract_cls = extract_cls
        self.passage_maxlength = passage_maxlength
        self.question_maxlength = question_maxlength
        self.projection = projection

class Retriever(transformers.PreTrainedModel):
    config_class = RetrieverConfig
    base_model_prefix = 'retriever'

    def __init__(self, config, initialize_wBERT=False):
        super().__init__(config)
        assert config.projection or config.indexing_dimension == 768, 'If no projection then indexing dimension must be equal to 768'
        self.config = config
        if initialize_wBERT:
            self.model = transformers.BertModel.from_pretrained('bert-base-uncased')
        else:
            self.model = transformers.BertModel(config)
        if self.config.projection:
            self.proj = nn.Linear(self.model.config.hidden_size, self.config.indexing_dimension)
            self.norm = nn.LayerNorm(self.config.indexing_dimension)
        self.loss_fct = torch.nn.KLDivLoss()

    def forward(self, question_ids, question_mask, passage_ids, passage_mask, gold_score=None):
        question_output = self.embed_text(text_ids=question_ids, text_mask=question_mask, apply_mask=self.config.apply_question_mask, extract_cls=self.config.extract_cls)
        bsz, n_passages, plen = passage_ids.size()
        passage_ids = passage_ids.view(bsz * n_passages, plen)
        passage_mask = passage_mask.view(bsz * n_passages, plen)
        passage_output = self.embed_text(text_ids=passage_ids, text_mask=passage_mask, apply_mask=self.config.apply_passage_mask, extract_cls=self.config.extract_cls)
        score = torch.einsum('bd,bid->bi', question_output, passage_output.view(bsz, n_passages, -1))
        score = score / np.sqrt(question_output.size(-1))
        if gold_score is not None:
            loss = self.kldivloss(score, gold_score)
        else:
            loss = None
        return (question_output, passage_output, score, loss)

    def embed_text(self, text_ids, text_mask, apply_mask=False, extract_cls=False):
        text_output = self.model(input_ids=text_ids, attention_mask=text_mask if apply_mask else None)
        if type(text_output) is not tuple:
            text_output.to_tuple()
        text_output = text_output[0]
        if self.config.projection:
            text_output = self.proj(text_output)
            text_output = self.norm(text_output)
        if extract_cls:
            text_output = text_output[:, 0]
        elif apply_mask:
            text_output = text_output.masked_fill(~text_mask[:, :, None], 0.0)
            text_output = torch.sum(text_output, dim=1) / torch.sum(text_mask, dim=1)[:, None]
        else:
            text_output = torch.mean(text_output, dim=1)
        return text_output

    def kldivloss(self, score, gold_score):
        gold_score = torch.softmax(gold_score, dim=-1)
        score = torch.nn.functional.log_softmax(score, dim=-1)
        return self.loss_fct(score, gold_score)


# Create minimal config
bert_config = MinimalBertConfig()
config = RetrieverConfig(
    indexing_dimension=3,
    apply_question_mask=False,
    apply_passage_mask=False,
    extract_cls=False,
    passage_maxlength=10,
    question_maxlength=8,
    projection=True,
    vocab_size=bert_config.vocab_size,
    hidden_size=bert_config.hidden_size,
    num_hidden_layers=bert_config.num_hidden_layers,
    num_attention_heads=bert_config.num_attention_heads,
    intermediate_size=bert_config.intermediate_size,
)

INIT_ARGS = {
    'config': config,
    'initialize_wBERT': False,
}

ARGS = {
    'question_ids': torch.randint(0, 100, (2, 8)),
    'question_mask': torch.ones(2, 8, dtype=torch.long),
    'passage_ids': torch.randint(0, 100, (2, 5, 10)),
    'passage_mask': torch.ones(2, 5, 10, dtype=torch.long),
    'gold_score': torch.randn(2, 5),
}
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
numpy, torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple — a tuple output has no array shape of its own; none is 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: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
RetrieverConfig Ran
ran on a synthesized input · constructed an object; no result was computed
shuyanzhou/doccoder/generator/fid/src/model.py
code served (permissive licence) · get_code("951ed5b9657b55ce")
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 an instance of its own class, RetrieverConfig: the run constructed the object and did not call it, so no result was computed. 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

torch.manual_seed(0)

ARGS = {
    'indexing_dimension': 768,
    'apply_question_mask': False,
    'apply_passage_mask': False,
    'extract_cls': False,
    'passage_maxlength': 200,
    'question_maxlength': 40,
    'projection': True,
}
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 RetrieverConfig — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a RetrieverConfig 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
config Ran
ran; our contract draft was wrong, not the code
shuyanzhou/docprompting/retriever/simcse/run_inference.py
code served (permissive licence) · get_code("508a4a6a64754c3c")
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 Namespace. 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 argparse
import shlex

torch.manual_seed(0)

ARGS = {
    'in_program_call': '--model_name bert-base-uncased --batch_size 32 --source_file data/conala/conala_nl.txt --target_file data/conala/python_manual_firstpara.txt --source_embed_save_file data/conala/.tmp/src_embedding --target_embed_save_file data/conala/.tmp/tgt_embedding --save_file [REPLACE]data/conala/simcse.[MODEL].[SOURCE].[TARGET].[POOLER].t[TOPK].json --top_k 100 --pooler cls --log_level verbose --nl_cm_folder data/conala/nl.cm --sim_func cls_distance.cosine --num_layers 12'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Namespace — a Namespace output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a Namespace 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
get_bert_embedding Ran
ran; our contract draft was wrong, not the code
shuyanzhou/docprompting/retriever/simcse/model.py
code served (permissive licence) · get_code("37fe359be5cffce7")
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 tuple. The image it ran in was not recorded. The code mentions cuda, and the harness aliases cuda to the CPU for every sample; whether this run needed that is 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 torch.nn as nn
from transformers import AutoTokenizer

torch.manual_seed(0)

# Create a minimal BERT-like model that satisfies the function's usage
class MinimalBertModel(nn.Module):
    def __init__(self, hidden_size=4, num_layers=2):
        super().__init__()
        self.hidden_size = hidden_size
        self.num_layers = num_layers
        self.embedding = nn.Embedding(100, hidden_size)
        self.linear = nn.Linear(hidden_size, hidden_size)
    
    def forward(self, input_ids, attention_mask=None, output_hidden_states=False):
        # input_ids shape: (batch_size, seq_len)
        embeddings = self.embedding(input_ids)  # (batch_size, seq_len, hidden_size)
        output = self.linear(embeddings)  # (batch_size, seq_len, hidden_size)
        
        if output_hidden_states:
            # Return tuple where last element is list of hidden states
            hidden_states = [embeddings] * self.num_layers + [output]
            return (output, None, hidden_states)
        else:
            # Return tuple where first element is the output
            return (output, None)

# Create a minimal tokenizer stand-in
class MinimalTokenizer:
    def __init__(self):
        self.pad_token_id = 0
        self.model_max_length = 512
    
    def encode(self, sent, add_special_tokens=True, add_prefix_space=False, max_length=512, truncation=False):
        # Simple mock: return a list of token ids
        tokens = [1, 2, 3] + [i % 98 + 1 for i in range(len(sent.split()))]
        if truncation and len(tokens) > max_length:
            tokens = tokens[:max_length]
        return tokens
    
    def build_inputs_with_special_tokens(self, tokens):
        return [101] + tokens + [102]

# Create model, tokenizer, and idf_dict
model = MinimalBertModel(hidden_size=4, num_layers=2)
tokenizer = MinimalTokenizer()

# Create idf_dict mapping token ids to idf scores
idf_dict = {i: 0.5 + (i % 10) * 0.1 for i in range(100)}

# Create sample sentences
all_sens = ["hello world", "this is a test"]

ARGS = {
    "all_sens": all_sens,
    "model": model,
    "tokenizer": tokenizer,
    "idf_dict": idf_dict,
    "batch_size": 2,
    "device": "cpu",
    "all_layers": False
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
distutils, torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple — a tuple output has no array shape of its own; none is 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
RetrievalModel Not yet run
unverified (harvested, no recorded run)
shuyanzhou/docprompting/retriever/simcse/model.py
code served (permissive licence) · get_code("19c938f795d433a5")
How it ran

no invocation recorded.

bert_cos_score_idf Not yet run
unverified (harvested, no recorded run)
shuyanzhou/docprompting/retriever/simcse/model.py
code served (permissive licence) · get_code("9c210e01ad10a85d")
How it ran

no invocation recorded.

collate_idf Not yet run
unverified (harvested, no recorded run)
shuyanzhou/docprompting/retriever/simcse/model.py
code served (permissive licence) · get_code("fade9d8bfe4dbc38")
How it ran

no invocation recorded.

get_tokenizer Not yet run
unverified (harvested, no recorded run)
shuyanzhou/docprompting/retriever/simcse/model.py
code served (permissive licence) · get_code("38d2231884f32e2e")
How it ran

no invocation recorded.

greedy_cos_idf_for_train Not yet run
unverified (harvested, no recorded run)
shuyanzhou/docprompting/retriever/simcse/model.py
code served (permissive licence) · get_code("2c7a8491c88c3808")
How it ran

no invocation recorded.

Also present in other papers' code

Of 9 samples lifted from this paper's linked repositories, 9 carry a function identity and 0 do not. Of the 9 distinct functions with an identity, 3 are also present in other papers whose code we hold (3 with at least one paper dated earlier, 0 the same month, 0 later) and 6 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
bert_cos_score_idf
brick of this paper's assembly: helper
1 other paper
1 dated earlier
1904.09675 (2019-04)
BERTScore: Evaluating Text Generation with BERT
collate_idf
brick of this paper's assembly: helper
1 other paper
1 dated earlier
1904.09675 (2019-04)
BERTScore: Evaluating Text Generation with BERT
get_bert_embedding
brick of this paper's assembly: helper
1 other paper
1 dated earlier
1904.09675 (2019-04)
BERTScore: Evaluating Text Generation with BERT

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-22.

Repositories linked to this paper

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

Abstract

Publicly available source-code libraries are continuously growing and changing. This makes it impossible for models of code to keep current with all available APIs by simply training these models on existing code repositories. Thus, existing models inherently cannot generalize to using unseen functions and libraries, because these would never appear in their training data. In contrast, when human programmers use functions and libraries for the first time, they frequently refer to textual resources such as code manuals and documentation, to explore and understand the available functionality. Inspired by this observation, we introduce DocPrompting: a natural-language-to-code generation approach that explicitly leverages code documentation by (1) retrieving the relevant documentation pieces given a natural language (NL) intent, and (2) generating code based on the NL intent and the retrieved documentation. DocPrompting is general: it can be applied to any programming language, and is agnostic to the underlying neural model. We demonstrate that DocPrompting consistently improves NL-to-code models: DocPrompting improves strong base models such as CodeT5 by 2.85% in pass@1 (52% relative gain) and 4.39% in pass@10 (30% relative gain) in execution-based evaluation on the popular Python CoNaLa benchmark; on a new Bash dataset tldr, DocPrompting improves CodeT5 and GPT-Neo-1.3B by up to absolute 6.9% exact match. 1

For agents

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

get_harvested_code_for_paper("2207.05987")
get_code_for_paper("2207.05987")
have("2207.05987")

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

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

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

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

Connect an agent — have() is free.