SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2406.03234 · ICML · 2024

Fine-Grained Causal Dynamics Learning with Quantization for Improving Robustness in Reinforcement Learning

Byoung-Tak Zhang, Inwoo Hwang, Yunhyeok Kwak, Suhyung Choi, Sanghack Lee

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 (0 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; 4 failures of our instrument; 5 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/2406.03234.json · badge: /api/ran/2406.03234.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
iwhwang/Fine-Grained-Causal-RL marked official in Papers with Code
Papers with Code archive
6 ran · 5 no recorded run
FunctionStatusWhere it lives
NearestEmbed Ran
ran on a synthesized input
iwhwang/Fine-Grained-Causal-RL/fcdl/model/inference_ours_base.py
code served (permissive licence) · get_code("01a299feb3afceea")
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 torch.nn as nn
import numpy as np

INIT_ARGS = {
    'num_embeddings': 8,
    'embeddings_dim': 4,
}

ARGS = {
    'x': torch.randn(2, 4, 3, 3),
    'weight_sg': False,
}

if __name__ == '__main__':
    from torch.autograd import Function

    class NearestEmbedFunc(Function):
        """
        Input:
        ------
        x - (batch_size, emb_dim, *)
            Last dimensions may be arbitrary
        emb - (emb_dim, num_emb)
        """

        @staticmethod
        def forward(ctx, input, emb):
            if input.size(1) != emb.size(0):
                raise RuntimeError('invalid argument: input.size(1) ({}) must be equal to emb.size(0) ({})'.format(input.size(1), emb.size(0)))
            ctx.batch_size = input.size(0)
            ctx.num_latents = int(np.prod(np.array(input.size()[2:])))
            ctx.emb_dim = emb.size(0)
            ctx.num_emb = emb.size(1)
            ctx.input_type = type(input)
            ctx.dims = list(range(len(input.size())))
            x_expanded = input.unsqueeze(-1)
            num_arbitrary_dims = len(ctx.dims) - 2
            if num_arbitrary_dims:
                emb_expanded = emb.view(emb.shape[0], *[1] * num_arbitrary_dims, emb.shape[1])
            else:
                emb_expanded = emb
            dist = torch.norm(x_expanded - emb_expanded, 2, 1)
            _, argmin = dist.min(-1)
            shifted_shape = [input.shape[0], *list(input.shape[2:]), input.shape[1]]
            result = emb.t().index_select(0, argmin.view(-1)).view(shifted_shape).permute(0, ctx.dims[-1], *ctx.dims[1:-1])
            ctx.save_for_backward(argmin)
            return (result.contiguous(), argmin)

        @staticmethod
        def backward(ctx, grad_output, argmin=None):
            grad_input = grad_emb = None
            if ctx.needs_input_grad[0]:
                grad_input = grad_output
            if ctx.needs_input_grad[1]:
                argmin, = ctx.saved_tensors
                latent_indices = torch.arange(ctx.num_emb).type_as(argmin)
                idx_choices = (argmin.view(-1, 1) == latent_indices.view(1, -1)).type_as(grad_output.data)
                n_idx_choice = idx_choices.sum(0)
                n_idx_choice[n_idx_choice == 0] = 1
                idx_avg_choices = idx_choices / n_idx_choice
                grad_output = grad_output.permute(0, *ctx.dims[2:], 1).contiguous()
                grad_output = grad_output.view(ctx.batch_size * ctx.num_latents, ctx.emb_dim)
                grad_emb = torch.sum(grad_output.data.view(-1, ctx.emb_dim, 1) * idx_avg_choices.view(-1, 1, ctx.num_emb), 0)
            return (grad_input, grad_emb)

    def nearest_embed(x, emb):
        return NearestEmbedFunc.apply(x, emb)

    class NearestEmbed(nn.Module):

        def __init__(self, num_embeddings, embeddings_dim):
            super(NearestEmbed, self).__init__()
            self.weight = nn.Parameter(torch.rand(embeddings_dim, num_embeddings))

        def forward(self, x, weight_sg=False):
            """Input:
            ---------
            x - (batch_size, emb_size, *)
            """
            return nearest_embed(x, self.weight.detach() if weight_sg else self.weight)

    module = NearestEmbed(**INIT_ARGS)
    output = module(**ARGS)
    print("Output shape:", output[0].shape)
    print("Argmin shape:", output[1].shape)
    print("Success!")
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 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)
NearestEmbedEMA Ran
ran on a synthesized input
iwhwang/Fine-Grained-Causal-RL/fcdl/model/inference_ours_base.py
code served (permissive licence) · get_code("ecb0e7b0c5200bbb")
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 torch.nn as nn

class NearestEmbedEMA(nn.Module):

    def __init__(self, n_emb, emb_dim, decay=0.99, eps=1e-05):
        super(NearestEmbedEMA, self).__init__()
        self.decay = decay
        self.eps = eps
        self.embeddings_dim = emb_dim
        self.n_emb = n_emb
        self.emb_dim = emb_dim
        embed = torch.randn(emb_dim, n_emb)
        self.register_buffer('weight', embed)
        self.register_buffer('cluster_size', torch.zeros(n_emb))
        self.register_buffer('embed_avg', embed.clone())
        self.is_freeze = False

    def forward(self, x):
        dims = list(range(len(x.size())))
        x_expanded = x.unsqueeze(-1)
        num_arbitrary_dims = len(dims) - 2
        if num_arbitrary_dims:
            emb_expanded = self.weight.view(self.emb_dim, *[1] * num_arbitrary_dims, self.n_emb)
        else:
            emb_expanded = self.weight
        dist = torch.norm(x_expanded - emb_expanded, 2, 1)
        _, argmin = dist.min(-1)
        shifted_shape = [x.shape[0], *list(x.shape[2:]), x.shape[1]]
        result = self.weight.t().index_select(0, argmin.view(-1)).view(shifted_shape).permute(0, dims[-1], *dims[1:-1])
        if self.training and (not self.is_freeze):
            latent_indices = torch.arange(self.n_emb).type_as(argmin)
            emb_onehot = (argmin.view(-1, 1) == latent_indices.view(1, -1)).type_as(x.data)
            n_idx_choice = emb_onehot.sum(0)
            n_idx_choice[n_idx_choice == 0] = 1
            flatten = x.permute(1, 0).contiguous().view(x.shape[1], -1)
            self.cluster_size.data.mul_(self.decay).add_(1 - self.decay, n_idx_choice)
            embed_sum = flatten @ emb_onehot
            self.embed_avg.data.mul_(self.decay).add_(1 - self.decay, embed_sum)
            n = self.cluster_size.sum()
            cluster_size = (self.cluster_size + self.eps) / (n + self.n_emb * self.eps) * n
            embed_normalized = self.embed_avg / cluster_size.unsqueeze(0)
            self.weight.data.copy_(embed_normalized)
        return (result, argmin)


INIT_ARGS = {
    'n_emb': 5,
    'emb_dim': 4,
    'decay': 0.99,
    'eps': 1e-05
}

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

if __name__ == '__main__':
    model = NearestEmbedEMA(**INIT_ARGS)
    model.train()
    result, argmin = model(**ARGS)
    print("Result shape:", result.shape)
    print("Argmin shape:", argmin.shape)
    print("Result:", result)
    print("Argmin:", argmin)
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
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: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
gumbel_sigmoid_batch Ran
ran; our contract draft was wrong, not the code
iwhwang/Fine-Grained-Causal-RL/fcdl/model/inference_ours_base.py
code served (permissive licence) · get_code("e068bd1d96a5dfbb")
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)

# log_alpha: tensor that will be used in sigmoid computation
# Shape: (4,) - a 1D tensor of log probabilities
log_alpha = torch.randn(4, dtype=torch.float32)

# device: where to place tensors
device = 'cpu'

# bs: batch size (optional, can be None or an integer)
bs = 2

# tau: temperature parameter for gumbel-sigmoid
tau = 1.0

# hard: whether to use hard concrete or soft version
hard = False

ARGS = {
    'log_alpha': log_alpha,
    'device': device,
    'bs': bs,
    'tau': tau,
    'hard': hard
}
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
nearest_embed Ran
ran; our contract draft was wrong, not the code
iwhwang/Fine-Grained-Causal-RL/fcdl/model/inference_ours_base.py
code served (permissive licence) · get_code("34f0bd8890d57785")
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. 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 valid arguments for nearest_embed(x, emb)
# x: (batch_size, emb_dim, *)
# emb: (emb_dim, num_emb)

batch_size = 2
emb_dim = 4
num_emb = 3

# Create input tensor with shape (batch_size, emb_dim, spatial_dim)
# Using spatial dimension of 5 to make it distinct from other dims
x = torch.randn(batch_size, emb_dim, 5)

# Create embedding tensor with shape (emb_dim, num_emb)
emb = torch.randn(emb_dim, num_emb)

ARGS = {
    'x': x,
    'emb': emb
}
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 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
sample_logistic Ran
ran; our contract draft was wrong, not the code
iwhwang/Fine-Grained-Causal-RL/fcdl/model/inference_ours_base.py
code served (permissive licence) · get_code("5d1698fd8ac701df")
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)

ARGS = {
    "shape": (2, 4),
    "device": torch.device("cpu"),
}
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
to_numpy Ran
ran; our contract draft was wrong, not the code
iwhwang/Fine-Grained-Causal-RL/fcdl/model/inference_ours_base.py
code served (permissive licence) · get_code("e8a1a77da0a39f61")
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 ndarray, 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
import numpy as np

torch.manual_seed(0)

# Create a small tensor on CPU
tensor = torch.randn(2, 4)

ARGS = {
    "tensor": tensor
}
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 ndarray, 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
Inference Not yet run
unverified (harvested, no recorded run)
iwhwang/Fine-Grained-Causal-RL/fcdl/model/inference_ours_base.py
code served (permissive licence) · get_code("f1fd3b6a5e8c1295")
How it ran

no invocation recorded.

InferenceOursBase Not yet run
unverified (harvested, no recorded run)
iwhwang/Fine-Grained-Causal-RL/fcdl/model/inference_ours_base.py
code served (permissive licence) · get_code("3830e846ed12b85e")
How it ran

no invocation recorded.

NearestEmbedFunc Not yet run
unverified (harvested, no recorded run)
iwhwang/Fine-Grained-Causal-RL/fcdl/model/inference_ours_base.py
code served (permissive licence) · get_code("f55aad2046e48425")
How it ran

no invocation recorded.

VQVAEGumbelMatrixLatent Not yet run
unverified (harvested, no recorded run)
iwhwang/Fine-Grained-Causal-RL/fcdl/model/inference_ours_base.py
code served (permissive licence) · get_code("a845f759481f9c69")
How it ran

no invocation recorded.

kaiming_init Not yet run
unverified (harvested, no recorded run)
iwhwang/Fine-Grained-Causal-RL/fcdl/model/inference_ours_base.py
code served (permissive licence) · get_code("9ffd4319295052f4")
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, 3 are also present in other papers whose code we hold (3 with at least one paper dated earlier, 0 the same month, 1 later) and 8 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
nearest_embed
brick of this paper's assembly: helper
2 other papers
1 dated earlier, 1 later
1711.00937 (2017-11)
Neural Discrete Representation Learning
2412.04671 (2024-12)
Fully Distributed, Flexible Compositional Visual Representations via Soft Tensor Products
NearestEmbed
brick of this paper's assembly: helper
1 other paper
1 dated earlier
1711.00937 (2017-11)
Neural Discrete Representation Learning
NearestEmbedFunc
brick of this paper's assembly: helper
1 other paper
1 dated earlier
1711.00937 (2017-11)
Neural Discrete Representation Learning

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

Causal dynamics learning has recently emerged as a promising approach to enhancing robustness in reinforcement learning (RL). Typically, the goal is to build a dynamics model that makes predictions based on the causal relationships among the entities. Despite the fact that causal connections often manifest only under certain contexts, existing approaches overlook such fine-grained relationships and lack a detailed understanding of the dynamics. In this work, we propose a novel dynamics model that infers fine-grained causal structures and employs them for prediction, leading to improved robustness in RL. The key idea is to jointly learn the dynamics model with a discrete latent variable that quantizes the state-action space into subgroups. This leads to recognizing meaningful context that displays sparse dependencies, where causal structures are learned for each subgroup throughout the training. Experimental results demonstrate the robustness of our method to unseen states and locally spurious correlations in downstream tasks where fine-grained causal reasoning is crucial. We further illustrate the effectiveness of our subgroup-based approach with quantization in discovering fine-grained causal relationships compared to prior methods.

For agents

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

get_harvested_code_for_paper("2406.03234")
get_code_for_paper("2406.03234")
have("2406.03234")

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

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

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

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

Connect an agent — have() is free.