SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2602.04417 · 2026

EMA Policy Gradient: Taming Reinforcement Learning for LLMs with EMA Anchor and Top-k KL

Jimmy Ba, Lunjun Zhang

arXiv · PDF · Open in the Atlas

Code that ran

6 of 10 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; 2 honoured the contract we drafted, 0 violated it and 0 have no contract verdict; 4 failures of our instrument; 4 no recorded run), measured 2026-11-21; 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/2602.04417.json · badge: /api/ran/2602.04417.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
LunjunZhang/ema-pg canonical (classifier label)
classifier basis: census
6 ran · 4 no recorded run
FunctionStatusWhere it lives
create_huggingface_actor Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
LunjunZhang/ema-pg/search/verl/utils/model.py
code served (permissive licence) · get_code("360c671d6041ba3b")
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 MockCausalLMModel. 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
from unittest.mock import Mock, patch
from transformers import AutoConfig, PretrainedConfig

torch.manual_seed(0)

# Create a minimal mock config class
class MockPretrainedConfig(PretrainedConfig):
    model_type = "mock_model"
    
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.hidden_size = 64
        self.num_hidden_layers = 2
        self.num_attention_heads = 2
        self.intermediate_size = 128
        self.vocab_size = 1000
        self.max_position_embeddings = 512

# Create a minimal mock model
class MockCausalLMModel(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.config = config
        self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
        self.lm_head = nn.Linear(config.hidden_size, config.vocab_size)
    
    def forward(self, input_ids):
        x = self.embeddings(input_ids)
        return self.lm_head(x)

# Mock AutoConfig.from_pretrained to return our mock config
def mock_from_pretrained(model_name, trust_remote_code=False):
    return MockPretrainedConfig()

# Mock AutoModelForCausalLM.from_config to return our mock model
def mock_from_config(config, **kwargs):
    return MockCausalLMModel(config)

# Set up patches
import transformers
original_from_pretrained = transformers.AutoConfig.from_pretrained
original_from_config = transformers.AutoModelForCausalLM.from_config

transformers.AutoConfig.from_pretrained = staticmethod(mock_from_pretrained)
transformers.AutoModelForCausalLM.from_config = staticmethod(mock_from_config)

ARGS = {
    "model_name": "gpt2",
    "override_config_kwargs": {"hidden_size": 128, "num_hidden_layers": 4},
    "automodel_kwargs": {"trust_remote_code": False}
}
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 MockCausalLMModel — a MockCausalLMModel output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a MockCausalLMModel 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_image Ran
ran, honoured the contract we drafted
LunjunZhang/ema-pg/math/rllm/misc.py
code served (permissive licence) · get_code("8e21ff6e15adbc8f")
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 Image. 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 numpy as np
import tempfile
import os
from PIL import Image

# Create a temporary image file
temp_dir = tempfile.mkdtemp()
image_path = os.path.join(temp_dir, "test_image.png")

# Create a small RGB image and save it
img_array = np.random.randint(0, 256, (4, 3, 3), dtype=np.uint8)
img = Image.fromarray(img_array, mode='RGB')
img.save(image_path)

ARGS = {
    'image_path': image_path
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
PIL, numpy — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Image — a Image output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a Image output the recorded ndim 3 and dtype family int 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_query Ran
ran; our contract draft was wrong, not the code
LunjunZhang/ema-pg/search/infer.py
code served (permissive licence) · get_code("8709b4b7236b87d7")
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 str. 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 re

def get_query(text):
    import re
    pattern = re.compile('<search>(.*?)</search>', re.DOTALL)
    matches = pattern.findall(text)
    if matches:
        return matches[-1]
    else:
        return None

# Test case 1: text with search tags
text_with_search = "Some prefix <search>query content here</search> some suffix"

ARGS = {
    "text": text_with_search
}
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 str — a str output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a str 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
merge_dicts Ran
ran; our contract draft was wrong, not the code
LunjunZhang/ema-pg/math/rllm/misc.py
code served (permissive licence) · get_code("b7aec73d6258eba0")
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 numpy as np

torch.manual_seed(0)

# Construct a simple list of dictionaries to merge
dict_list = [
    {"a": 1, "b": 2},
    {"a": 3, "c": 4},
    {"b": 5, "c": 6}
]

ARGS = {
    "dict_list": dict_list
}
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 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
pad_from_left Ran
ran, honoured the contract we drafted
LunjunZhang/ema-pg/math/rllm/misc.py
code served (permissive licence) · get_code("15c74c1c2cf76cf7")
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 2, dtype family int; 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 random

def pad_from_left(input_id_list, pad_token_id):
    max_len = max([len(input_id) for input_id in input_id_list])
    if len(input_id_list) == 1:
        max_len += random.randint(1, 100)
    padded_input_ids = [[pad_token_id] * (max_len - len(input_id)) + input_id for input_id in input_id_list]
    return padded_input_ids

# Setup code
ARGS = {
    "input_id_list": [
        [101, 2054, 2003],
        [101, 2054],
        [101, 2054, 2003, 2067]
    ],
    "pad_token_id": 0
}
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 2, dtype family int — 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
unpad_dataproto Ran
ran; our contract draft was wrong, not the code
LunjunZhang/ema-pg/search/verl/protocol.py
code served (permissive licence) · get_code("25f0ea3f460f6ce1")
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 DataProto. 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)

class DataProto:
    """Stand-in class for DataProto that supports slicing."""
    def __init__(self, data):
        self.data = data
    
    def __getitem__(self, key):
        """Support slicing to return a new DataProto with sliced data."""
        sliced_data = self.data[key]
        return DataProto(sliced_data)
    
    def __repr__(self):
        return f"DataProto({self.data})"

# Create a small DataProto instance with some data
data_tensor = torch.randn(2, 4)
data_proto = DataProto(data_tensor)

ARGS = {
    "data": data_proto,
    "pad_size": 0
}
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 DataProto — a DataProto output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a DataProto 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_huggingface_actor_config Not yet run
unverified (harvested, no recorded run)
LunjunZhang/ema-pg/search/verl/utils/model.py
code served (permissive licence) · get_code("19472d4343d0a082")
How it ran

no invocation recorded.

get_weight_loader Not yet run
unverified (harvested, no recorded run)
LunjunZhang/ema-pg/search/verl/models/weight_loader_registry.py
code served (permissive licence) · get_code("919cf310ad4c189a")
How it ran

no invocation recorded.

search Not yet run
unverified (harvested, no recorded run)
LunjunZhang/ema-pg/search/infer.py
code served (permissive licence) · get_code("b0919972b9febb29")
How it ran

no invocation recorded.

squeeze Not yet run
unverified (harvested, no recorded run)
LunjunZhang/ema-pg/search/verl/utils/model.py
code served (permissive licence) · get_code("3b15e2ac7497c441")
How it ran

no invocation recorded.

Also present in other papers' code

Of 10 samples lifted from this paper's linked repositories, 10 carry a function identity and 0 do not. Of the 10 distinct functions with an identity, 10 are also present in other papers whose code we hold (7 with at least one paper dated earlier, 8 the same month, 5 later) and 0 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
unpad_dataproto 89 other papers
36 dated earlier, 13 the same month, 37 later, 3 undated
2409.19256 (2024-09)
HybridFlow: A Flexible and Efficient RLHF Framework
2410.21236 (2024-10)
Flaming-hot Initiation with Regular Execution Sampling for Large Language Models
2025.findings-emnlp.1015 (2025 (year only))
MT-R1-Zero: Advancing LLM-based Machine Translation via R1-Zero-like Reinforcement Learning
and 86 more not named here
squeeze 82 other papers
36 dated earlier, 12 the same month, 31 later, 3 undated
2409.19256 (2024-09)
HybridFlow: A Flexible and Efficient RLHF Framework
2410.21236 (2024-10)
Flaming-hot Initiation with Regular Execution Sampling for Large Language Models
2025.findings-emnlp.1015 (2025 (year only))
MT-R1-Zero: Advancing LLM-based Machine Translation via R1-Zero-like Reinforcement Learning
and 79 more not named here
get_huggingface_actor_config 53 other papers
34 dated earlier, 5 the same month, 12 later, 2 undated
2409.19256 (2024-09)
HybridFlow: A Flexible and Efficient RLHF Framework
2410.21236 (2024-10)
Flaming-hot Initiation with Regular Execution Sampling for Large Language Models
2025.findings-emnlp.1015 (2025 (year only))
MT-R1-Zero: Advancing LLM-based Machine Translation via R1-Zero-like Reinforcement Learning
and 50 more not named here
get_weight_loader 20 other papers
15 dated earlier, 2 the same month, 2 later, 1 undated
2410.21236 (2024-10)
Flaming-hot Initiation with Regular Execution Sampling for Large Language Models
2025.findings-emnlp.1015 (2025 (year only))
MT-R1-Zero: Advancing LLM-based Machine Translation via R1-Zero-like Reinforcement Learning
2502.14768 (2025-02)
Logic-RL: Unleashing LLM Reasoning with Rule-Based Reinforcement Learning
and 17 more not named here
create_huggingface_actor 17 other papers
13 dated earlier, 1 the same month, 2 later, 1 undated
2025.findings-emnlp.1015 (2025 (year only))
MT-R1-Zero: Advancing LLM-based Machine Translation via R1-Zero-like Reinforcement Learning
2502.14768 (2025-02)
Logic-RL: Unleashing LLM Reasoning with Rule-Based Reinforcement Learning
2503.10460 (2025-03)
Light-R1: Curriculum SFT, DPO and RL for Long COT from Scratch and Beyond
and 14 more not named here
get_query 5 other papers
5 dated earlier
2503.09516 (2025-03)
Search-R1: Training LLMs to Reason and Leverage Search Engines with Reinforcement Learning
2505.04588 (2025-05)
ZeroSearch: Incentivize the Search Capability of LLMs without Searching
2505.07596 (2025-05)
Reinforced Internal-External Knowledge Synergistic Reasoning for Efficient Adaptive Search Agent
and 2 more not named here
get_image 1 other paper
1 the same month
2602.03719 (2026-02)
BranPO: Scalable Contrastive Branch Sampling for Long-Horizon Agentic Reinforcement Learning
merge_dicts 1 other paper
1 the same month
2602.03719 (2026-02)
BranPO: Scalable Contrastive Branch Sampling for Long-Horizon Agentic Reinforcement Learning
pad_from_left 1 other paper
1 the same month
2602.03719 (2026-02)
BranPO: Scalable Contrastive Branch Sampling for Long-Horizon Agentic Reinforcement Learning
search 1 other paper
1 dated earlier
2601.14896 (2026-01)
Language-Coupled Reinforcement Learning for Multilingual Retrieval-Augmented Generation

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

Repositories linked to this paper

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

Abstract

Reinforcement Learning (RL) has enabled Large Language Models (LLMs) to acquire increasingly complex reasoning and agentic behaviors. In this work, we propose two simple techniques to improve policy gradient algorithms for LLMs. First, we replace the fixed anchor policy during RL with an Exponential Moving Average (EMA), similar to a target network in deep Q-learning. Second, we introduce Top-k KL estimator, which allows for flexible interpolation between exact KL and sampled KL. We derive the stability conditions for using EMA anchor; moreover, we show that our Top-k KL estimator yields both unbiased KL values and unbiased gradients at any k, while bringing the benefits of exact KL. When combined with GRPO, the two techniques (EMA-PG) lead to a significant performance boost. On math reasoning, it allows R1-distilled Qwen-1.5B to reach 53.9% on OlympiadBench compared to 50.8% by GRPO. On agentic RL domains, with Qwen-3B base, EMA-PG improves GRPO by an average of 33.3% across 7 datasets of Q&A with search engines, including 29.7% → 44.1% on HotpotQA, 27.4% → 40.1% on 2WikiMultiHopQA. Overall, we show that EMA-PG is a simple, principled, and powerful approach to scaling RL for LLMs. Code: github.com/LunjunZhang/ema-pg.

For agents

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

get_harvested_code_for_paper("2602.04417")
get_code_for_paper("2602.04417")
have("2602.04417")

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

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

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

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

Connect an agent — have() is free.