SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2402.13720 · EMNLP · 2024

Ouroboros: Generating Longer Drafts Phrase by Phrase for Faster Speculative Decoding

Maosong Sun, Zhiyuan Liu, Xu Han, Chaojun Xiao, Wang Xu, Weilin Zhao, Yuxiang Huang, Yewei Fang, Xinrong Zhang, Kaihuo Zhang

arXiv · PDF · Open in the Atlas

Code that ran

6 of 11 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (3 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 3 have no contract verdict; 3 failures of our instrument; 5 no recorded run); 1 of them was also run on the host, not in the jail, by the peer-agreement lane that set its level, measured 2026-11-24; 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/2402.13720.json · badge: /api/ran/2402.13720.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
thunlp/ouroboros canonical (classifier label)
classifier basis: census
3 ran · 3 no recorded run
thunlp/Ouroboros community
Papers with Code archive
3 ran · 2 no recorded run
FunctionStatusWhere it lives
repeat_kv Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
thunlp/ouroboros/ouroboros/models/modeling_llama.py
code served (permissive licence) · get_code("30d7eec482ebf6b1")
How it ran

Ran in Syntology's jail on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned Tensor, ndim 4, dtype family float, shape (2, 6, 5, 4) as a later run recorded it. The image it ran in was not recorded. The comparison behind this sample's level is a different run: the peer-agreement lane ran it again on the host, not in the jail (report dated 2026-09-04T23:09:20Z). 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

torch.manual_seed(0)

# Create a tensor with shape (batch, num_key_value_heads, seqlen, head_dim)
# Using distinct sizes: batch=2, num_key_value_heads=3, seqlen=5, head_dim=4
hidden_states = torch.randn(2, 3, 5, 4)

# n_rep is the repetition factor
n_rep = 2

ARGS = {
    "hidden_states": hidden_states,
    "n_rep": n_rep,
}
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 Tensor, ndim 4, dtype family float, shape (2, 6, 5, 4) — shape (2, 6, 5, 4) 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
CacheEngine Ran
ran on a synthesized input · constructed an object; no result was computed
thunlp/Ouroboros/ouroboros/ouroboros.py
code served (permissive licence) · get_code("6a1b1dc5e77396d7")
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, CacheEngine: 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 numpy as np

torch.manual_seed(0)

# CacheEngine constructor takes LEVEL and GUESS_SET_SIZE
LEVEL = 3
GUESS_SET_SIZE = 5

ARGS = {
    "LEVEL": LEVEL,
    "GUESS_SET_SIZE": GUESS_SET_SIZE,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type CacheEngine — 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 CacheEngine 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
KVCacheModelLade Ran
ran on a synthesized input · constructed an object; no result was computed
thunlp/Ouroboros/ouroboros/ouroboros.py
code served (permissive licence) · get_code("20e375bb284e9206")
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, KVCacheModelLade: 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 torch.nn as nn

torch.manual_seed(0)

class NGramCache:
    def __init__(self):
        self.cache = {}
    
    def has(self, token):
        return token in self.cache
    
    def get_guess_tokens(self, token):
        return self.cache.get(token, [])
    
    def add_extra_ngram(self, approx_tok, target_tok):
        pass
    
    def update_in_place(self, key_token, modified_ngrams):
        pass

class SimpleGenerationModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 8)
        self.ctx = None
    
    def lade_generate(self, inputs, max_new_tokens, continue_ctx, continue_flag, do_sample, window_size, guess_set_size, lookahead_level, ngram_cache):
        batch_size = inputs.shape[0]
        seq_len = inputs.shape[1]
        
        num_layers = 2
        num_heads = 2
        head_dim = 2
        
        past_key_values = []
        for _ in range(num_layers):
            k = torch.randn(batch_size, num_heads, seq_len, head_dim)
            v = torch.randn(batch_size, num_heads, seq_len, head_dim)
            past_key_values.append((k, v))
        
        output = torch.cat([inputs, torch.randint(0, 100, (batch_size, max_new_tokens))], dim=1)
        
        self.ctx = {
            'past_key_values': past_key_values,
            'ngram_cache': ngram_cache
        }
        
        return output

model = SimpleGenerationModel()
ngram_cache = NGramCache()

ARGS = {
    'model': model,
    'window_size': 60,
    'guess_set_size': 60,
    'lookahead_level': 8,
    'topk': 3
}
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 KVCacheModelLade — 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 KVCacheModelLade 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
KVCacheModelSimpleWithGuess Ran
ran on a synthesized input · constructed an object; no result was computed
thunlp/Ouroboros/ouroboros/ouroboros.py
code served (permissive licence) · get_code("d72d77c358c2f8ad")
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, KVCacheModelSimpleWithGuess: 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 torch.nn as nn

torch.manual_seed(0)

class MockModel(nn.Module):
    """Mock model that implements forward_with_guess method."""
    
    def __init__(self, vocab_size=100, hidden_dim=4, num_layers=2, num_heads=2):
        super().__init__()
        self.embedding = nn.Embedding(vocab_size, hidden_dim)
        self.transformer_layers = nn.ModuleList([
            nn.TransformerEncoderLayer(
                d_model=hidden_dim,
                nhead=num_heads,
                dim_feedforward=8,
                batch_first=True
            )
            for _ in range(num_layers)
        ])
        self.lm_head = nn.Linear(hidden_dim, vocab_size)
    
    def forward_with_guess(self, input_ids, guess_len=None, guess_size=None, 
                          position_ids=None, past_key_values=None, use_cache=False):
        """
        Mock forward pass that returns logits and past_key_values.
        
        Args:
            input_ids: tensor of shape (batch, seq_len)
            guess_len: length of guesses
            guess_size: size of guesses
            position_ids: position indices
            past_key_values: cached key-values from previous forward
            use_cache: whether to use caching
        """
        batch_size = input_ids.shape[0]
        seq_len = input_ids.shape[1]
        
        # Embed input
        x = self.embedding(input_ids)
        
        # Pass through transformer layers
        for layer in self.transformer_layers:
            x = layer(x)
        
        # Generate logits
        logits = self.lm_head(x)  # shape: (batch, seq_len, vocab_size)
        
        # Create mock past_key_values (list of tuples of k,v tensors)
        # Each layer produces a (k, v) tuple with shapes (batch, num_heads, seq_len, head_dim)
        num_layers = len(self.transformer_layers)
        head_dim = 4 // 2  # hidden_dim / num_heads
        past_key_values = []
        for _ in range(num_layers):
            k = torch.randn(batch_size, 2, seq_len, head_dim)
            v = torch.randn(batch_size, 2, seq_len, head_dim)
            past_key_values.append((k, v))
        
        class OutputWrapper:
            def __init__(self, logits, past_key_values):
                self.logits = logits
                self.past_key_values = past_key_values
        
        return OutputWrapper(logits, past_key_values)


# Create the mock model
model = MockModel(vocab_size=100, hidden_dim=4, num_layers=2, num_heads=2)

# Define ARGS dictionary with all parameters for KVCacheModelSimpleWithGuess
ARGS = {
    'model': model,
    'lookahead_level': 8,
    'debug': False
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
IPython, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type KVCacheModelSimpleWithGuess — 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 KVCacheModelSimpleWithGuess 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
apply_rotary_pos_emb Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
thunlp/ouroboros/ouroboros/models/modeling_llama.py
code served (permissive licence) · get_code("f725bc2d76076485")
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, ndim 5, 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 torch

torch.manual_seed(0)

# Create small tensors for q and k
# Shape: (batch_size=2, seq_len=3, hidden_dim=4)
q = torch.randn(2, 3, 4)
k = torch.randn(2, 3, 4)

# Create cos and sin tensors
# The function squeezes dimensions 1 and 0, then indexes by position_ids
# So we need shape that allows this: (1, 1, seq_len, hidden_dim)
cos = torch.randn(1, 1, 5, 4)
sin = torch.randn(1, 1, 5, 4)

# Create position_ids
# Shape: (batch_size=2, seq_len=3)
position_ids = torch.tensor([[0, 1, 2], [1, 2, 3]])

ARGS = {
    "q": q,
    "k": k,
    "cos": cos,
    "sin": sin,
    "position_ids": position_ids,
}
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 tuple, ndim 5, dtype family float — a tuple 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
thunlp/ouroboros/ouroboros/models/modeling_llama.py
code served (permissive licence) · get_code("b99eea6376d1e212")
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 Tensor, ndim 2, dtype family float, shape (2, 4) 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

torch.manual_seed(0)

# The function rotate_half takes a single parameter 'x' which is a tensor
# It accesses x.shape[-1] to get the last dimension
# It uses indexing with [..., :] slicing notation
# It calls torch.cat() to concatenate tensors

# Create a small tensor with shape (2, 4) - batch size 2, hidden dim 4
x = torch.randn(2, 4)

ARGS = {
    "x": x
}
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 Tensor, ndim 2, dtype family float, shape (2, 4) — shape (2, 4) 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
_debug_show_kvcache Not yet run
unverified (harvested, no recorded run)
thunlp/Ouroboros/ouroboros/ouroboros.py
code served (permissive licence) · get_code("3e877f54ec1313b0")
How it ran

no invocation recorded.

j_make_causal_mask_multilevel Not yet run
unverified (harvested, no recorded run)
thunlp/ouroboros/ouroboros/models/mask_making_llama.py
code served (permissive licence) · get_code("0da5cc8e940c9ab5")
How it ran

no invocation recorded.

j_make_causal_mask_with_guess Not yet run
unverified (harvested, no recorded run)
thunlp/ouroboros/ouroboros/models/mask_making_llama.py
code served (permissive licence) · get_code("7940da8888838790")
How it ran

no invocation recorded.

ouroboros Not yet run
unverified (harvested, no recorded run)
thunlp/Ouroboros/ouroboros/ouroboros.py
code served (permissive licence) · get_code("07ad96b45bb5eb75")
How it ran

no invocation recorded.

ouroboros_specbench Not yet run
unverified (harvested, no recorded run)
thunlp/ouroboros/benchmark/test_specbench/model/ouroboros/ouroboros.py
code served (permissive licence) · get_code("c27ae46e25d93b32")
How it ran

no invocation recorded.

Also present in other papers' code

Of 11 samples lifted from this paper's linked repositories, 11 carry a function identity and 0 do not. Of the 11 distinct functions with an identity, 4 are also present in other papers whose code we hold (4 with at least one paper dated earlier, 3 the same month, 3 later) and 7 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
68 dated earlier, 25 the same month, 258 later, 6 same year, order not determinable, 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
repeat_kv 243 other papers
33 dated earlier, 19 the same month, 187 later, 2 same year, order not determinable, 2 undated · 22 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
2305.17888 (2023-05)
LLM-QAT: Data-Free Quantization Aware Training for Large Language Models
and 240 more not named here
apply_rotary_pos_emb 83 other papers
19 dated earlier, 11 the same month, 51 later, 2 same year, order not determinable · 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
_debug_show_kvcache
brick of this paper's assembly: helper
1 other paper
1 dated earlier · 1 only as an assembly brick
2211.17192 (2022-11)
Fast Inference from Transformers via Speculative Decoding

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

Repositories linked to this paper

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

Abstract

Speculative decoding is a widely used method that accelerates the generation process of large language models (LLMs) with no compromise in model performance. It achieves this goal by using an existing smaller model for drafting and then employing the target LLM to verify the draft in a low-cost parallel manner. Under such a drafting-verification framework, drafting efficiency has become a bottleneck in the final speedup of speculative decoding. Therefore, generating longer drafts at less cost can lead to better decoding speedup. To achieve this, we introduce Ouroboros, which can generate draft phrases to parallelize the drafting process and meanwhile lengthen drafts in a training-free manner. The experimental results on various typical text generation tasks show that Ouroboros can achieve speedups of up to 2.4× over speculative decoding and 3.9× over vanilla decoding, without fine-tuning draft and target models. The source code of Ouroboros is available at https://github.com/thunlp/Ouroboros. * indicates equal contribution. † indicates corresponding authors.

For agents

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

get_harvested_code_for_paper("2402.13720")
get_code_for_paper("2402.13720")
have("2402.13720")

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

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

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

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

Connect an agent — have() is free.