LeetLLM
My PlanLearnGlossaryTracksPracticeBlog
LeetLLM

Your go-to resource for mastering AI & LLM systems.

Product

  • Learn
  • Glossary
  • Tracks
  • Practice
  • Blog
  • RSS

Legal

  • Terms of Service
  • Privacy Policy

ยฉ 2026 LeetLLM. All rights reserved.

All Topics
Your Progress
0%

0 of 177 articles completed

๐Ÿ› ๏ธComputing Foundations0/9
Git, Shell, Linux for AIDocker for Reproducible AIPython for AI EngineeringNumPy and Tensor ShapesCUDA for ML TrainingMPS & Metal for ML on MacData Structures for AISQL and Data ModelingAlgorithms for ML Engineers
๐Ÿ“ŠMath & Statistics0/8
Gradients and BackpropVectors, Matrices & TensorsLinear Algebra for MLAdam, Momentum, SchedulersProbability for Machine LearningStatistics and UncertaintyDistributions and SamplingHypothesis Tests, Intervals, and pass@k
๐Ÿ“šPreparation & Prerequisites0/13
Neural Networks from ScratchCNNs from ScratchTraining & BackpropagationSoftmax, Cross-Entropy & OptimizationRNNs, LSTMs, GRUs, and Sequence ModelingAutoencoders and VAEsThe Transformer Architecture End-to-EndLanguage Modeling & Next TokensFrom GPT to Modern LLMsPrompt Engineering FundamentalsCalling LLM APIs in ProductionFirst AI App End-to-EndThe LLM Lifecycle
๐ŸงฎML Algorithms & Evaluation0/11
Linear Regression from ScratchLogistic Regression and MetricsDecision Trees, Forests, and BoostingReinforcement Learning BasicsValidation and LeakageClustering and PCACore Retrieval AlgorithmsDecoding AlgorithmsExperiment Design and A/B TestingPyTorch Training LoopsDataset Pipelines and Data Quality
๐Ÿ“ฆProduction ML Systems0/6
Feature Engineering for Production MLBatch and Streaming Feature PipelinesGradient Boosted Trees in ProductionRanking and Recommendation SystemsForecasting and Anomaly DetectionMonitoring Predictive Models
๐ŸงชCore LLM Foundations0/8
The Bitter Lesson & ComputeBPE, WordPiece, and SentencePieceStatic to Contextual EmbeddingsPerplexity & Model EvaluationFile Ingestion for AIChunking StrategiesLLM Benchmarks & LimitationsInstruction Tuning & Chat Templates
๐ŸงฐApplied LLM Engineering0/24
Dimensionality Reduction for EmbeddingsCoT, ToT & Self-Consistency PromptingFunction Calling & Tool UseMCP & Tool Protocol StandardsContext EngineeringPrompt Injection DefenseResponsible AI GovernanceData Labeling and Human FeedbackEvaluating AI AgentsProduction RAG PipelinesHybrid Search: Dense + SparseReranking and Cross-Encoders for RAGRAG Evaluation for Reliable AnswersLLM-as-a-Judge EvaluationBias & Fairness in LLMsHallucination Detection & MitigationLLM Observability & MonitoringExperiment Tracking with MLflow and W&BPrompt Optimization with DSPyModel Versioning & DeploymentSemantic Caching & Cost OptimizationLLM Cost Engineering & Token EconomicsModel Gateways, Routing, and FallbacksDesign an Automated Support Agent
๐ŸŽ“Portfolio Capstones0/9
Capstone: Delivery ETA PredictionCapstone: Product RankingCapstone: Demand ForecastingCapstone: Image Damage ClassifierCapstone: Production ML PipelineCapstone: Document QACapstone: Eval DashboardCapstone: Fine-Tuned ClassifierCapstone: Reproducible ML Study
๐Ÿง Transformer Deep Dives0/8
Sentence Embeddings & Contrastive LossEmbedding Similarity & QuantizationScaled Dot-Product AttentionVision Transformers and Image EncodersPositional Encoding: RoPE & ALiBiLayer Normalization: Pre-LN vs Post-LNMechanistic InterpretabilityDecoding Strategies: Greedy to Nucleus
๐ŸงฌAdvanced Training & Adaptation0/16
Scaling Laws & Compute-Optimal TrainingPre-training Data at ScaleBuild GPT from Scratch LabJAX for PyTorch ResearchersContinued Pretraining for Domain ShiftSynthetic Data PipelinesSupervised Fine-Tuning PipelineMixed Precision TrainingDistributed Training: FSDP & ZeROLoRA & Parameter-Efficient TuningReward Modeling from Preference DataRLHF & DPO AlignmentConstitutional AI & Red TeamingRLVR & Verifiable RewardsKnowledge Distillation for LLMsModel Merging and Weight Interpolation
๐Ÿค–Advanced Agents & Retrieval0/16
Vector DB Internals: HNSW & IVFAdvanced RAG: HyDE & Self-RAGGraphRAG & Knowledge GraphsRAG Security & Access ControlStructured Output GenerationReAct & Plan-and-ExecuteGuardrails & Safety FiltersCode Generation & SandboxingComputer-Use / GUI / Browser AgentsHuman-in-the-Loop Agent ArchitectureAI Coding Workflow with AgentsAgent Memory & PersistenceAgent Failure & RecoveryRecursive Language Models (RLM)Multi-Agent OrchestrationCapstone: Production Agent
โšกInference & Production Scale0/19
Inference: TTFT, TPS & KV CacheMulti-Query & Grouped-Query AttentionKV Cache & PagedAttentionPrefix Caching and Prompt CachingFlashAttention & Memory EfficiencyContinuous Batching & SchedulingScaling LLM InferenceModel Parallelism for LLM InferenceModel Quantization: GPTQ, AWQ & GGUFLocal LLM DeploymentSLM Specialization & Edge DeploymentSpeculative DecodingLong Context Window ManagementMixture of Experts ArchitectureMamba & State Space ModelsReasoning & Test-Time ComputeAdvanced MLOps & DevOps for AIGPU Serving & AutoscalingA/B Testing for LLMs
๐Ÿ—๏ธSystem Design Capstones0/9
Content Moderation SystemCode Completion SystemMulti-Tenant LLM PlatformLLM-Powered Search EngineVision-Language Models & CLIPMultimodal LLM ArchitectureDiffusion Models: Images & TextReal-Time Voice AI AgentReasoning & Test-Time Compute
๐ŸŽคAI Lab Interviewing0/4
AI Lab Coding Interview: Python SystemsAI Lab System Design InterviewAI Lab Behavioral InterviewAI Lab Technical Presentation
๐Ÿ”ฌProject Deep Dives0/17
Deep Dive - vLLMDeep Dive - SkyRLDeep Dive - FlashAttentionDeep Dive - FlashInferDeep Dive - DeepGEMMDeep Dive - NCCLDeep Dive - MegatronDeep Dive - DeepSpeedDeep Dive - RayDeep Dive - MLflowDeep Dive - PyTorchDeep Dive - TransformersDeep Dive - SGLangDeep Dive - slimeDeep Dive - DeepEPDeep Dive - TinkerDeep Dive - Light-PEFT
Back to Topics
LearnPortfolio CapstonesCapstone: Reproducible ML Study
๐Ÿ“ŠHardEvaluation & Benchmarks

Capstone: Reproducible ML Study

Turn one research paper into a falsifiable, public-safe ML study with paired experiments, uncertainty, reproducible artifacts, and a defensible report.

31 min read
Learning path
Step 88 of 177 in the full curriculum
Capstone: Fine-Tuned ClassifierSentence Embeddings & Contrastive Loss

Personalize this lesson

Adapt explanations and teaching visuals to your background and preferred voice.

A research demo can look convincing and still collapse when someone asks for the exact command, seed, data, or baseline. One chart isn't evidence if nobody can tell which choices produced it.

This capstone turns a small idea into a research artifact another engineer can inspect and rerun. You'll read one paper, lock a falsifiable claim, run a controlled offline study, report uncertainty and failures, then defend the result in ten minutes.

Three-panel paired-seed evidence for reward shaping. A scatter plot places shaped-minus-sparse early-success differences for 24 seeds on a shared axis with zero marking no change, including 19 positive and five negative results. An interval plot places the mean gain of 0.143 inside a 90 percent interval from 0.061 to 0.225. A bar chart compares early success, 0.439 sparse versus 0.582 shaped, and equal final original-reward success of 0.911 for both arms. Three-panel paired-seed evidence for reward shaping. A scatter plot places shaped-minus-sparse early-success differences for 24 seeds on a shared axis with zero marking no change, including 19 positive and five negative results. An interval plot places the mean gain of 0.143 inside a 90 percent interval from 0.061 to 0.225. A bar chart compares early success, 0.439 sparse versus 0.582 shaped, and equal final original-reward success of 0.911 for both arms.
The shaping arm clears the locked early-learning rule on average, but five regressed seeds rule out a uniform-gain claim. Equal final means under original reward keep the conclusion limited to learning speed in this fixture.

The running study asks whether a safe form of reward shaping helps a tiny agent learn faster. Everything runs locally with synthetic data and NumPy. No private logs, live users, paid APIs, or specialized hardware enter the study.

Triage one paper before building

Start with Ng, Harada, and Russell's paper on policy invariance under reward transformations.[1]Reference 1Policy Invariance Under Reward Transformations: Theory and Application to Reward Shapinghttps://wordpress.andrewng.org/index.php/publication/policy-invariance-under-reward-transformations-theory-and-application-to-reward-shaping/ Its main claim is precise enough to test in a small simulator: a potential-based shaping reward can guide learning while preserving optimal policies under the theorem's assumptions.

Don't begin by reproducing every table or proof. First decide whether the paper contains one claim that fits your time, compute, and safety constraints. Keshav's three-pass reading method provides a practical sequence: classify the paper, inspect its evidence, then reconstruct the part you plan to test.[2]Reference 2How to Read a Paperhttps://dl.acm.org/doi/10.1145/1273445.1273458

Use this triage card while reading. Fill it with page or section pointers so a reviewer can trace your interpretation back to source text.

Triage fieldCorridor-study note
problemsparse rewards provide little learning signal before goal completion
paper claimpotential-based shaping preserves optimal policies under stated assumptions
equation to implementF(s,a,sโ€ฒ)=ฮณฮฆ(sโ€ฒ)โˆ’ฮฆ(s)F(s,a,s') = \gamma \Phi(s') - \Phi(s)F(s,a,sโ€ฒ)=ฮณฮฆ(sโ€ฒ)โˆ’ฮฆ(s)
smallest testseven-state corridor with tabular Q-learning
assumption at riskfinal evaluation must use original environment reward
evidence you can reproducelearning speed across fixed simulator seeds
claim you can't makethe method improves deep RL or deployed agents

First pass: classify the claim

Read title, abstract, introduction, headings, figures, conclusion, and references. Write one sentence for problem, method, comparison, and claimed result. If those sentences stay vague, the study isn't ready to design.

For this paper, the method isn't "add helpful rewards." Instead, the method derives a transition reward from a potential function. That distinction separates the policy-invariance theorem from arbitrary bonuses that may change the task.

Stop the first pass with a scope decision: reproduce, extend, or decline. This capstone performs a small empirical check of one implication and adds an uncertainty-focused artifact. It doesn't attempt a full paper reproduction.

Second pass: inspect evidence and assumptions

Study the equation, experimental setup, plots, and failure caveats. Write down what stays constant, what changes, and what the paper measures. Missing implementation detail belongs in an assumptions log, not in a silent guess.

Pay close attention to evaluation reward. A candidate trained with shaped reward can look better if its score includes the extra training bonus. Compare both learned policies using the original environment reward or you have changed the measurement.

Record every adaptation. The corridor, Q-learning hyperparameters, action-slip probability, seed budget, and bootstrap rule are capstone choices rather than claims copied from the paper.

Third pass: reconstruct the test

Explain the shaping equation without looking. Rebuild the smallest environment where moving toward a goal changes potential. Predict what should happen to early learning and final policy before running code.

Then challenge the design. Could the candidate receive more steps, a friendlier random stream, or an easier evaluation? Could a single lucky seed drive the mean? Every plausible shortcut becomes a control, ablation, or stated limitation.

Finish paper_triage.md with three labels: supported by source, study adaptation, and unresolved. That file prevents a plausible implementation detail from turning into a misattributed paper claim.

Turn curiosity into a falsifiable contract

"Does reward shaping help agents learn?" is too broad. It doesn't identify an agent, environment, shaping rule, metric, sample, or outcome that would count against the idea.

A falsifiable hypothesis names an observation that can contradict it. Narrow scope makes the capstone stronger because every noun can become a file, parameter, table column, or assertion.

Use this research question:

In a stochastic seven-state corridor, does potential-based shaping increase tabular Q-learning's first-30-episode goal-reaching rate versus sparse reward, while keeping final greedy-policy success unchanged under original reward?

Lock the contract before inspecting confirmatory results:

Contract fieldLocked value
unit of analysisone paired simulator seed
baselinetabular Q-learning with sparse terminal reward
candidatesame Q-learning plus potential-based shaping during training
primary metricfirst-30-episode success-rate difference, shaped minus sparse
uncertainty90% paired bootstrap interval over seed differences
minimum useful effectmean paired difference at least +0.10
final-policy guardrailabsolute mean final-success difference at most 0.02
confirmatory sampleseeds 0 through 23
stopping rulerun all 24 seed pairs

State the expected result

Prediction comes before output. Expect shaping to improve early goal-reaching because each move changes a distance-based potential. Expect final greedy success to match because the shaping term has the potential-based form studied by Ng and colleagues.[1]Reference 1Policy Invariance Under Reward Transformations: Theory and Application to Reward Shapinghttps://wordpress.andrewng.org/index.php/publication/policy-invariance-under-reward-transformations-theory-and-application-to-reward-shaping/

That expectation isn't permission to hide a miss. It gives reviewers a record of what you believed before seeing confirmatory values. Exploratory explanations can follow, but they need an explicit label.

Write this expected pattern in study_plan.md before running seeds 0 through 23:

  • positive early paired difference
  • interval above zero
  • near-zero final difference
  • timestamp or immutable commit for locked plan

A commit makes later edits visible, but it isn't equivalent to independent preregistration. For formal work, register hypotheses, variables, tests, decision criteria, and exclusions in a timestamped read-only system before collecting confirmatory results.[3]Reference 3Welcome to Registrationshttps://help.osf.io/article/330-welcome-to-registrations

Write the rejection rule

Support the capstone's narrow claim only if the mean early difference is at least +0.10 and the 90% interval's lower bound is above zero. Also require the final-policy guardrail.

Reject the release claim when either requirement fails. A mean of +0.09 is below the declared effect threshold even if its interval is positive. A mean of +0.20 also fails if final original-reward performance shifts beyond the guardrail.

"Inconclusive" can be accurate when interval width leaves multiple practical interpretations. Keep that label distinct from "no effect" and from "the candidate is worse."

Keep the study public-safe

Small research work still needs a data and authority boundary. Synthetic data removes many privacy risks, but a public repository can still leak credentials, copied code, or outputs from proprietary environments.

The corridor generator owns every transition. It doesn't imitate a customer, scrape a service, call an external model, or exercise a live agent. Runs can be shared because their complete input is a tiny configuration plus pseudorandom seed.

Add this boundary to the README before code:

SurfaceIncludedExcluded
datagenerated corridor transitionsuser messages, production logs, private datasets
computelocal CPU and NumPyremote model APIs, paid accelerators
actionsleft/right in simulatorbrowser, shell, account, or network actions
outputsmetrics, tables, plots, manifestssecrets, identifiers, raw third-party content
claimthis simulator and implementationhuman behavior, robotics, deployed-agent safety

Run a secret scanner before publishing. Review generated files for machine paths and usernames. Use an open license only for code and assets you have authority to release.

Build the smallest controlled environment

The corridor has states 0 through 6. Every episode starts at 0; reaching 6 yields environment reward 1; every other transition yields 0. An intended action reverses with probability 0.15, and an episode ends after 12 steps.

Write the environment contract before writing the agent. This prevents reward, reset, or ending-condition changes from entering one experimental arm unnoticed.

Environment fieldLocked contract
observationinteger state in {0, 1, ..., 6}
actions0 = left, 1 = right
resetreturn state 0; select pre-generated tape by seed
transitionmove one cell, clamp at endpoints, reverse intended move on a 0.15 slip
reward1 on first arrival at state 6; otherwise 0
terminatedagent reaches state 6
truncated12 steps elapse without reaching goal
random inputsexploration, action, tie-break, and slip draws indexed by seed, episode, and step
logged outputstate, intended action, realized move, environment reward, termination reason

terminated means task reached goal. truncated means measurement budget ended episode. Keep distinction in run rows because treating timeout as terminal success or bootstrapping through true terminal changes learning target.

Tabular Q-learning stores one value for each state-action pair. During training, it updates the chosen action toward observed reward plus the best estimated next-state value. Sutton and Barto provide the broader reinforcement-learning foundation behind this update.[4]Reference 4Reinforcement Learning: An Introductionhttp://incompleteideas.net/book/the-book-2nd.html

The first diagram follows one environment transition. Both arms then read the same environment reward; only the candidate receives a training-only potential difference before its update. Final evaluation reads the original reward branch for both arms.

Diagram showing Start: state 0, Choose left or right, 15% action reversal?, and Next corridor state. Diagram showing Start: state 0, Choose left or right, 15% action reversal?, and Next corridor state.
Start: state 0, Choose left or right, 15% action reversal?, and Next corridor state.
Diagram showing Environment reward: goal only, Sparse baseline update, Add potential difference, and Shaped candidate update. Diagram showing Environment reward: goal only, Sparse baseline update, Add potential difference, and Shaped candidate update.
Environment reward: goal only, Sparse baseline update, Add potential difference, and Shaped candidate update.

Define distance potential as:

ฮฆ(s)=โˆ’6โˆ’s6.\Phi(s) = -\frac{6-s}{6}.ฮฆ(s)=โˆ’66โˆ’sโ€‹.

States nearer the goal have a larger potential. Candidate training adds:

F(s,a,sโ€ฒ)=ฮณฮฆ(sโ€ฒ)โˆ’ฮฆ(s).F(s,a,s') = \gamma \Phi(s') - \Phi(s).F(s,a,sโ€ฒ)=ฮณฮฆ(sโ€ฒ)โˆ’ฮฆ(s).

With discount 0.95, a move toward the goal usually produces a positive shaping signal. A move away usually produces a negative one. The environment reward hasn't changed; only candidate training receives FFF.

ComponentSparse baselineShaped candidate
states and actionsidenticalidentical
slip tapepairedpaired
Q-learning updateidenticalidentical
environment rewardgoal onlygoal only
training-only additionnoneฮณฮฆ(sโ€ฒ)โˆ’ฮฆ(s)\gamma\Phi(s')-\Phi(s)ฮณฮฆ(sโ€ฒ)โˆ’ฮฆ(s)
final evaluation rewardgoal onlygoal only

Lock controls, seeds, and ablations

Reinforcement-learning measurements can vary with random seeds, environment randomness, codebase, and hyperparameters. Henderson and colleagues show why a single run or loosely standardized baseline can mislead.[5]Reference 5Deep Reinforcement Learning That Mattershttps://ojs.aaai.org/index.php/AAAI/article/view/11694

Pair each baseline run with candidate run under one pre-generated random tape. Tape stores exploration draws, random actions, tie-break draws, and action slips for every episode and step. Indexing by episode and step prevents early episode termination from shifting all later randomness.

Pairing reduces irrelevant seed noise in the difference estimator. It doesn't erase algorithm variability: policies visit different states, so identical tape entries can affect the arms differently.

Separate pilot and confirmatory seeds

Use seeds 900, 901, and 902 to debug code, plots, and manifests. Never include them in confirmatory metrics because you have already observed their behavior.

Use integers 0 through 23 for the locked study. Twenty-four paired seeds fit a laptop capstone and expose heterogeneity, but they aren't a universal sample-size recommendation.

Run every pair. Stopping after ten favorable seeds would make sample size depend on observed outcome. If a run fails mechanically, record failure and rerun policy before looking at aggregate results.

Add controls before interpretation

Zero-potential control sets ฮฆ(s)=0\Phi(s)=0ฮฆ(s)=0. Under the same tape, it must match sparse training exactly. If it doesn't, candidate code changed more than reward.

Original-reward evaluation is another control. Both arms receive identical greedy evaluation slips, and neither receives shaping reward. A result reported only on shaped return fails the measurement contract.

Use a sign-reversed potential only as an exploratory stress test after confirmatory analysis. It may reveal sensitivity to learning dynamics, but it can't retroactively redefine the primary hypothesis.

Plan the ablation matrix

An ablation removes or changes one component to identify which mechanism drives a result. Change one factor per row and preserve all other settings.

IDComparisonOne changed factorPurposeReport class
E0sparse vs zero potentialshaping term fixed at zerocatch implementation driftrequired control
E1sparse vs distance potentialtraining reward onlyconfirm primary claimconfirmatory
E2paired vs shuffled seed labelsanalysis pairingshow pairing's precision effectplanned ablation
E3distance vs reversed potentialpotential signinspect learning sensitivityexploratory

Don't call an unplanned hyperparameter sweep an ablation after choosing its best row. Preserve all runs and label post-result searches exploratory.

Define metrics and uncertainty

For seed iii, let pi,30shapep^{shape}_{i,30}pi,30shapeโ€‹ and pi,30sparsep^{sparse}_{i,30}pi,30sparseโ€‹ be fractions of first 30 training episodes that reach the goal. The paired effect is:

di=pi,30shapeโˆ’pi,30sparse.d_i = p^{shape}_{i,30} - p^{sparse}_{i,30}.diโ€‹=pi,30shapeโ€‹โˆ’pi,30sparseโ€‹.

Primary estimate averages all 24 differences:

dห‰=124โˆ‘i=124di.\bar{d} = \frac{1}{24}\sum_{i=1}^{24}d_i.dห‰=241โ€‹i=1โˆ‘24โ€‹diโ€‹.

That number answers a bounded question about mean early success under the declared seed-generating procedure. It doesn't prove every seed improves, so report all did_idiโ€‹ values and count regressions.

Bootstrap paired seed differences

A bootstrap resamples the 24 paired differences with replacement and recomputes their mean. Repeating that process 10,000 times gives a distribution of plausible mean estimates under the empirical seed sample.

Use fixed bootstrap seed 20260731. Report 5th and 95th percentiles as a 90% interval. Agarwal and colleagues emphasize that finite-run reinforcement-learning comparisons need uncertainty views rather than point estimates alone.[6]Reference 6Deep Reinforcement Learning at the Edge of the Statistical Precipicehttps://proceedings.neurips.cc/paper/2021/hash/f514cec81cb148559cf475e7426eed5e-Abstract.html

The interval isn't a probability that theorem is true, and its coverage doesn't extend automatically beyond this simulator. It quantifies sampling uncertainty over declared seed pairs, conditional on code and study design.

Keep a final-policy guardrail

After 80 training episodes, evaluate each greedy policy for 200 episodes on original reward. Pair evaluation slip tapes by seed. Compute shaped-minus-sparse final-success difference exactly as above.

Require absolute mean final difference at most 0.02. Equal final means don't prove policy invariance generally; they show this finite implementation didn't detect a final-performance change at declared resolution.

Also inspect per-seed final differences. An average near zero can hide equal and opposite failures if candidate helps one region and harms another.

Plan the experiment table before running

A compact experiment table stops notebook state from becoming methodology. Each row names exact config, sample, output, and decision role.

Store the table in study_plan.md and mirror machine-readable fields in configs/study.json. Freeze both in the same commit as the hypothesis.

Use one status vocabulary: planned, running, complete, mechanical_failure, or excluded_by_locked_rule. "Bad result" isn't an exclusion reason.

RunSeedsEpisodesEvaluationOutputDecision role
pilot smoke900-9021020console tracedebug only
zero-potential control0-2380200exact-equality receiptimplementation check
primary paired study0-2380200seed table + bootstrapconfirmatory claim
shuffled-pair analysissame completed rowsnonenoneinterval comparisonplanned ablation
reversed-potential stress0-2380200separate seed tableexploratory appendix

Package an exact repository

A reviewer shouldn't have to guess where hypothesis ends and analysis begins. Keep source, config, immutable run outputs, report, and talk in distinct paths.

This tree is small enough for a public repository while still representing a credible research artifact:

repository-tree.txt
1reproducible-reward-shaping/ 2โ”œโ”€โ”€ README.md 3โ”œโ”€โ”€ LICENSE 4โ”œโ”€โ”€ CITATION.cff 5โ”œโ”€โ”€ pyproject.toml 6โ”œโ”€โ”€ uv.lock 7โ”œโ”€โ”€ study_plan.md 8โ”œโ”€โ”€ paper_triage.md 9โ”œโ”€โ”€ configs/ 10โ”‚ โ””โ”€โ”€ study.json 11โ”œโ”€โ”€ src/ 12โ”‚ โ””โ”€โ”€ corridor_study/ 13โ”‚ โ”œโ”€โ”€ __init__.py 14โ”‚ โ”œโ”€โ”€ environment.py 15โ”‚ โ”œโ”€โ”€ train.py 16โ”‚ โ”œโ”€โ”€ analyze.py 17โ”‚ โ””โ”€โ”€ manifest.py 18โ”œโ”€โ”€ tests/ 19โ”‚ โ”œโ”€โ”€ test_environment.py 20โ”‚ โ”œโ”€โ”€ test_zero_potential.py 21โ”‚ โ””โ”€โ”€ test_manifest.py 22โ”œโ”€โ”€ data/ 23โ”‚ โ””โ”€โ”€ generated/ 24โ”‚ โ””โ”€โ”€ README.md 25โ”œโ”€โ”€ artifacts/ 26โ”‚ โ”œโ”€โ”€ manifest.json 27โ”‚ โ”œโ”€โ”€ runs/ 28โ”‚ โ”‚ โ”œโ”€โ”€ primary_seed_rows.csv 29โ”‚ โ”‚ โ””โ”€โ”€ bootstrap_means.npy 30โ”‚ โ””โ”€โ”€ checksums.sha256 31โ”œโ”€โ”€ report/ 32โ”‚ โ”œโ”€โ”€ report.md 33โ”‚ โ”œโ”€โ”€ figures/ 34โ”‚ โ”‚ โ””โ”€โ”€ paired_seed_delta.svg 35โ”‚ โ””โ”€โ”€ tables/ 36โ”‚ โ””โ”€โ”€ primary_result.csv 37โ””โ”€โ”€ talk/ 38 โ”œโ”€โ”€ outline.md 39 โ””โ”€โ”€ q-and-a.md

Pin environment and entrypoint

Use pyproject.toml plus uv.lock to pin NumPy and development tools. README should name supported Python version and one clean command such as uv run corridor-study --config configs/study.json.

Run from a fresh clone or container. Record operating system, architecture, Python, NumPy, commit, config hash, and wall-clock duration in manifest. The machine identity may remain coarse; hostnames and usernames don't belong in public output.

The Machine Learning Reproducibility Checklist calls for clear model, hyperparameter, seed, environment, and result reporting.[7]Reference 7The Machine Learning Reproducibility Checklisthttps://www.cs.mcgill.ca/~jpineau/ReproducibilityChecklist.pdf A lockfile helps, but complete execution instructions and immutable inputs still matter.

Record data provenance

Synthetic data still needs provenance. Save generator version, seed range, transition rule, slip probability, state count, step cap, and environment source hash.

Don't commit one unexplained CSV and call it generated. data/generated/README.md should state exact command that reconstructs any derived rows and whether tracked output is canonical or disposable.

If you adapt capstone to public dataset later, record original URL, license, version, retrieval date, checksum, preprocessing command, and excluded rows. Never replace original identifier with local filename alone.

Create an artifact manifest

The manifest connects the claim to exact files. JSON stays easy to inspect and hash.

The sample below names identities rather than mutable labels such as latest:

artifacts/manifest.json
1{ 2 "study_id": "corridor-reward-shaping-v1", 3 "git_commit": "7c0ffee", 4 "config_sha256": "<sha256-of-configs-study-json>", 5 "source_sha256": "<sha256-of-src-tree>", 6 "python": "3.12.x", 7 "numpy": "<locked-version>", 8 "confirmatory_seeds": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23], 9 "bootstrap_seed": 20260731, 10 "primary_rows": "artifacts/runs/primary_seed_rows.csv", 11 "report_table": "report/tables/primary_result.csv", 12 "status": "complete" 13}

Add SHA-256 checksums after results become immutable. Verify the checksums in the clean-run script before rendering the report.

CITATION.cff gives software human-readable and machine-readable citation metadata. GitHub can render that file as citation formats for repository visitors.[8]Reference 8About CITATION fileshttps://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-citation-files Use release version or persistent identifier after archive.

Run the miniature study

The complete script below generates paired random tapes, trains both arms, evaluates on original reward, bootstraps paired differences, and prints decision. Its only dependency is NumPy.

Read control points before running: make_tape freezes randomness by episode and step; train changes only reward; evaluate never receives shaping reward; bootstrap samples paired differences.

Run it with uv run reward_shaping_study.py. Expected output follows code.

reward_shaping_study.py
1#!/usr/bin/env -S uv run --script 2# /// script 3# requires-python = ">=3.12" 4# dependencies = ["numpy"] 5# /// 6 7import numpy as np 8 9N_STATES = 7 10GOAL = N_STATES - 1 11GAMMA = 0.95 12ALPHA = 0.35 13EPSILON = 0.20 14TRAIN_EPISODES = 80 15MAX_STEPS = 12 16SEEDS = tuple(range(24)) 17 18def potential(state: int) -> float: 19 return -(GOAL - state) / GOAL 20 21def make_tape(seed: int) -> dict[str, np.ndarray]: 22 rng = np.random.default_rng(seed) 23 shape = (TRAIN_EPISODES, MAX_STEPS) 24 return { 25 "explore": rng.random(shape), 26 "action": rng.integers(0, 2, shape), 27 "tie": rng.integers(0, 2, shape), 28 "slip": rng.random(shape), 29 } 30 31def train(tape: dict[str, np.ndarray], shaped: bool) -> tuple[np.ndarray, np.ndarray]: 32 q = np.zeros((N_STATES, 2), dtype=float) 33 solved: list[int] = [] 34 35 for episode in range(TRAIN_EPISODES): 36 state = 0 37 reached_goal = False 38 39 for step in range(MAX_STEPS): 40 if tape["explore"][episode, step] < EPSILON: 41 action = int(tape["action"][episode, step]) 42 else: 43 best = np.flatnonzero(q[state] == q[state].max()) 44 action = int(best[tape["tie"][episode, step] % len(best)]) 45 46 move = -1 if action == 0 else 1 47 if tape["slip"][episode, step] < 0.15: 48 move = -move 49 50 next_state = int(np.clip(state + move, 0, GOAL)) 51 environment_reward = float(next_state == GOAL) 52 shaping_reward = ( 53 GAMMA * potential(next_state) - potential(state) 54 if shaped 55 else 0.0 56 ) 57 training_reward = environment_reward + shaping_reward 58 target = ( 59 training_reward 60 if next_state == GOAL 61 else training_reward + GAMMA * q[next_state].max() 62 ) 63 q[state, action] += ALPHA * (target - q[state, action]) 64 state = next_state 65 66 if state == GOAL: 67 reached_goal = True 68 break 69 70 solved.append(int(reached_goal)) 71 72 return q, np.asarray(solved) 73 74def evaluate(q: np.ndarray, seed: int, episodes: int = 200) -> float: 75 slips = np.random.default_rng(10_000 + seed).random((episodes, MAX_STEPS)) 76 successes: list[bool] = [] 77 78 for episode in range(episodes): 79 state = 0 80 for step in range(MAX_STEPS): 81 action = int(np.argmax(q[state])) 82 move = -1 if action == 0 else 1 83 if slips[episode, step] < 0.15: 84 move = -move 85 state = int(np.clip(state + move, 0, GOAL)) 86 if state == GOAL: 87 break 88 successes.append(state == GOAL) 89 90 return float(np.mean(successes)) 91 92rows: list[tuple[int, float, float, float, float]] = [] 93for seed in SEEDS: 94 tape = make_tape(seed) 95 sparse_q, sparse_train = train(tape, shaped=False) 96 shaped_q, shaped_train = train(tape, shaped=True) 97 rows.append( 98 ( 99 seed, 100 float(sparse_train[:30].mean()), 101 float(shaped_train[:30].mean()), 102 evaluate(sparse_q, seed), 103 evaluate(shaped_q, seed), 104 ) 105 ) 106 107results = np.asarray(rows, dtype=float) 108early_delta = results[:, 2] - results[:, 1] 109final_delta = results[:, 4] - results[:, 3] 110 111bootstrap_rng = np.random.default_rng(20_260_731) 112bootstrap_means = np.asarray( 113 [ 114 early_delta[ 115 bootstrap_rng.integers(0, len(early_delta), len(early_delta)) 116 ].mean() 117 for _ in range(10_000) 118 ] 119) 120interval_low, interval_high = np.quantile(bootstrap_means, [0.05, 0.95]) 121 122primary_supported = early_delta.mean() >= 0.10 and interval_low > 0.0 123guardrail_passed = abs(final_delta.mean()) <= 0.02 124 125print(f"paired seeds: {len(SEEDS)}") 126print(f"early sparse mean: {results[:, 1].mean():.3f}") 127print(f"early shaped mean: {results[:, 2].mean():.3f}") 128print(f"mean paired delta: {early_delta.mean():+.3f}") 129print(f"90% paired bootstrap CI: [{interval_low:+.3f}, {interval_high:+.3f}]") 130print( 131 "seeds improved / tied / regressed: " 132 f"{int(np.sum(early_delta > 0))} / " 133 f"{int(np.sum(early_delta == 0))} / " 134 f"{int(np.sum(early_delta < 0))}" 135) 136print(f"final sparse mean: {results[:, 3].mean():.3f}") 137print(f"final shaped mean: {results[:, 4].mean():.3f}") 138print(f"mean final delta: {final_delta.mean():+.3f}") 139print(f"decision: {'SUPPORT H1' if primary_supported else 'REJECT H1'}") 140print(f"guardrail: {'PASS' if guardrail_passed else 'FAIL'}")
Output
1paired seeds: 24 2early sparse mean: 0.439 3early shaped mean: 0.582 4mean paired delta: +0.143 590% paired bootstrap CI: [+0.061, +0.225] 6seeds improved / tied / regressed: 19 / 0 / 5 7final sparse mean: 0.911 8final shaped mean: 0.911 9mean final delta: +0.000 10decision: SUPPORT H1 11guardrail: PASS

Read the result without hiding variance

The primary estimate clears the locked +0.10 threshold, and the 90% interval stays above zero. The final original-reward mean is identical at printed precision. Under the declared rule, the fixture supports H1 and passes the guardrail.

Five of 24 seeds regress. That observation belongs next to headline mean because it shows shaping isn't uniformly better. A reviewer can inspect those rows, rerun them, and ask whether one potential interacts poorly with early exploration.

The result supports one sentence: "In this corridor fixture, potential-based shaping increased mean first-30-episode success by 0.143 across 24 paired seeds, with a 90% paired bootstrap interval of [0.061, 0.225], while mean final original-reward success was unchanged."

Separate support from proof

Potential-based shaping theory motivates candidate design, but a tiny experiment doesn't prove the theorem. It verifies implementation behavior under one finite setup.

Likewise, a bootstrap interval isn't a certificate of external validity. New environments, algorithms, reward scales, horizons, and hyperparameters can change learning dynamics.

Use precise verbs: observed, estimated, supported under the locked rule, and didn't detect. Avoid proved, guaranteed, always, and works in production.

Preserve the complete seed table

Report seed, sparse early rate, shaped early rate, paired difference, sparse final rate, shaped final rate, and run status. Sort by seed, not performance.

Keep failed mechanical runs in the ledger with their errors. If the locked rerun rule permits replacement, preserve the first failed attempt and link the replacement rather than overwriting it.

The aggregate table should point to the row-table checksum. A screenshot alone can't support reanalysis.

Treat negative results as artifacts

A rejected hypothesis isn't failed capstone. Hidden rejection is. Strong artifact makes negative result easy to understand, rerun, and extend.

Keep report structure unchanged when claim fails. Replace celebratory language with declared decision, uncertainty, likely explanations, and next discriminating study. Don't quietly change metric or seed set.

Use this diagnosis table after locked analysis:

SymptomPlausible causeHonest response
interval crosses zeroseed budget too small or effect unstablereport inconclusive result and wider interval
mean below +0.10effect smaller than useful thresholdreject practical claim even if sign is positive
final guardrail failsreward or terminal handling changed task behaviorhold candidate and inspect implementation
a few extreme seeds dominateunstable exploration or environment interactionshow seed distribution and robust summary
zero-potential control differscode paths aren't identicalstop analysis and fix experiment harness
clean clone can't runmissing dependency, data, or commandrepair artifact before sharing report

A negative result can still narrow future work. For example, a wide interval may justify more seeds; a stable null effect may rule out one potential; guardrail failure may expose incorrect terminal shaping.

Mark post-result hypotheses exploratory. "Seed 6 regressed because early slips trapped policy" can become next registered study, but it isn't confirmed by same observed seed trace.

Produce a figure, table, and report

A research artifact needs three aligned views. The table preserves exact values, the figure makes the distribution visible, and the report connects evidence to the claim. All three must derive from the same immutable rows.

Generate the table and figure from artifacts/runs/primary_seed_rows.csv. Don't type result numbers into plot code or the report by hand. Add a test that the report-table hash matches the manifest.

Use accessible colors plus sign and position. Negative seed differences need a label or distinct shape so interpretation doesn't depend on red-green perception.

Required table

report/tables/primary_result.csv should contain one row per arm plus paired delta summary:

MetricSparseShapedPaired difference
first-30 success0.4390.582+0.143
90% intervaln/an/a[+0.061, +0.225]
improved/tied/regressed seedsn/an/a19/0/5
final original-reward success0.9110.911+0.000

Required figure

Show every seed difference on common x-axis with visible zero line. Add paired mean and interval, then align early and final arm means on same zero-to-one scale.

Caption should state inference rather than repeat title. Mention five negative seeds and equal final means. Avoid a bar chart that hides seed distribution.

Export SVG for report and PNG for slides. Save plotting command and source hash in manifest.

Required report

Keep report concise enough to review in one sitting:

  1. Abstract with scope and decision.
  2. Paper claim and study adaptation.
  3. Locked hypothesis, expected result, and rejection rule.
  4. Environment, baseline, candidate, controls, and seed plan.
  5. Primary table, figure, uncertainty, and negative seeds.
  6. Ablations and mechanical checks.
  7. Limitations, negative findings, and next study.
  8. Reproduction command, manifest, license, and citation.

State deviations from plan in their own table. none is acceptable only after checking commit diff between locked plan and final config.

Write limitations that constrain the claim

Limitations aren't a ceremonial paragraph. Each should identify unsupported inference and, when possible, experiment that would test it.

This capstone has at least six:

LimitationUnsupported inferenceUseful next study
one seven-state corridorshaping helps other environmentsadd branching grid and delayed traps
tabular Q-learning onlyeffect transfers to neural agentspreregister small function-approximation study
one potentialany potential speeds learningcompare several locked potential families
one hyperparameter setresult is tuning-robustcrossed seed-by-hyperparameter design
24 seedseffect estimate is highly preciseplan seed count from target interval width
synthetic taskdeployed-agent value or safetyno such claim without separate governed study

Also state the theorem's boundary. Potential-based shaping preserves optimal policies under the assumptions in the source formulation; a finite implementation can still be wrong, undertrained, or measured on the wrong reward.

Don't describe public-safe synthetic setup as representative of users. Its strength is auditability, not realism.

Submit four milestones

Each submission should be reviewable before the next stage begins. A milestone is an evidence package, not a calendar date.

Keep reviewer feedback in reviews/ or issue tracker. When feedback changes locked plan, record amendment before confirmatory run.

Use these four submissions:

Milestone 1: paper and study contract

Submit paper_triage.md, study_plan.md, source links, one-paragraph scope, falsifiable hypothesis, expected result, rejection rule, public-safety boundary, and limitations forecast.

Reviewer should trace shaping equation to paper and distinguish paper claims from study adaptations. No confirmatory results should exist yet.

Exit criterion: another engineer can predict which output supports, rejects, or leaves claim inconclusive.

Milestone 2: simulator and baseline

Submit exact repository skeleton, environment tests, sparse Q-learning baseline, pilot-only run, zero-potential equality test, config schema, dependency lock, and clean-run command.

Reviewer should run seed 900 and inspect one episode trace. They should confirm goal reward, slip behavior, terminal handling, and 12-step cap.

Exit criterion: baseline and zero-potential control are bit-for-bit equal under same tape.

Milestone 3: confirmatory evidence

Submit immutable 24-seed row table, paired bootstrap output, experiment table, manifest, checksums, primary figure, planned ablations, and deviation log.

Reviewer should reconstruct headline values from row table and rerun at least one seed pair. Mechanical failures must remain visible.

Exit criterion: decision follows locked rule without manual number edits.

Milestone 4: public artifact and defense

Submit final report, exact reproduction instructions, license, CITATION.cff, archived release identifier if available, ten-minute talk outline, Q&A sheet, and artifact review checklist.

Reviewer should start from clean clone and produce primary table. They should also identify one unsupported claim and verify report doesn't make it.

Exit criterion: independent reviewer can exercise artifact and explain evidence, limits, and next study.

Prepare a ten-minute talk

A short technical talk tests whether your research decisions form a coherent story. Ten minutes leaves no room for every implementation detail, so use an evidence hierarchy rather than a file tour.

Practice with a timer and one backup slide per likely challenge. The main deck should fit seven slides and reserve at least two minutes for questions.

Use this pacing:

TimeSlideJob
0:00-0:45problemsparse reward and narrow corridor question
0:45-1:45paper claimpotential-based shaping and assumption boundary
1:45-3:00hypothesisprimary effect, expected pattern, rejection rule
3:00-4:30designbaseline, candidate, paired tapes, seeds, controls
4:30-6:15evidenceseed plot, interval, five regressions, final guardrail
6:15-7:15failure checkszero potential, original-reward evaluation, deviations
7:15-8:00limitationsclaim boundary and next study
8:00-10:00Q&Adefend choices with artifact links

Build Q&A from attack surfaces

Write the answers before the presentation. Each answer should point to an evidence file or admit unresolved uncertainty.

QuestionStrong answer shape
Why 24 seeds?bounded laptop budget; report interval width; no claim of universal adequacy
Why 90% interval?locked before results for capstone sensitivity; show exact choice; alternative belongs appendix
Why mean?primary estimand was paired mean; whole distribution and regression count remain visible
Did shaping change task?training reward differed; both final policies evaluated on original reward; guardrail passed
Why can five seeds regress?method changes learning dynamics; mean claim isn't per-seed guarantee
Does theorem prove experiment?no; theorem motivates form, while artifact checks finite implementation
Can result transfer to agents?no; corridor, tabular learner, and synthetic data bound claim
What would falsify next idea?preregister environment family and potential comparison with rejection thresholds

Don't answer every challenge with "more data." Some failures demand corrected control, better estimand, or narrower claim.

Review artifact like an outsider

Reproducibility asks whether another team can obtain result using same artifacts and setup; replicability asks about independent artifacts under ACM's current terminology.[9]Reference 9Artifact Review and Badginghttps://www.acm.org/publications/policies/artifact-review-and-badging-current This capstone targets repeatability first and provides enough documentation for an independent reproducibility attempt.

ACM's functional artifact criteria emphasize documented, consistent, complete, exercisable artifacts with verification and validation evidence.[9]Reference 9Artifact Review and Badginghttps://www.acm.org/publications/policies/artifact-review-and-badging-current Use those words as review questions, not as a badge claim.

FAIR principles add findability, accessibility, interoperability, and reuse to data stewardship.[10]Reference 10The FAIR Guiding Principles for scientific data management and stewardshiphttps://www.nature.com/articles/sdata201618 A public repository, open formats, machine-readable manifest, license, and citation metadata help. They don't replace executable validation.

Outsider checklist

  • Can reviewer find hypothesis and locked commit?
  • Can reviewer install environment without global packages?
  • Can reviewer regenerate synthetic rows from config and seeds?
  • Can reviewer verify source, config, and result checksums?
  • Can reviewer recompute table and figure from same rows?
  • Can reviewer see failed runs and plan deviations?
  • Can reviewer distinguish confirmatory from exploratory work?
  • Can reviewer state exactly where claim stops?
  • Can reviewer cite release and understand license?
  • Can reviewer reproduce primary decision from clean clone?

If any answer is "no," the artifact isn't ready. Fix the package before polishing the talk.

Defend bounded evidence

You can move from one paper claim to a bounded empirical question without pretending a small study reproduces an entire field. You can state expected result and rejection rule before confirmatory output, then preserve negative seeds and failed hypotheses.

You can also separate algorithm change from random noise through paired tapes, report bootstrap uncertainty, and keep final evaluation on original task. Those habits apply to model training, retrieval, evaluators, and agent benchmarks.

Ship evidence another engineer can inspect: source, lockfile, config, seed table, manifest, figure, report, limitations, talk, and Q&A. The artifact is credible because the claim remains smaller than the evidence.

Complete the lesson

Mastery Check

Answer every question, then check your score. Score 75% or higher to mark this lesson complete.

1.Which research question is falsifiable enough for the capstone?
2.Why must final evaluation use original environment reward for both arms?
3.What does zero-potential control test?
4.Why are pilot seeds 900 through 902 excluded from confirmatory table?
5.The early mean difference is +0.09 and its 90% interval is [+0.03, +0.15]. What does locked rule say?
6.Why report five regressed seeds when paired mean supports H1?
7.Which file best links published claim to exact code, config, seeds, and result files?
8.A reversed-potential run was conceived after inspecting negative seeds. How should it be reported?
9.Which ten-minute talk claim stays within evidence?

9 questions remaining.

Next Step
Continue to Sentence Embeddings & Contrastive Loss

You can now turn a paper claim into controlled evidence; next you'll examine how contrastive objectives shape reusable sentence <span data-glossary="vector">vectors</span> and how to evaluate those representations without losing this experimental discipline.

PreviousCapstone: Fine-Tuned Classifier
Share this article
XFacebookLinkedInBlueskyRedditHacker NewsEmail
References

Policy Invariance Under Reward Transformations: Theory and Application to Reward Shaping

Ng, A. Y., Harada, D., and Russell, S. ยท 1999 ยท ICML 1999

How to Read a Paper

Keshav, S. ยท 2007 ยท ACM SIGCOMM Computer Communication Review

Welcome to Registrations

Open Science Framework ยท 2026

Reinforcement Learning: An Introduction

Sutton, R. S. and Barto, A. G. ยท 2018 ยท MIT Press

Deep Reinforcement Learning That Matters

Henderson, P., Islam, R., Bachman, P., Pineau, J., Precup, D., and Meger, D. ยท 2018 ยท AAAI 2018

Deep Reinforcement Learning at the Edge of the Statistical Precipice

Agarwal, R., Schwarzer, M., Castro, P. S., Courville, A. C., and Bellemare, M. G. ยท 2021 ยท NeurIPS 2021

The Machine Learning Reproducibility Checklist

Pineau, J., et al. ยท 2021

About CITATION files

GitHub ยท 2026

Artifact Review and Badging

Association for Computing Machinery ยท 2026

The FAIR Guiding Principles for scientific data management and stewardship

Wilkinson, M. D., et al. ยท 2016 ยท Scientific Data

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.