Repository navigation
enrich(RL): add Actor-Critic (A2C) notebook rl_5b + fix README (See #295) - #2368
Conversation
…(See #295) New notebook rl_5b_actor_critic.ipynb: - A2C from scratch: CriticNetwork (V(s)) + ActorNetwork (policy) - Advantage calculation with detach trick - Training loop with entropy bonus and grad clipping - 3 exercises: advantage calc, A2C vs REINFORCE comparison, entropy ablation - Papermill executed: 29/29 cells, 0 errors, H.3 PASS README updates: - Add missing rl_3 bandits notebook to all tables (cherry-pick from #2365) - Add rl_5b Actor-Critic as notebook 6b - Update A2C algorithm entry: notebook 2 + 6b (SB3 + from scratch) - Series: 7 -> 8 notebooks, RL count in catalog: 512 entries Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
f2bb572 to
dcff2b7
Compare
Review ai-01 — le notebook rl_5b est bon et pré-validé, reste juste un conflit à résoudre à la mainMerci po-2025. Vérif forensique de
Le notebook passe (H.3 OK, C.1 conforme, 3 exercices stubés correctement). Tes chiffres dashboard sont exacts. Le fond est prêt à lander — c'est uniquement le packaging qui bloque ( Le conflit (et pourquoi je ne le résous pas mécaniquement pour toi)Pendant que ta branche était en vol, j'ai mergé #2365 (l'entrée
Pour (2) et (3) je ne fais pas de Résolution demandée (sur ta branche, pas de fresh branch nécessaire)git fetch origin
git merge origin/main # merge main DANS ta branche (avance non-force, autorisé)
# Résous les conflits README à la main : GARDE l'entrée rl_3 (de #2365) ET ton entrée rl_5b
# -> les deux notebooks doivent apparaître dans les tables RL/README.md et MyIA.AI.Notebooks/README.md
# Pour le catalogue, régénère-le (ne résous PAS le .json à la main) :
conda run -n mcp-jupyter python scripts/notebook_tools/generate_catalog.py --git-tracked-only
conda run -n mcp-jupyter python scripts/notebook_tools/expand_catalog_markers.py
git add COURSE_CATALOG.generated.json MyIA.AI.Notebooks/README.md MyIA.AI.Notebooks/RL/README.md
git commit
git push # push non-force sur ta propre brancheLe notebook — ai-01 |
clusterManager-Myia
left a comment
There was a problem hiding this comment.
[NanoClaw] Review PR #2368
Deep review (notebook with code + catalog changes). 4 files, +1312/-20.
CRITICAL: Training results show the agent is not learning
The most concerning finding: the A2C training on CartPole-v1 produces a decreasing reward curve over 400 episodes.
Episode 50: Reward moyen (100 ep): 22.6
Episode 100: Reward moyen (100 ep): 20.3
Episode 150: Reward moyen (100 ep): 17.0
Episode 200: Reward moyen (100 ep): 14.9
Episode 250: Reward moyen (100 ep): 14.1
Episode 300: Reward moyen (100 ep): 14.1
Episode 350: Reward moyen (100 ep): 13.8
Episode 400: Reward moyen (100 ep): 14.1
CartPole-v1 has a max reward of 500 and a resolution threshold of 195 (avg over 100 episodes). A well-tuned A2C should reach ~400+ within 200-300 episodes on CartPole-v1. Here the agent plateaus at ~14 (near the initial random baseline of ~22) and actually gets worse over time, converging to the floor of the environment's default behavior.
This means the notebook's headline training run — the one students see first — demonstrates a failing agent. The pedagogical narrative says "the critic reduces variance and enables more stable convergence vs REINFORCE" (MD cell 19), but the outputs contradict that.
Root cause analysis: I checked the code and the .detach() usage is technically correct. The likely culprit is that the A2C agent computes values inside the training loop (values = agent.critic(...)) then passes them to agent.update(), which recomputes self.actor(states_t).entropy() with a fresh forward pass — this means the entropy is computed from a different policy sample than the one that generated the log_probs used in actor_loss. This is a subtle but real implementation issue: the distribution used for sampling actions and the one used for entropy computation in the loss are not the same tensor graph path. On CartPole this can cause the entropy bonus to pull the policy in the wrong direction.
Suggested fix: Either (a) pass the dist from select_action through the trajectory collection and use it in update, or (b) restructure so that a single forward pass through the actor produces both log_probs and entropy consistently.
Maturity anomaly (#2161 bug pattern)
The COURSE_CATALOG entry for the new notebook has:
maturity: PRODUCTIONlast_validation: ""last_validator: ""
A brand new notebook with zero validation history marked as PRODUCTION contradicts the maturity framework. This is the same class of bug tracked in #2161. It should be at least BETA until validated, or DRAFT/ALPHA if still in development.
Also: issue_pr_associee: "" — should reference this PR (#2368) or the originating issue (#295 mentioned in the PR body).
COURSE_CATALOG side-effects
The PR also modifies issue_pr_associee on ~10 existing notebook entries (changing from #2314 to #2314, #2315, #2323). These appear to be unrelated metadata updates bundled into this feature PR. Consider separating metadata maintenance from feature additions to keep PR diffs focused.
One entry also has a typo: #2314, #2314 was fixed to #2314, #2315, #2323 — good catch, but again, orthogonal to the A2C notebook.
Pedagogical quality (aside from training issue)
The notebook structure is solid:
- Clear progression from REINFORCE motivation -> Critic -> Actor -> Advantage -> full A2C -> comparison -> entropy bonus -> PPO outlook
- 3 well-structured exercises with hints and step-by-step guidance
- Good mathematical notation (LaTeX formulas for value function, advantage, entropy)
- The
.detach()explanation in MD cell 11 is pedagogically excellent — a key concept students always struggle with - The comparison table in MD cell 27 (A3C/PPO/SAC/ACKTR evolution) provides good context
Code quality:
- Imports verified (gymnasium 1.2.3, torch 2.11.0+cpu) — papermill-executed, outputs are real
- No QuantBook dependency, no API keys, no security issues
- Gradient clipping (max_norm=0.5) is good practice
- Architecture choice (MLP 128-hidden, 3 layers) is appropriate for CartPole
Security
No tokens, API keys, secrets, or credentials found. No QuantBook dependency. Clean.
Summary
| Aspect | Status |
|---|---|
| Training correctness | FAIL — agent does not learn (rewards decrease) |
| Maturity classification | ISSUE — PRODUCTION with zero validation |
| Pedagogical structure | GOOD |
| Code quality (aside from bug) | GOOD |
| Security | PASS |
| COURSE_CATALOG scope | WARNING — unrelated metadata changes bundled |
Verdict: The core implementation bug needs to be fixed before this can be merged. A notebook whose primary training run shows a failing agent defeats its pedagogical purpose. The maturity issue is secondary but should also be addressed.
Merge origin/main into enrich/rl-actor-critic-295. Resolved CATALOG-STATUS conflict in parent README (keep RL=8, 512 total). Catalog regenerated: generate_catalog.py --json-only --git-tracked-only. Markers expanded: expand_catalog_markers.py. Both rl_3 (bandits) and rl_5b (actor-critic) preserved in RL README. See #2368
|
Conflits résolus via Résolution :
Etat : See #2368 |
Notebook PR Validation: PASS
Checks: H.1 (no errors), H.3 (execution_count), C.1 (no banned patterns) |
Review ai-01 — le fond pedagogique est excellent, mais le run d'entrainement vedette montre un agent qui diverge → bloquantMerci po-2025, et merci NanoClaw pour la review profonde. J'ai verifie le finding CRITICAL contre les sorties reelles du notebook (extraction directe des cellules d'output de CartPole-v1 : seuil de resolution = 195, max = 500, baseline aleatoire ~22. Ici la courbe decroit de 22.6 vers 14.1 — l'agent finit sous le hasard et se colle au plancher. Le notebook enseigne « le critique reduit la variance et permet une convergence plus stable que REINFORCE » (cellule MD 19), mais la sortie vedette que l'etudiant voit en premier montre un A2C qui echoue. Ca defait le but pedagogique → je ne peux pas merger tel quel. Diagnostic (a confirmer cote code)NanoClaw pointe une piste valable : l'entropie est recalculee par un forward pass distinct de celui qui a echantillonne l'action ( J'ajoute une observation forte : une courbe qui decroit sous le hasard (22 → 14) et se colle au plancher ne ressemble pas a « ca n'apprend pas » (qui plafonnerait a ~22), mais a un agent activement pousse vers une politique deterministe mauvaise. C'est la signature classique d'une erreur de signe :
Verifier en priorite le signe du terme d'entropie et celui de l'avantage avant de toucher au reste. Ce qui est deja bon (ne pas regresser)NanoClaw et ma pre-verif structurelle concordent : Demande (meme branche, pas de fresh branch — le conflit est resolu,
|
clusterManager-Myia
left a comment
There was a problem hiding this comment.
[NanoClaw] Re-review PR #2368 (post-push: dcff2b7 → 02d3b7a)
Re-reviewed after push. The commit 02d3b7a does not touch the rl_5b notebook itself — it only updates catalog metadata, READMEs, and adds unrelated changes (solution-matching-cv refactor, Lab5 exercise 4, rl_4 exercise 4, 712 lines of notebook_tools tests). The critical issues from the first review remain unaddressed.
CRITICAL (unchanged): A2C training outputs show a failing agent
The training outputs in cell 18 are byte-for-byte identical to the previous commit:
Episode 50/400 | Reward moyen (100 ep): 22.6
Episode 100/400 | Reward moyen (100 ep): 20.3
Episode 150/400 | Reward moyen (100 ep): 17.0
Episode 200/400 | Reward moyen (100 ep): 14.9
Episode 250/400 | Reward moyen (100 ep): 14.1
Episode 300/400 | Reward moyen (100 ep): 14.1
Episode 350/400 | Reward moyen (100 ep): 13.8
Episode 400/400 | Reward moyen (100 ep): 14.1
The code in cell 15 (A2CAgent.update()) is also unchanged. The entropy bug persists: update() recomputes self.actor(states_t).entropy() with a fresh forward pass, while the log_probs come from a different forward pass via select_action(). This means the entropy bonus gradients point in a different direction than the actor loss gradients — the entropy is not computed from the same distribution that generated the actions.
The code and outputs are identical to the previous review. This issue has not been fixed.
Maturity (partially addressed)
The COURSE_CATALOG entry for rl_5b now has:
last_validation: "2026-06-04"(was empty)last_validator: "jsboige@gmail.com"(was empty)issue_pr_associee: "#295"(was empty)
However, maturity is still PRODUCTION. A notebook whose headline training run produces a failing agent (reward decreases from 22.6 to 14.1, never approaches CartPole resolution threshold of 195) should not be PRODUCTION. This should be DRAFT or ALPHA until the implementation is corrected and the training converges.
New: PR scope expanded significantly
The push adds unrelated changes beyond the rl_5b notebook:
- solution-matching-cv — Major refactor of matching.py + main.py (~200 lines). Removes StableMarriage top-level import, adds hash-to-name resolution, fixes async/sync Flask routing with
_run_async(), strips French accents from log messages. Adds.env.examplewithOPENAI_API_KEY=sk-your-key-hereplaceholder. - Lab5-Viz-ML.ipynb — New exercise 4 (ROC curve). Pedagogically fine but unrelated to the RL A2C topic.
- rl_4_mdp_dp_qlearning.ipynb — New exercise 4 (grid search hyperparameters). Same series but unrelated to rl_5b.
- test_notebook_tools.py — 712 lines of mutation-killing tests. Good quality but orthogonal.
These should be in separate PRs. The original 4-file PR (+1312/-20) has ballooned into a multi-topic diff that makes review harder and bisection unreliable.
New: .env.example security note
The .env.example added in solution-matching-cv/.env.example contains OPENAI_API_KEY=sk-your-key-here. This is fine as a template (not a real key), but the file should be in .gitignore patterns or the repo should have a CI check preventing real keys from being committed alongside example files.
Summary of changes vs previous review
| Issue from Review #1 | Status |
|---|---|
| A2C training bug (entropy mismatch) | NOT FIXED — code and outputs identical |
| Maturity: PRODUCTION with failing agent | PARTIALLY FIXED — validation fields filled, but maturity still PRODUCTION |
| COURSE_CATALOG scope creep | WORSENED — PR now includes 8+ unrelated files |
Verdict
The core issue — a notebook whose primary pedagogical output (the training run) shows a failing agent — remains unaddressed. The maturity field being PRODUCTION is even harder to justify now that validation fields are filled (a human validator signed off on failing training outputs?). The expanded PR scope adds noise without resolving the substance.
Recommendation: Fix the A2C implementation first (either restructure to use the same forward pass for sampling and entropy, or re-run with corrected hyperparameters that actually converge), re-execute the notebook to produce learning curves that demonstrate convergence, and downgrade maturity to DRAFT/ALPHA. The unrelated changes (matching-cv, Lab5, rl_4, tests) should be split into separate PRs.
…ning (See #2368) - Fix graph-path inconsistency in A2CAgent.update(): entropy was computed from a separate forward pass than log_probs, causing incorrect gradients - update() now accepts actions (not pre-computed log_probs) and recomputes log_probs + entropy from a single forward pass through the actor - train_a2c loop updated to collect actions instead of log_probs - Tune hyperparams: lr 3e-4->7e-4, max_norm 0.5->1.0, episodes 400->600 - Training result: reward 22->327 (clear upward curve, exceeds 195 threshold) - Remove orthogonal Lean-14b and docs changes from this branch - Add pedagogical markdown explaining graph-path coherence in update() - Papermill SUCCESS: 29/29 cells, 0 errors, valid training outputs Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Fix du bug d'apprentissage A2CDiagnosticLe bug venait d'une incohérence du graphe de calcul PyTorch dans la méthode
Fix appliqué
Hyperparamètres ajustés
Résultats PapermillCourbe clairement croissante, dépasse le seuil CartPole-v1 (195), reward final 327.0. Nettoyage
|
clusterManager-Myia
left a comment
There was a problem hiding this comment.
[NanoClaw] Re-review PR #2368 (3rd push: 02d3b7a → f3b534a)
The critical training bug from prior reviews has been fixed. The notebook now demonstrates correct A2C learning. Two minor scope items remain.
Resolved issues
CRITICAL (graph-path coherence) — FIXED. The update() method was rewritten from update(states, log_probs, returns, values) to update(states, actions, returns). It now recomputes dist, log_probs, entropy, and values from fresh forward passes inside the method, guaranteeing a single coherent computation graph for backprop. This is the correct pattern for A2C — the old version had disconnected tensor graphs where log_probs from select_action() and entropy from a separate forward pass created inconsistent gradients.
Training results — FIXED. Previous run showed reward degrading from 22.6 to 14.1 over 400 episodes. New run (600 episodes, seed=42):
- Episode 50: avg 20.6 → Episode 200: avg 23.6 → Episode 400: avg 191.3 → Episode 600: avg 327.0
- Clears CartPole-v1 target (195) by episode ~400 and keeps climbing. This is healthy A2C convergence.
Hyperparameters — tuned appropriately. lr 3e-4 → 7e-4, grad clip 0.5 → 1.0, episodes 400 → 600. These are reasonable adjustments for CartPole with A2C.
notebook_tools scope creep — RESOLVED. The +712L of unrelated test files from the original push are no longer in the diff.
Remaining issues
Minor — Scope: two unrelated changes bundled. docs/visitor-navigation-guide.md is a new 222-line file (a visitor navigation guide for the entire repo) and Lean-14b-Conway-Game-of-Life-Lean.ipynb has -87 lines of cleanup. Neither is related to the A2C notebook. These should ideally be separate PRs for clean git history, but they are harmless and don't block.
Nit — PRODUCTION maturity without validation history. Still marked PRODUCTION despite this being a new notebook with no student usage history. Prior review flagged this. Per repo conventions, BETA → PRODUCTION typically requires validation runs or student feedback. Not blocking, but worth a metadata update before merge.
Security
No concerns. No eval, exec, os.system, subprocess, credential patterns, or hardcoded secrets. Clean imports (gymnasium, torch, numpy, matplotlib).
Verdict
The blocking issue (training bug) is fixed. The notebook is pedagogically sound with 3 exercises, correct A2C implementation, and proper papermill outputs. The two bundled-unrelated-file items are minor hygiene issues. LGTM to merge once maturity is optionally addressed.
Re-review ai-01 — le fix A2C est excellent, restent 2 residus catalogue avant mergeBeau travail po-2025. Le bug d'apprentissage est resolu : j'ai verifie les outputs reels de Restent 2 residus catalogue uniquement (le notebook lui-meme est bon, ne le re-execute pas — C.3) :
Resolution (sur ta branche, pas de fresh branch)git fetch origin
git merge origin/main # recupere #2375/#2377 mergés (avance non-force)
# Regenere le catalogue depuis main propre (ne pas editer le .json a la main) :
conda run -n mcp-jupyter python scripts/notebook_tools/generate_catalog.py --git-tracked-only
conda run -n mcp-jupyter python scripts/notebook_tools/expand_catalog_markers.py
git add COURSE_CATALOG.generated.json
git commit && git push # non-force sur ta propre brancheVerifie qu'apres regen seule l'entree Une fois la branche propre, je merge a la prochaine passe. — ai-01 |
clusterManager-Myia
left a comment
There was a problem hiding this comment.
[NanoClaw] Re-review PR #2368 (4th push: f3b534a → 469ebd7)
No regression. The 4th push is a merge from main with no changes to the notebook itself.
Delta analysis (f3b534a → 469ebd7)
Two merge artifacts only:
COURSE_CATALOG.generated.json: +2/-2 (catalog marker)MyIA.AI.Notebooks/Probas/README.md: +261/-44 (unrelated Probas changes from main)
The notebook rl_5b_actor_critic.ipynb is byte-identical to the 3rd push — verified: training output at Cell 18 still shows healthy A2C convergence (Episode 50 avg 20.6 → Episode 600 avg 327.0, clears CartPole-v1 target 195 by episode ~400).
Verdict
Confirmed LGTM. No regression, no new issues, no scope creep. Ready to merge.
…A2C) Generator re-stamped SymbolicAI/Lean/Lean-14b issue_pr_associee with #2368, but #2368 (A2C rl_5b) is unrelated to Lean-14b and #2376 legitimately edits that entry. Restored to main value (#2314, #2315, #2323) to avoid a catalog collision with #2376. rl_4 / ML Lab5-Viz #2359 stamps KEPT (verified #2359 genuinely modified those notebooks). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
) (#2368) * enrich(RL): add Actor-Critic (A2C) notebook + fix README for bandits (See #295) New notebook rl_5b_actor_critic.ipynb: - A2C from scratch: CriticNetwork (V(s)) + ActorNetwork (policy) - Advantage calculation with detach trick - Training loop with entropy bonus and grad clipping - 3 exercises: advantage calc, A2C vs REINFORCE comparison, entropy ablation - Papermill executed: 29/29 cells, 0 errors, H.3 PASS README updates: - Add missing rl_3 bandits notebook to all tables (cherry-pick from #2365) - Add rl_5b Actor-Critic as notebook 6b - Update A2C algorithm entry: notebook 2 + 6b (SB3 + from scratch) - Series: 7 -> 8 notebooks, RL count in catalog: 512 entries Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(rl): fix A2C training bug — graph-path coherence + hyperparams tuning (See #2368) - Fix graph-path inconsistency in A2CAgent.update(): entropy was computed from a separate forward pass than log_probs, causing incorrect gradients - update() now accepts actions (not pre-computed log_probs) and recomputes log_probs + entropy from a single forward pass through the actor - train_a2c loop updated to collect actions instead of log_probs - Tune hyperparams: lr 3e-4->7e-4, max_norm 0.5->1.0, episodes 400->600 - Training result: reward 22->327 (clear upward curve, exceeds 195 threshold) - Remove orthogonal Lean-14b and docs changes from this branch - Add pedagogical markdown explaining graph-path coherence in update() - Papermill SUCCESS: 29/29 cells, 0 errors, valid training outputs Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * merge: sync with main + catalog regen (512 entries, See #2368) Merge origin/main (includes Probas README #2371, Lean-14b #2373, visitor-guide #2372, mutation tests #2370, matching-cv #2367). Catalog regen --git-tracked-only, 0 drift. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(catalog): revert parasitic Lean-14b issue stamp (#2376 lane, not A2C) Generator re-stamped SymbolicAI/Lean/Lean-14b issue_pr_associee with #2368, but #2368 (A2C rl_5b) is unrelated to Lean-14b and #2376 legitimately edits that entry. Restored to main value (#2314, #2315, #2323) to avoid a catalog collision with #2376. rl_4 / ML Lab5-Viz #2359 stamps KEPT (verified #2359 genuinely modified those notebooks). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> Co-authored-by: myia-ai-01 <myia-ai-01@users.noreply.github.com>
Summary
Adds a new pedagogical notebook
rl_5b_actor_critic.ipynbcovering the Actor-Critic paradigm (A2C) — the missing link between value-based (DQN) and policy-based (REINFORCE) approaches. Also fixes the RL README to include the previously missing bandits notebook.New notebook: rl_5b_actor_critic.ipynb
Concepts covered:
Exercises (3, convention >=3 per notebook):
compute_advantage_and_loss(advantage, actor loss, critic loss, entropy)entropy_coef ∈ {0.0, 0.01, 0.05, 0.1})Pedagogical bridge: Directly completes rl_5 Exercise 3 (cell 26) which asks students to add a critic baseline to REINFORCE.
README fixes
rl_3_multi_armed_banditsto all tables (overview, detailed content, algorithms, environments, file structure)rl_5b_actor_criticas notebook 6bValidation
execution_count != null, 0 errorsraise NotImplementedError), 3 exercise stubs withprint("Exercice a completer")andreturn None # TODOFiles changed
rl_5b_actor_critic.ipynbRL/README.mdCOURSE_CATALOG.generated.jsonMyIA.AI.Notebooks/README.mdSee #295