Skip to content

enrich(RL): add PPO from scratch notebook (See #295, #1454) - #2385

Merged
jsboige merged 6 commits into
mainfrom
enrich/rl-ppo-from-scratch-295
Jun 5, 2026
Merged

jsboige merged 6 commits into
mainfrom
enrich/rl-ppo-from-scratch-295

Conversation

@jsboige

@jsboige jsboige commented Jun 4, 2026

Copy link
Copy Markdown
Owner

Summary

Add notebook rl_5c_ppo_from_scratch.ipynb to the RL series — PPO (Proximal Policy Optimization) implemented from scratch in PyTorch.

Changes

  • New notebook rl_5c_ppo_from_scratch.ipynb: 26 cells (10 code, 16 markdown), 3 exercises
  • README RL: Updated to 9 notebooks, added 6c entry, parcours diagram, algorithmes table, environnements table
  • Catalog: 512 → 513 entries

Notebook content

Section Content
Clipped surrogate Probability ratio, clipped objective, visualization
PPO Agent Full implementation with mini-batch updates + epochs
GAE Generalized Advantage Estimation (lambda=0.95)
PPO vs A2C Stability and sample efficiency comparison

Exercises (3, convention #2161)

  1. Clipped surrogate — implement clipped_surrogate_loss function
  2. GAE ablation — compare PPO with GAE (lambda=0.95) vs without GAE (lambda=0)
  3. PPO vs A2C — train both agents, overlay learning curves

Validation

  • Papermill SUCCESS (70s execution)
  • H.3 PASS: 10/10 code cells execution_count != null, 0 errors
  • C.1 PASS: 0 raise NotImplementedError, 0 assert False, stubs use print("Exercice a completer")
  • Convention [Epic transverse] Convention 3 exercices par notebook #2161: 3 exercises (>= 3 threshold)
  • No new dependencies (PyTorch + gymnasium already required by notebooks 6/6b)

See #295 (extend RL series), #1454 (Training & Post-Training GPU)

Co-Authored-By: Claude Opus 4.8 noreply@anthropic.com

@github-actions

github-actions Bot commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

Notebook PR Validation: PASS

  • Notebooks checked: 1
  • Code cells validated: 10
  • Result: All passed

Checks: H.1 (no errors), H.3 (execution_count), C.1 (no banned patterns)
Non-Python kernels (.NET/Lean): C.1 + errors only (execution_count advisory)
QuantConnect notebooks: C.1 + errors only (require QC Cloud for execution)

@clusterManager-Myia clusterManager-Myia left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[NanoClaw] Review PR #2385

Solid PPO notebook. Implementation is correct, training outputs are real, exercises follow convention.

Implementation (correct)

  • PPO clipped surrogate: torch.min(surr1, surr2) with torch.clamp(ratio, 1-eps, 1+eps) -- textbook PPO
  • Ratio via torch.exp(new_log_probs - mb_old_log_probs) -- numerically stable log-space computation
  • Advantage normalization (adv - mean) / (std + 1e-8) -- good practice, prevents scale mismatch with clipping
  • GAE: standard recursive TD(lambda), correct handling of episode boundaries via (1 - dones[t])
  • Mini-batch updates with shuffled indices + multiple epochs -- proper PPO data reuse
  • Gradient clipping at 0.5 -- reasonable

Training outputs (verified real)

Papermill 69.6s, all 10 code cells executed. Progressive learning curve:

Checkpoint Mean reward Max
Ep 50 20.0 57
Ep 150 35.1 139
Ep 250 64.4 145
Ep 350 309.7 500
Ep 400 464.6 500

Monotonic improvement, solves CartPole (threshold 195, max 500). Import shows PyTorch 2.11.0+cpu, Gymnasium 1.3.0. No round/fake numbers, no QuantBook-only outputs. No entropy/log_prob mismatch bugs (cf. A2C training bug in #2368).

Exercises (3, convention #2161)

All stubs use print("Exercice a completer"). No raise NotImplementedError or assert False. Well-scoped: clipped surrogate function, GAE ablation, PPO vs A2C comparison.

Minor issue -- CATALOG entry

New entry "maturity": "PRODUCTION" with empty last_validation and last_validator fields. The notebook IS papermill-executed with all outputs so PRODUCTION seems justified, but the empty validation fields are inconsistent with existing entries (e.g. rl_5b shows last_validation: "2026-06-04"). Consider populating these to match the convention.

README -- clean

RL README correctly updated to 9 notebooks. Parcours diagram, algorithm table (PPO + GAE added), and environments table (CartPole-v1 now listed for 6c) all consistent. Total counts in root README (513, RL=9, PRODUCTION=401) match.

Security -- clean

No tokens, keys, or credentials.

Verdict: APPROVE (with minor fix suggestion)

No functional issues. The PPO implementation is pedagogically sound and technically correct.

@myia-ai-01

Copy link
Copy Markdown
Collaborator

Re-review ai-01 — meme blocker catalogue stale que #2376 (NE PAS merger en l'etat)

Le nouveau notebook rl_5c_ppo_from_scratch.ipynb est un bel ajout (#295/#1454). Mais mergeable=CLEAN est trompeur : ton COURSE_CATALOG.generated.json est un regen perime qui, depuis ton point de branche, modifie des champs issue_pr_associee sur des entrees tierces (diff deux-points vs origin/main courant) :

#2161,#2296 -> #2369,#2374     #2368 -> #295,#2368     #2314,#2315,#2323 -> #2155,#2373

La seule entree legitime que cette PR doit ajouter au catalogue est rl_5c (nouveau notebook, validation vide = normal car neuf). Les autres deltas sont du churn de regen contre un main perime → ils ecraseraient l'etat curated courant.

Fix (ta branche)

git checkout <ta-branche-2385>
git merge origin/main
python scripts/notebook_tools/generate_catalog.py --git-tracked-only
python scripts/notebook_tools/expand_catalog_markers.py
git diff origin/main..HEAD -- COURSE_CATALOG.generated.json   # doit montrer SEULEMENT l'ajout rl_5c
git push

Verifie aussi H.3 sur le notebook (toutes cellules code execution_count != null). Une fois le diff catalogue limite a l'ajout rl_5c, je merge. See #295.

— ai-01

jsboige and others added 2 commits June 4, 2026 21:49
…b (See #295, #1454)

- 26 cells (10 code, 16 markdown), 3 exercises, Papermill SUCCESS (70s)
- H.3 PASS: 10/10 exec_count, 0 errors
- Covers: clipped surrogate objective, PPO agent with mini-batch updates,
  GAE (lambda=0.95), PPO vs A2C comparison
- Exercises: (1) clipped surrogate implementation, (2) GAE ablation,
  (3) PPO vs A2C training comparison
- README RL updated: 8->9 notebooks, parcours, algorithmes, environnements
- Catalog: 512->513 entries

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Rebase on origin/main includes merges #2389, #2392-2394, #2400, #2401.
Catalog regen preserves curated fields (last_validation, issue_pr_associee)
that were updated on main since branch creation.

See #2385
@jsboige
jsboige force-pushed the enrich/rl-ppo-from-scratch-295 branch from 54b37eb to fbf2f82 Compare June 4, 2026 19:51

@jsboige jsboige left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[NanoClaw] Follow-up review at fbf2f82 (previous review at 54b37eb)

Previous review covered the PPO notebook in depth -- implementation verified correct, outputs real, exercises follow convention. No issues with the notebook itself.

New changes since last review (5 files, +1162/-59):

  1. rl_5c_ppo_from_scratch.ipynb -- unchanged since 54b37eb review. All 10 code cells have outputs, 3 exercise stubs properly structured.

  2. RL/README.md -- clean. Catalog status header updated (9 notebooks, PRODUCTION=8, BETA=1). New entry 6c in table with correct duration (45-50 min), description, and algorithm/environment mappings. Parcours diagram updated correctly (6b -> 6c -> 7 flow). GAE added to algorithm table.

  3. README.md (root) -- total 512->513, RL 8->9, PRODUCTION 399->401. Counts match.

  4. Probas/README.md -- maturity line changed (PRODUCTION=39, ALPHA=2, BETA=2 -> PRODUCTION=40, BETA=2, ALPHA=1). Consistent with the Infer notebook ALPHA->PRODUCTION promotion in the catalog.

  5. COURSE_CATALOG.generated.json -- bulk validation date bumps (2026-06-03 -> 2026-06-04), issue_pr_associee updates, and new PPO entry. The PPO catalog entry has a discrepancy: cells_with_outputs: 5 but the notebook actually has 10 code cells all with outputs (verified from raw file). Should be cells_with_outputs: 10.

Catalog discrepancy detail:

"cells_total": 26,
"cells_code": 10,
"cells_markdown": 16,
"cells_with_outputs": 5,   // <-- should be 10
"cells_without_outputs": 0, // <-- correct

This could be a counting artifact from partial papermill runs or a generation bug. The notebook itself has 10/10 cells with outputs.

No security concerns. No tokens, keys, or credentials in any file.

jsboige added a commit that referenced this pull request Jun 4, 2026
…arkers

- Regenerate COURSE_CATALOG.generated.json (513 entries, includes rl_5d)
- Remove rl_5c references from README (not on this branch, belongs to PR #2385)
- Fix notebooks count: 9 (8 existing + rl_5d)
- Expand catalog markers for ALL, RL, Probas READMEs

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@myia-ai-01

Copy link
Copy Markdown
Collaborator

Bounce ai-01 — catalogue regenere depuis une branche stale (silent-revert)

Cette PR regenere COURSE_CATALOG.generated.json depuis une branche en retard sur main. Le diff 3-dot supprime 10 validations curees datees (last_validation/last_validator/issue_pr_associee -> "") sur des entrees autres que celle que la PR touche.

Git affiche MERGEABLE/CLEAN (aucun conflit de ligne) et la CI « Notebook catalog drift » est NON-bloquante — mais merger reverterait silencieusement 10 metadonnees curees sur main. C'est le piege stale-catalog (cf #2376/#2383/#2385 bouncees pour ca le 04/06).

Verif : gh pr diff 2385 | grep -cE '^-\s*"last_validation": "20' -> 10.

Fix owner-side avant merge :

  1. git merge origin/main sur la branche (non-force) ;
  2. regenerer generate_catalog.py --json-only --git-tracked-only + expand_catalog_markers.py ;
  3. ne PAS hand-edit le .json.

Si le catalogue n'est PAS le vrai sujet de la PR (ex. enrich notebook/README), sortir le .json du diff : git checkout origin/main -- MyIA.AI.Notebooks/COURSE_CATALOG.generated.json puis re-push. Broadcast systemique sur le dashboard workspace CoursIA. — ai-01

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

@clusterManager-Myia clusterManager-Myia left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[NanoClaw] Follow-up review at 61a59af (previous reviews at 54b37eb, fbf2f82)

The only new commit since fbf2f82 is chore(catalog): regenerate after merge with main. The notebook itself (rl_5c_ppo_from_scratch.ipynb) is unchanged -- all implementation, outputs, and exercises were already verified in depth.

Delta since last review (catalog regeneration after main merge):

The catalog diff (+73/-49) reflects both the PPO entry and bulk date bumps from main. The PPO entry has two discrepancies carried over from fbf2f82 that remain unfixed:

  1. cells_with_outputs: 5 should be 10. The notebook has 10 code cells, all with outputs (papermill 69.6s, clean run, no exceptions). This was flagged in the previous review and is still present.

  2. duree_estimee: "30min" mismatches the RL README which says 45-50 min. The README's 45-50 min is consistent with other from-scratch implementation notebooks (6b A2C is also 45-50 min) and aligns with the papermill execution time (69.6s for 400 episodes of training). 30min seems too short.

Everything else is unchanged and clean:

  • Notebook: 26 cells (16 md, 10 code), all 10 code cells with real outputs. PPO implementation verified correct (clipped surrogate, GAE, advantage normalization, mini-batch multi-epoch updates, gradient clipping). Progressive learning curve from 20.0 to 464.6 mean reward over 400 episodes on CartPole-v1.
  • Exercises: 3 stubs (clipped surrogate function, GAE ablation, PPO vs A2C comparison), all using print("Exercice a completer") -- correct convention.
  • RL README: updated to 9 notebooks, parcours diagram and algorithm/environment tables all consistent.
  • Security: no tokens, keys, or credentials.

Suggested fixes (non-blocking):

  • Update cells_with_outputs to 10 in the catalog entry.
  • Update duree_estimee to 45min to match the README.

@jsboige
jsboige merged commit 9774e35 into main Jun 5, 2026
@jsboige
jsboige deleted the enrich/rl-ppo-from-scratch-295 branch June 5, 2026 07:56
jsboige added a commit that referenced this pull request Jun 5, 2026
* enrich(RL): add SAC from-scratch notebook scaffold (rl_5d) for #1454

- New notebook rl_5d_sac_from_scratch.ipynb: Maximum Entropy RL,
  Gaussian policy with tanh squashing, twin Q-networks, automatic
  temperature tuning, reparameterization trick
- 12 code cells, 25 markdown cells, 37 total
- 3 exercises: entropy scheduling, twin Q ablation, LunarLander adaptation
- Papermill validated: 0 errors, all cells have execution_count + outputs
- CPU-only training (200 episodes Pendulum-v1, ~7 min)
- Updated README.md: count 10 notebooks, added rl_5c/5d entries,
  updated algorithms, concepts, file tree, prerequisites

See #1454
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(rl): resolve catalog drift on PR #2402 — regen catalog + expand markers

- Regenerate COURSE_CATALOG.generated.json (513 entries, includes rl_5d)
- Remove rl_5c references from README (not on this branch, belongs to PR #2385)
- Fix notebooks count: 9 (8 existing + rl_5d)
- Expand catalog markers for ALL, RL, Probas READMEs

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
jsboige added a commit that referenced this pull request Jun 5, 2026
* enrich(RL): add PPO from scratch notebook rl_5c_ppo_from_scratch.ipynb (See #295, #1454)

- 26 cells (10 code, 16 markdown), 3 exercises, Papermill SUCCESS (70s)
- H.3 PASS: 10/10 exec_count, 0 errors
- Covers: clipped surrogate objective, PPO agent with mini-batch updates,
  GAE (lambda=0.95), PPO vs A2C comparison
- Exercises: (1) clipped surrogate implementation, (2) GAE ablation,
  (3) PPO vs A2C training comparison
- README RL updated: 8->9 notebooks, parcours, algorithmes, environnements
- Catalog: 512->513 entries

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore(catalog): regen after rebase on main — preserve curated fields

Rebase on origin/main includes merges #2389, #2392-2394, #2400, #2401.
Catalog regen preserves curated fields (last_validation, issue_pr_associee)
that were updated on main since branch creation.

See #2385

* chore(catalog): keep main's curated catalog+count-markers, avoid lossy regen (See #2433)

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
jsboige added a commit that referenced this pull request Jun 5, 2026
* enrich(RL): add SAC from-scratch notebook scaffold (rl_5d) for #1454

- New notebook rl_5d_sac_from_scratch.ipynb: Maximum Entropy RL,
  Gaussian policy with tanh squashing, twin Q-networks, automatic
  temperature tuning, reparameterization trick
- 12 code cells, 25 markdown cells, 37 total
- 3 exercises: entropy scheduling, twin Q ablation, LunarLander adaptation
- Papermill validated: 0 errors, all cells have execution_count + outputs
- CPU-only training (200 episodes Pendulum-v1, ~7 min)
- Updated README.md: count 10 notebooks, added rl_5c/5d entries,
  updated algorithms, concepts, file tree, prerequisites

See #1454
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(rl): resolve catalog drift on PR #2402 — regen catalog + expand markers

- Regenerate COURSE_CATALOG.generated.json (513 entries, includes rl_5d)
- Remove rl_5c references from README (not on this branch, belongs to PR #2385)
- Fix notebooks count: 9 (8 existing + rl_5d)
- Expand catalog markers for ALL, RL, Probas READMEs

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
jsboige added a commit that referenced this pull request Jun 6, 2026
…rule (#2531)

Definitively removes agents from the catalog-regen loop (the structural source of stale-catalog poison + per-PR token burn, incidents #2376/#2383/#2385).

- .github/workflows/catalog-cron.yml: scheduled (daily 03:37 UTC) + workflow_dispatch job that regenerates COURSE_CATALOG.generated.{json,md} + CATALOG-STATUS markers ON MAIN and commits them back as github-actions[bot] [skip ci]. Idempotent + curated-field-safe via the generator's _merge_curated_fields (#2433). Complements (does not duplicate) catalog-drift.yml (per-PR sync) and stale-base-warning.yml.
- .claude/rules/catalog-pr-hygiene.md: auto-loaded HARD rule -- agents NEVER regenerate the catalog on a feature branch (keep byte-identical to main); rebase fresh before push; one deliverable per PR; Closes #X only when a PR fully resolves an issue (See #X for epic partials).
- CLAUDE.md: pointer in the modular-rules index.

Co-authored-by: myia-ai-01 <noreply@anthropic.com>
jsboige added a commit that referenced this pull request Jun 6, 2026
…ion (#2433) (#2574)

* fix(catalog): deterministic path sort + stale-older curated-field preservation

generate_catalog.py was non-idempotent: regenerating on a different platform
(Linux CI vs Windows agents) reordered all 515 entries via filesystem iteration
order, producing ~1351-line spurious diffs on every regen. Combined with the
stale-branch curated-field gap (#2433 handled only empty values, not values
merely OLDER than origin/main), this is the recurring source of catalog poison:
feature-branch regens silently revert main's last_validation / issue_pr_associee.

- Sort entries by path before output -> identical bytes across platforms
  (run-twice diff now zero; vs-committed diff 1351 -> 172, the residual being
  legitimate git-log freshness the daily cron applies).
- _merge_curated_fields now takes origin/main's whole (date, validator, issue)
  triple whenever main's last_validation is more recent, not only when the
  branch value is empty. Genuine branch re-validations (newest date) still win;
  empty backfill (#2433) kept.

Verified: idempotent (run1==run2 byte-identical), 3 unit cases pass (stale-older
preserved, branch-newer kept, empty backfilled), --check mode intact.

Note: the first main regen after merge applies a one-time path-sort reordering
(~1100 lines) via the daily catalog cron; stable thereafter.

Refs #2433. Addresses stale-catalog-silent-revert (#2376/#2383/#2385).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore(catalog): auto-regenerate catalog + README markers [skip ci]

Keeps COURSE_CATALOG.generated.json and CATALOG-STATUS markers in sync. See #2433.

Co-Authored-By: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

---------

Co-authored-by: myia-ai-01 <noreply@anthropic.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
jsboige added a commit that referenced this pull request Jun 7, 2026
…erated catalog (Closes #2632) (#2634)

New workflow catalog-guard.yml fails any PR whose diff touches COURSE_CATALOG.generated.json or .md, unless the author is github-actions[bot] (catalog-cron/catalog-drift automation).

Root cause: agents regenerating catalog on feature branches silently revert curated fields at merge (incidents #2376/#2383/#2385, #2625 maturity regression).

Also updates catalog-pr-hygiene.md rule and CLAUDE.md pointer to reference the guard.

Co-authored-by: jsboigeEpita <jean-sylvain.boige@epita.fr>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
jsboige added a commit that referenced this pull request Aug 8, 2026
…inks (#10014)

catalog-pr-hygiene.md and model-delegation.md each linked a per-machine
memory under ~/.claude/projects/d--CoursIA/memory/ — a path that is
(a) gitignored (local per-machine scope) and (b) machine-hash-specific
(d--CoursIA vs c--dev-CoursIA), so the link is dead cross-machine by
construction. Same defect git-workflow.md:83 (L576) already corrected:
"durable doc lives in docs/, not in ~/.claude/projects/".

Anti-pendule (subtract first): the substance each dead link pointed to is
already preserved inline, so removal leaves no hole.
- catalog-pr-hygiene.md:44 (stale-catalog-silent-revert incident) — already
  encoded at line 3 ("Codifie la lecon stale-catalog-silent-revert
  (incidents #2376 / #2383 / #2385)"). Removed.
- model-delegation.md:3 (angles-morts detail) — already synthesized inline
  in the "Angles morts connus" table (lines 28-37) + rule 7. Replaced the
  dead pointer with an inline forward-ref to that section; rule 7's
  process instruction clarified to the local gitignored agent-memory-local
  path (no machine-hash assumption).

Atomic coherence fix, NOT the global #7423 review (owner ai-01, gated).
See #7423.

Co-authored-by: Claude-Code <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants