/toolkit:latex-syncfrom toolkit
Sets up latex-code-sync to link paper equations with code implementations, annotates functions with equation decorators, and verifies math-code agreement.
Ships in toolkit. Installing the plugin adds it to Claude Code.
One workflow against one CLI, in the order you do it.
| They said | Mode |
|---|---|
| "set up", "initialize", "add this to my project" | setup |
| "link", "annotate", "tag this function" | annotate |
| "verify", "check", "do they match" | verify |
Three skills until RFC-0002, and the split bought a user nothing: nobody annotates without having set up, and nobody verifies without having annotated.
Hybrid: Project structure detection and file generation are scripted. LLM is used to identify equation-code correspondences.
Initialize latex-code-sync in a research project to link paper equations with code implementations.
@latex decoratorslatex-code-sync.toml with project settingsproject/
├── paper/
│ ├── main.tex
│ └── appendix.tex
├── src/
│ └── equations.py # Create here
└── pyproject.toml
code-repo/ paper-repo/
├── equations.py ├── main.tex
├── model.py └── appendix.tex
├── pyproject.toml
└── .github/workflows/
└── verify-equations.yml # Clone paper-repo in CI
# pyproject.toml
[project.optional-dependencies]
verify = ["latex-code-sync>=0.1.0"]
# or in requirements.txt
latex-code-sync>=0.1.0
# equations.py
"""
LaTeX-Code Sync: Linking paper equations to implementations.
Equation Registry:
- eq:loss -> loss_function()
- eq:gradient -> gradient_step()
"""
from __future__ import annotations
import torch
try:
from latex_code_sync import latex, VerifyStrategy
except ImportError:
def latex(*args, **kwargs):
def decorator(func): return func
return decorator
class VerifyStrategy:
NONE = "none"
TEST_CASES = "test_cases"
@latex(
"eq:loss",
notation={"y": "y", "y_hat": r"\hat{y}"},
description="Loss function (Eq. X in paper)",
test_cases=[
{"inputs": {"y": torch.tensor([1.0]), "y_hat": torch.tensor([1.0])}, "expected": 0.0},
],
)
def loss_function(y: torch.Tensor, y_hat: torch.Tensor) -> torch.Tensor:
"""Compute loss."""
return torch.mean((y - y_hat) ** 2)
if __name__ == "__main__":
print("Testing equations...")
# Quick self-test
# latex-code-sync.toml
[latex-code-sync]
latex_dir = "paper/"
modules = ["equations"]
strict = true
warn_unlabeled = true
[paper]
repository = "user/paper-repo" # For separate repos
branch = "main"
# .github/workflows/verify-equations.yml
name: Verify Equations
on:
push:
branches: [main]
paths: ['equations.py', '*.py']
pull_request:
paths: ['equations.py', '*.py']
schedule:
- cron: '0 6 * * *' # Daily check
workflow_dispatch:
jobs:
verify:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v4
with:
repository: ${{ github.repository_owner }}/paper-repo
path: paper
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- run: pip install -e ".[verify]" torch --index-url https://download.pytorch.org/whl/cpu
- name: List equations
run: |
python -c "
import equations
from latex_code_sync import get_registry
for label, spec in get_registry().equations.items():
print(f'{label}: {spec.function.__name__ if spec.function else \"N/A\"}')"
- name: Verify
run: latex-code-sync verify --latex-dir=paper/ --modules=equations --strict
# In paper directory
grep -rn "\\\\label{eq:" *.tex
grep -rn "\\\\label{eq:" **/*.tex
# Example output:
# main.tex:45: E = mc^2 \label{eq:energy}
# appendix.tex:123: \beta = \int v_t \, dt \label{eq:beta-def}
# Look for functions that might implement equations
grep -rn "def compute_\|def calculate_\|def loss\|def energy" *.py
grep -rn "torch.mean\|torch.sum\|torch.exp" *.py
| LaTeX Pattern | Code Pattern |
|---|---|
eq:loss, eq:*-loss | *_loss(), compute_loss() |
eq:energy, eq:E-* | energy(), compute_energy() |
eq:gradient, eq:grad-* | gradient(), grad_*() |
eq:update, eq:step | update(), step() |
eq:softmax, eq:sigmoid | softmax(), sigmoid() |
eq:kl, eq:divergence | kl_divergence(), kl_div() |
# Explicit test cases (recommended)
@latex("eq:x", test_cases=[...])
# Property-based (for invariants)
@latex("eq:x", verify="properties", properties=["output >= 0"])
# No verification (complex implementations)
@latex("eq:x", verify="none")
After setup, verify:
equations.py created with @latex decoratorslatex-code-sync.toml configuration filepyproject.tomlpython equations.pyLLM-required: Linking code functions to paper equations requires understanding mathematical semantics. No script alternative.
Add @latex decorators to existing Python functions to create verified links between code implementations and paper equations.
\label{eq:...} in LaTeX@latex(...) above function@latex("eq:loss")
def compute_loss(y, y_hat):
return torch.mean((y - y_hat) ** 2)
@latex(
"eq:gradient-descent",
notation={
"params": r"\theta", # θ in paper
"loss": r"\mathcal{L}", # L in paper
"learning_rate": r"\eta", # η in paper
},
)
def gradient_step(params, loss, learning_rate):
return params - learning_rate * grad(loss, params)
@latex(
"eq:softmax",
test_cases=[
{
"inputs": {"logits": torch.tensor([0.0, 0.0, 0.0])},
"expected": torch.tensor([1/3, 1/3, 1/3]),
"tolerance": 1e-6,
},
{
"inputs": {"logits": torch.tensor([1000.0, 0.0, 0.0])},
"expected": torch.tensor([1.0, 0.0, 0.0]),
"tolerance": 1e-4,
},
],
)
def softmax(logits: torch.Tensor) -> torch.Tensor:
exp_x = torch.exp(logits - logits.max())
return exp_x / exp_x.sum()
@latex(
"eq:elbo",
depends=["eq:kl-divergence", "eq:reconstruction"],
description="Evidence lower bound combines KL and reconstruction terms",
)
def elbo(x, z, mu, logvar):
return reconstruction_loss(x, z) - kl_divergence(mu, logvar)
@latex(
"eq:complex-integral",
verify="none", # Too complex to test with simple cases
description="Numerical integration of path measure",
)
def compute_path_integral(trajectories, potential):
# Complex implementation...
pass
| Python Name | LaTeX Symbol | Example |
|---|---|---|
x, input | x | Input data |
y, target | y | Target/label |
y_hat, pred | \hat{y} | Prediction |
params, theta | \theta | Model parameters |
learning_rate, lr | \eta | Learning rate |
loss, L | \mathcal{L} | Loss function |
grad, gradient | \nabla | Gradient |
mu, mean | \mu | Mean |
sigma, std | \sigma | Standard deviation |
alpha, beta, gamma | \alpha, \beta, \gamma | Greek letters |
weight, W | W or \mathbf{W} | Weight matrix |
bias, b | b or \mathbf{b} | Bias vector |
hidden, h | h or \mathbf{h} | Hidden state |
epsilon, eps | \epsilon | Small constant |
lambda_, lam | \lambda | Regularization |
temperature, tau | \tau | Temperature |
test_cases=[
# Zero case
{"inputs": {"x": torch.zeros(3)}, "expected": torch.zeros(3)},
# Identity case
{"inputs": {"x": torch.ones(3)}, "expected": torch.ones(3)},
# Known values
{"inputs": {"x": torch.tensor([1.0, 2.0])}, "expected": torch.tensor([...])},
]
test_cases=[
# Perfect prediction = zero loss
{"inputs": {"y": t([1,2,3]), "y_hat": t([1,2,3])}, "expected": 0.0},
# Known error
{"inputs": {"y": t([0.0]), "y_hat": t([1.0])}, "expected": 1.0},
]
test_cases=[
# Uniform distribution
{"inputs": {"logits": torch.zeros(3)}, "expected": torch.tensor([1/3, 1/3, 1/3])},
# Peaked distribution
{"inputs": {"logits": torch.tensor([100.0, 0.0])}, "expected": torch.tensor([1.0, 0.0])},
# Sum to 1
{"inputs": {"logits": torch.randn(5)}, "property": "output.sum() == 1.0"},
]
Given these equations in paper:
% main.tex
\begin{equation}\label{eq:energy}
E_t^{(j)}(\phi, x) := \frac{\|\phi_{\Omega_x} - \sqrt{\bar\alpha_t}\varphi_j\|_2^2}{2(1-\bar\alpha_t)}
\end{equation}
\begin{equation}\label{eq:weights}
W_t^{(j)}(\phi,x) := \frac{e^{-E_t^{(j)}}}{\sum_{\ell} e^{-E_t^{(\ell)}}}
\end{equation}
\begin{equation}\label{eq:uncertainty}
\mathsf{U}_t(\phi,x) := 1 - \sum_{j=1}^N W_t^{(j)}(\phi,x)^2
\end{equation}
Create annotated functions:
# equations.py
from latex_code_sync import latex
import torch
@latex(
"eq:energy",
notation={
"phi_patch": r"\phi_{\Omega_x}",
"library_patch": r"\varphi_j",
"alpha_bar_t": r"\bar\alpha_t",
},
test_cases=[
{"inputs": {"phi_patch": torch.zeros(9), "library_patch": torch.zeros(9), "alpha_bar_t": 0.5}, "expected": 0.0},
],
)
def els_energy(phi_patch, library_patch, alpha_bar_t):
"""ELS patch-matching energy."""
sqrt_alpha = torch.sqrt(torch.tensor(alpha_bar_t))
sigma_sq = 1 - alpha_bar_t
diff = phi_patch - sqrt_alpha * library_patch
return (diff ** 2).sum() / (2 * sigma_sq)
@latex(
"eq:weights",
notation={"energies": r"E_t^{(j)}"},
depends=["eq:energy"],
)
def gibbs_weights(energies):
"""Compute Gibbs/softmax weights from energies."""
return torch.softmax(-energies, dim=-1)
@latex(
"eq:uncertainty",
notation={"weights": r"W_t^{(j)}"},
depends=["eq:weights"],
test_cases=[
{"inputs": {"weights": torch.tensor([1.0, 0.0, 0.0])}, "expected": 0.0},
{"inputs": {"weights": torch.tensor([0.5, 0.5])}, "expected": 0.5},
],
)
def weight_uncertainty(weights):
"""Gini impurity of weight distribution."""
return 1.0 - (weights ** 2).sum(dim=-1)
eq:energy not eq:Energyverify="none")Script-first: This skill runs the latex-code-sync CLI tool. LLM assists only with interpreting failures.
Run latex-code-sync verification to ensure paper equations match their code implementations.
# Basic verification
latex-code-sync verify --latex-dir=paper/ --modules=equations
# Strict mode (fail on any issue)
latex-code-sync verify --latex-dir=paper/ --modules=equations --strict
# Verbose output
latex-code-sync verify --latex-dir=paper/ --modules=equations -v
# Multiple modules
latex-code-sync verify --latex-dir=paper/ --modules=equations,models.loss,utils.math
| Check | Description | Example Issue |
|---|---|---|
| Label exists | \label{eq:X} found in LaTeX | Typo in decorator |
| Function registered | @latex("eq:X") decorator present | Missing import |
| Test cases pass | Test inputs produce expected outputs | Implementation bug |
| Dependencies valid | All depends labels exist | Removed equation |
| Notation consistent | Symbol mappings are plausible | Parameter renamed |
✓ eq:energy - PASSED (3 test cases)
✓ eq:weights - PASSED (2 test cases)
✓ eq:uncertainty - PASSED (2 test cases)
Verification complete: 3/3 equations passed
✗ eq:energy - FAILED
Test case 1: Expected 0.0, got 0.5
Inputs: phi_patch=zeros(9), library_patch=zeros(9), alpha_bar_t=0.5
Code: equations.py:45 els_energy()
Paper: main.tex:67 \label{eq:energy}
Possible causes:
- Formula mismatch: check normalization factor
- Parameter interpretation differs
⚠ eq:beta-def - Label not found in LaTeX
Decorator at: equations.py:89
Searched: paper/*.tex
Did you mean: eq:beta (found in appendix.tex:234)?
# Run the equations module directly
python equations.py
# Or in Python
import equations
from latex_code_sync import get_registry, verify_all
registry = get_registry()
results = verify_all(registry)
for label, result in results.items():
print(f"{label}: {'PASS' if result.passed else 'FAIL'}")
# Clone/locate paper repo
git clone https://github.com/user/paper-repo paper/
# Run verification
latex-code-sync verify --latex-dir=paper/ --modules=equations
# Simulates CI environment
PAPER_DIR=paper/ latex-code-sync verify --modules=equations --strict
# Add debugging to test case
@latex(
"eq:energy",
test_cases=[{
"inputs": {"x": torch.tensor([1.0])},
"expected": 1.0,
"debug": True, # Print intermediate values
}]
)
# Test function manually
from equations import els_energy
import torch
phi = torch.zeros(9)
lib = torch.zeros(9)
alpha = 0.5
result = els_energy(phi, lib, alpha)
print(f"Result: {result}")
print(f"Expected: 0.0")
print(f"Match: {abs(result - 0.0) < 1e-6}")
# Paper: E = ||φ - √α·lib||² / (2(1-α))
def paper_formula(phi, lib, alpha):
diff = phi - math.sqrt(alpha) * lib
return (diff ** 2).sum() / (2 * (1 - alpha))
# Code implementation
def code_implementation(phi, lib, alpha):
return els_energy(phi, lib, alpha)
# Compare
phi = torch.randn(9)
lib = torch.randn(9)
alpha = 0.5
paper_result = paper_formula(phi, lib, alpha)
code_result = code_implementation(phi, lib, alpha)
print(f"Paper: {paper_result:.6f}")
print(f"Code: {code_result:.6f}")
print(f"Diff: {abs(paper_result - code_result):.2e}")
# Increase tolerance
test_cases=[{
"inputs": {...},
"expected": 0.333333,
"tolerance": 1e-5, # Default is 1e-6
}]
# Ensure consistent shapes in test
test_cases=[{
"inputs": {"x": torch.tensor([1.0, 2.0])}, # Shape: (2,)
"expected": torch.tensor([0.5, 1.0]), # Must match shape
}]
# Set seed for reproducibility
@latex("eq:x", test_cases=[...])
def func_with_randomness(x):
torch.manual_seed(42) # Fixed seed
return ...
# Force CPU for tests
test_cases=[{
"inputs": {"x": torch.tensor([1.0]).cpu()},
"expected": torch.tensor([1.0]).cpu(),
}]
# Markdown report
latex-code-sync report --latex-dir=paper/ --modules=equations -o report.md
# JSON for CI
latex-code-sync verify --latex-dir=paper/ --modules=equations --json > results.json
# Equation Verification Report
## Summary
- Total equations: 12
- Passed: 10
- Failed: 1
- Skipped: 1
## Details
### eq:energy ✓
- File: equations.py:45
- Tests: 3/3 passed
- Notation: φ_Ω → phi_patch, α̅ → alpha_bar_t
### eq:weights ✗
- File: equations.py:67
- Tests: 1/2 failed
- Error: Test 2 expected [0.5, 0.5], got [0.499, 0.501]
What the command file sets; muted values are Claude Code's defaults
sonnetlatex, equations, code-verification, research, reproducibility
7-day visitors to each command page
8 commands in this plugin
/agora-feedbackOpt-in, review-gated usage feedback for Research Agora skills (RFC-0001).
Use when asked to "enable agora feedback", "share skill feedback",
"show my skill usage stats", "submit agora feedback", "report skill usage",
"disable feedback capture", or "purge my feedback spool".
Nothing is ever sent without the user reviewing the exact payload and
explicitly confirming.
/code-simplifyAnalyze and refactor Python codebases to remove dead code, eliminate duplication, and simplify complexity. Use when asked to "simplify code", "remove dead code", "find duplicates", "refactor", "clean up codebase", or "reduce complexity"./experiment-trackerSync ML experiment results to paper drafts. Use when asked to "update results",
"sync experiments", "pull latest metrics", "update tables from code",
"experiment to paper", "refresh results", or "sync paper with repo".
Extracts metrics from code/logs and updates paper sections.
/figuresMake publication figures for ML papers, in TikZ or matplotlib. Use when asked
to "create a figure", "make a plot", "visualize results", "draw a neural
network", "make a diagram in LaTeX", "TikZ flowchart", "architecture diagram",
"publication figure", "style matplotlib", or "format figures for a
conference". **tikz** draws diagrams whose content you describe; **plot**
renders data you supply, read from real files rather than invented.
/htcondorGenerate HTCondor submission files and wrapper scripts for ML research jobs.
Use when asked to "create condor job", "submit to cluster", "write .sub file",
"htcondor setup", "cluster job", or "batch submission". Supports GPU/CPU jobs,
parameter sweeps, multi-seed experiments, and ablation studies.
/latexBuild, debug and lint a LaTeX paper. Use when asked to "build the pdf",
"recompile", "compile the paper", "why won't my paper compile", "the pdf is
still the old version", "fix latex errors", "debug latex", "parse the log",
"fix LaTeX", "make LaTeX consistent", "check LaTeX style", or "standardize
notation". Three modes over one source tree: **build** compiles with latexmk
and proves the PDF is fresh, **debug** reads the log that build produced and
fixes what it reports, **lint** greps for house-style and notation violations.
npx claudepluginhub rpatrik96/research-agora --plugin toolkitOther plugins' commands for the same job