SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2606.10228 · 2026

SHAPO: Sharpness-Aware Policy Optimization for Safe Exploration

Liam Paull, Kaustubh Mani, Yann Pequignot, Vincent Lawzero

arXiv · PDF · Open in the Atlas

Code that ran

7 of 13 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 2 have no contract verdict; 3 failures of our instrument; 6 no recorded run), measured 2026-11-24; 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/2606.10228.json · badge: /api/ran/2606.10228.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
montrealrobotics/shapo community
Papers with Code archive
7 ran · 6 no recorded run
FunctionStatusWhere it lives
Actor Ran
ran on a synthesized input
montrealrobotics/shapo/safepo/single_agent/shapo.py
code served (permissive licence) · get_code("e8e31987c5d58926")
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 Normal. 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
import torch.nn as nn
from torch.distributions import Normal

def build_mlp_network(sizes, use_layer_norm=False):
    """
    Build a multi-layer perceptron (MLP) neural network.

    This function constructs an MLP network with the specified layer sizes and activation functions.

    Args:
        sizes (list of int): List of integers representing the sizes of each layer in the network.
        use_layer_norm (bool): Whether to use layer normalization after each linear layer.

    Returns:
        nn.Sequential: An instance of PyTorch's Sequential module representing the constructed MLP.
    """
    layers = list()
    for j in range(len(sizes) - 1):
        act = nn.Tanh if j < len(sizes) - 2 else nn.Identity
        affine_layer = nn.Linear(sizes[j], sizes[j + 1])
        nn.init.kaiming_uniform_(affine_layer.weight, a=np.sqrt(5))
        layers += [affine_layer]
        if use_layer_norm and j < len(sizes) - 2:
            layers += [nn.LayerNorm(sizes[j + 1])]
        layers += [act()]
    return nn.Sequential(*layers)

class Actor(nn.Module):
    """
    Actor network for policy-based reinforcement learning.

    This class represents an actor network that outputs a distribution over actions given observations.

    Args:
        obs_dim (int): Dimensionality of the observation space.
        act_dim (int): Dimensionality of the action space.
        hidden_sizes (list): List of hidden layer sizes.
        use_layer_norm (bool): Whether to use layer normalization.

    Attributes:
        mean (nn.Sequential): MLP network representing the mean of the action distribution.
        log_std (nn.Parameter): Learnable parameter representing the log standard deviation of the action distribution.

    Example:
        obs_dim = 10
        act_dim = 2
        actor = Actor(obs_dim, act_dim)
        observation = torch.randn(1, obs_dim)
        action_distribution = actor(observation)
    """

    def __init__(self, obs_dim: int, act_dim: int, hidden_sizes: list=[64, 64], use_layer_norm=False):
        super().__init__()
        self.mean = build_mlp_network([obs_dim] + hidden_sizes + [act_dim], use_layer_norm=use_layer_norm)
        self.log_std = nn.Parameter(torch.zeros(act_dim), requires_grad=True)

    def forward(self, obs: torch.Tensor):
        mean = self.mean(obs)
        std = torch.exp(self.log_std)
        return Normal(mean, std)


INIT_ARGS = {
    'obs_dim': 4,
    'act_dim': 3,
    'hidden_sizes': [8, 8],
    'use_layer_norm': False
}

ARGS = {
    'obs': torch.randn(2, 4)
}

if __name__ == '__main__':
    actor = Actor(**INIT_ARGS)
    distribution = actor(**ARGS)
    print(f"Distribution mean shape: {distribution.mean.shape}")
    print(f"Distribution stddev shape: {distribution.stddev.shape}")
    sample = distribution.rsample()
    print(f"Sample shape: {sample.shape}")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Normal — a Normal output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a Normal 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: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
VCritic Ran
ran on a synthesized input
montrealrobotics/shapo/safepo/single_agent/shapo.py
code served (permissive licence) · get_code("7af25f4312ec1e6c")
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 Tensor, ndim 1, dtype family float, shape (2,) 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
import torch.nn as nn

def build_mlp_network(sizes, use_layer_norm=False):
    """
    Build a multi-layer perceptron (MLP) neural network.

    This function constructs an MLP network with the specified layer sizes and activation functions.

    Args:
        sizes (list of int): List of integers representing the sizes of each layer in the network.
        use_layer_norm (bool): Whether to use layer normalization after each linear layer.

    Returns:
        nn.Sequential: An instance of PyTorch's Sequential module representing the constructed MLP.
    """
    layers = list()
    for j in range(len(sizes) - 1):
        act = nn.Tanh if j < len(sizes) - 2 else nn.Identity
        affine_layer = nn.Linear(sizes[j], sizes[j + 1])
        nn.init.kaiming_uniform_(affine_layer.weight, a=np.sqrt(5))
        layers += [affine_layer]
        if use_layer_norm and j < len(sizes) - 2:
            layers += [nn.LayerNorm(sizes[j + 1])]
        layers += [act()]
    return nn.Sequential(*layers)

class VCritic(nn.Module):
    """
    Critic network for value-based reinforcement learning.

    This class represents a critic network that estimates the value function for input observations.

    Args:
        obs_dim (int): Dimensionality of the observation space.
        hidden_sizes (list): List of hidden layer sizes.
        use_layer_norm (bool): Whether to use layer normalization.

    Attributes:
        critic (nn.Sequential): MLP network representing the critic function.

    Example:
        obs_dim = 10
        critic = VCritic(obs_dim)
        observation = torch.randn(1, obs_dim)
        value_estimate = critic(observation)
    """

    def __init__(self, obs_dim, hidden_sizes: list=[64, 64], use_layer_norm=False):
        super().__init__()
        self.critic = build_mlp_network([obs_dim] + hidden_sizes + [1], use_layer_norm=use_layer_norm)

    def forward(self, obs):
        return torch.squeeze(self.critic(obs), -1)


INIT_ARGS = {
    'obs_dim': 4,
    'hidden_sizes': [8, 16],
    'use_layer_norm': False
}

ARGS = {
    'obs': torch.randn(2, 4)
}
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 1, dtype family float, shape (2,) — shape (2,) 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: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
build_mlp_network Ran
ran; our contract draft was wrong, not the code
montrealrobotics/shapo/safepo/single_agent/shapo.py
code served (permissive licence) · get_code("0b4c507ca061e879")
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 Sequential. 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
import numpy as np

torch.manual_seed(0)

ARGS = {
    "sizes": [4, 8, 16, 2],
    "use_layer_norm": True,
}
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 Sequential — a Sequential output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a Sequential output the recorded ndim 1 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
compute_kl_constrained_perturbation Ran
ran; our contract draft was wrong, not the code
montrealrobotics/shapo/safepo/single_agent/shapo.py
code served (permissive licence) · get_code("41bcbe47eb145d13")
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 tuple, 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 torch
import torch.nn as nn
import numpy as np

torch.manual_seed(0)

# Define a minimal policy network with an actor that outputs a distribution
class MinimalActor(nn.Module):
    def __init__(self, obs_dim, action_dim):
        super().__init__()
        self.fc = nn.Linear(obs_dim, action_dim)
        self.log_std = nn.Parameter(torch.zeros(action_dim))
    
    def forward(self, obs):
        # Return a Normal distribution
        mean = self.fc(obs)
        std = torch.exp(self.log_std)
        return torch.distributions.Normal(mean, std)

class MinimalPolicy(nn.Module):
    def __init__(self):
        super().__init__()
        self.actor = MinimalActor(obs_dim=4, action_dim=3)
    
    def forward(self, obs):
        return self.actor(obs)

# Create policy instance
policy = MinimalPolicy()

# Create small batch of data
obs = torch.randn(2, 4)  # batch_size=2, obs_dim=4
actions = torch.randn(2, 3)  # batch_size=2, action_dim=3
data = {'obs': obs, 'actions': actions}

# Create step direction (perturbation direction in parameter space)
# Get total number of parameters
total_params = sum(p.numel() for p in policy.actor.parameters() if p.requires_grad)
step_direction = torch.randn(total_params)

# Define parameters for KL constraint function
target_kl = 0.5
max_search_steps = 10

ARGS = {
    'policy': policy,
    'data': data,
    'step_direction': step_direction,
    'target_kl': target_kl,
    'max_search_steps': max_search_steps
}
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 tuple, ndim 1, 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
get_flat_gradients_from Ran
ran, honoured the contract we drafted
montrealrobotics/shapo/safepo/single_agent/shapo.py
code served (permissive licence) · get_code("85e92e4bdd0a48f7")
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 1, dtype family float, shape (23,) 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 torch.nn as nn

torch.manual_seed(0)

# Create a simple model with parameters that have gradients
class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear1 = nn.Linear(4, 3)
        self.linear2 = nn.Linear(3, 2)
    
    def forward(self, x):
        x = self.linear1(x)
        x = self.linear2(x)
        return x

# Instantiate the model
model = SimpleModel()

# Create dummy input and target
x = torch.randn(2, 4)
target = torch.randn(2, 2)

# Forward pass and backward to populate gradients
output = model(x)
loss = nn.MSELoss()(output, target)
loss.backward()

# Now the model has gradients in its parameters
ARGS = {
    'model': model
}
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 1, dtype family float, shape (23,) — shape (23,) 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
get_flat_params_from Ran
ran, honoured the contract we drafted
montrealrobotics/shapo/safepo/single_agent/shapo.py
code served (permissive licence) · get_code("c4317ff2ec911b0b")
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 1, dtype family float, shape (23,) 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 torch.nn as nn

torch.manual_seed(0)

class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear1 = nn.Linear(4, 3)
        self.linear2 = nn.Linear(3, 2)
    
    def forward(self, x):
        x = self.linear1(x)
        x = self.linear2(x)
        return x

model = SimpleModel()

ARGS = {
    "model": model
}
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 1, dtype family float, shape (23,) — shape (23,) 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
log_gradient_statistics Ran
ran; our contract draft was wrong, not the code
montrealrobotics/shapo/safepo/single_agent/shapo.py
code served (permissive licence) · get_code("042de5c327d75c75")
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 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

torch.manual_seed(0)

# Create small gradient tensors
grads = torch.randn(4, requires_grad=False)
step_direction = torch.randn(4, requires_grad=False)
x = torch.randn(4, requires_grad=False)

ARGS = {
    "grads": grads,
    "step_direction": step_direction,
    "x": x,
}
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 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
ActorVCritic Not yet run
unverified (harvested, no recorded run)
montrealrobotics/shapo/safepo/single_agent/shapo.py
code served (permissive licence) · get_code("0ca07951d425f2e4")
How it ran

no invocation recorded.

compute_natural_gradient_direction Not yet run
unverified (harvested, no recorded run)
montrealrobotics/shapo/safepo/single_agent/shapo.py
code served (permissive licence) · get_code("952f8639298e4857")
How it ran

no invocation recorded.

compute_shapo_gradients_actor Not yet run
unverified (harvested, no recorded run)
montrealrobotics/shapo/safepo/single_agent/shapo.py
code served (permissive licence) · get_code("6c2cbc030bbea5a9")
How it ran

no invocation recorded.

conjugate_gradients Not yet run
unverified (harvested, no recorded run)
montrealrobotics/shapo/safepo/single_agent/shapo.py
code served (permissive licence) · get_code("66ed7b1d9ea7acbc")
How it ran

no invocation recorded.

fvp Not yet run
unverified (harvested, no recorded run)
montrealrobotics/shapo/safepo/single_agent/shapo.py
code served (permissive licence) · get_code("979727939a5c3e51")
How it ran

no invocation recorded.

set_param_values_to_model Not yet run
unverified (harvested, no recorded run)
montrealrobotics/shapo/safepo/single_agent/shapo.py
code served (permissive licence) · get_code("000d35f42103806e")
How it ran

no invocation recorded.

Also present in other papers' code

Of 13 samples lifted from this paper's linked repositories, 13 carry a function identity and 0 do not. Of the 13 distinct functions with an identity, 0 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 0 later) and 13 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.

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

Safe exploration is a prerequisite for deploying reinforcement learning (RL) agents in safety-critical domains. In this paper, we approach safe exploration through the lens of epistemic uncertainty, where the actor's sensitivity to parameter perturbations serves as a practical proxy for regions of high uncertainty. We propose Sharpness-Aware Policy Optimization (SHAPO), a sharpness-aware policy update rule that evaluates gradients at perturbed parameters, making policy updates pessimistic with respect to the actor's epistemic uncertainty. Analytically we show that this adjustment implicitly reweighs policy gradients, amplifying the influence of rare unsafe actions while tempering contributions from already safe ones, thereby biasing learning toward conservative behavior in under-explored regions. Across several continuous-control tasks, our method consistently improves both safety and task performance over existing baselines, significantly expanding their Pareto frontiers.

For agents

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

get_harvested_code_for_paper("2606.10228")
get_code_for_paper("2606.10228")
have("2606.10228")

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

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

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

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

Connect an agent — have() is free.