Skip to content

feat(ml): PatchTST & iTransformer training scripts (Stage 2) - #710

Merged
jsboige merged 1 commit into
mainfrom
feature/ml-curriculum-stage2-transformers-ts
May 4, 2026
Merged

jsboige merged 1 commit into
mainfrom
feature/ml-curriculum-stage2-transformers-ts

Conversation

@jsboige

@jsboige jsboige commented May 4, 2026

Copy link
Copy Markdown
Owner

Summary

  • Add PatchTST (ICLR 2023) and iTransformer (ICLR 2024) training scripts for financial time-series forecasting
  • 21 CPU-only smoke tests (11 PatchTST + 10 iTransformer) — all passing
  • Anti-pattern safeguards: train-only normalization, majority-class baseline, thermal watchdog (80C), AMP
  • Stage 2 documentation with architecture comparison and usage guide

Files

File Description
scripts/train_patchtst.py PatchTST model + training pipeline (635K params)
scripts/train_itransformer.py iTransformer model + training pipeline (613K params)
tests/test_patchtst.py 11 CPU smoke tests for PatchTST
tests/test_itransformer.py 10 CPU smoke tests for iTransformer
docs/STAGE2_TRANSFORMERS_TS.md Architecture comparison, quick start, details

Test plan

  • python -m pytest tests/ -v — 21/21 passed (2.83s)
  • python scripts/train_patchtst.py --dry-run — 635K params, pipeline validated
  • python scripts/train_itransformer.py --dry-run — 613K params, pipeline validated
  • Review architecture correctness vs papers
  • Review test coverage adequacy

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

🤖 Generated with Claude Code

…age 2)

Two SOTA transformer architectures for financial time-series forecasting:

- PatchTST (ICLR 2023): patching + channel independence, 635K params default
- iTransformer (ICLR 2024): inverted attention over variables, 613K params

Both include anti-pattern safeguards: train-only normalization, majority-class
baseline, thermal watchdog (80C), AMP support, walk-forward validation.

21 CPU-only smoke tests covering forward shapes, gradient flow, state dict
roundtrip, sequence building, normalization, and majority baseline computation.

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

@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.

COMMENT review (self-authored — cannot APPROVE)

PatchTST & iTransformer training scripts (Stage 2)

5 files, +1476: 2 training scripts + 1 doc + 2 test files.

Scripts reviewed

  1. train_patchtst.py (633 lines): PatchTST implementation (Nie et al., ICLR 2023)

    • Patching + channel independence as described in the paper
    • Variable positional encoding (learnable)
    • Proper train-only normalization (normalize_sequences computes stats on train set)
    • Majority-class baseline computed and compared (anti-pattern #703 safeguard)
    • AMP support, thermal watchdog, gradient clipping (max_norm=1.0)
    • CosineAnnealingWarmRestarts scheduler
    • Best-state checkpointing (saves best val_loss model)
  2. train_itransformer.py (541 lines): iTransformer implementation (Li et al., ICLR 2024)

    • Correct inverted architecture: [B,T,N] → [B,N,T] → Linear(T,d_model) → Transformer over N variable tokens
    • Mean aggregation across variables for final prediction
    • Same safeguards as PatchTST (normalization, baseline, AMP, thermal)
  3. STAGE2_TRANSFORMERS_TS.md (102 lines): Architecture comparison table, quick start, anti-pattern safeguards documented

Tests

  • test_patchtst.py (11 tests): forward pass shapes, parameter count, state dict roundtrip, gradient flow, normalization
  • test_itransformer.py (10 tests): similar coverage for iTransformer

Anti-pattern compliance

  • --test-ratio HONORED: actual ratio reported alongside requested
  • Train-only Z-normalization (anti-leakage)
  • Majority-class baseline always reported with edge calculation
  • batch_thermal_check() every 5 batches, MAX_TEMP=80°C
  • Walk-forward validation supported via Stage 0 WalkForwardSplitter

Minor notes

  • sys.path.append(str(Path(__file__).resolve().parent.parent.parent / "shared")) — fragile but consistent
  • Both scripts share duplicated code (normalize_sequences, compute_majority_class_baseline, save_checkpoint) — could be extracted to shared module, but acceptable for now
  • data_hash included in metadata for reproducibility

No bugs found. Ready for external APPROVE.

@jsboige
jsboige merged commit 21f097e into main May 4, 2026
1 check passed
@jsboige
jsboige deleted the feature/ml-curriculum-stage2-transformers-ts branch May 4, 2026 20:30
jsboige added a commit that referenced this pull request Jul 20, 2026
…paths) (#7598)

MGS-10-CenterBias.ipynb hardcoded `c:/dev/MetaGeneticSharp/...` absolute paths in
cell 1 (5 #r directives + 1 prerequisite comment). Same anti-pattern as
PR #7583 (MGS-7b N-D landscape) and PR #7595 (MGS-7-TSP).

Transform c:/dev/MetaGeneticSharp/ -> ..\MetaGeneticSharp\ (relative to
notebook location at Search/Part4-Metaheuristics/, submodule at
Search/MetaGeneticSharp/). Build config kept Debug (matches canonical,
minimum surface change).

Verifications:
- nbclient .net-csharp: 8/8 cells, 0 errors, all execution_count
- promote ec+outputs: 8/8 cells promoted from .executed.ipynb
- strip probeAddresses banner: 9 banner lines stripped from canonical
  (NOT from .executed.ipynb - C708-L5 NEW lesson applied)
- H.3 validate_pr_notebooks.py origin/main: PASS 1/1 (8 cells [.net-csharp])
- dotnet build MetaGeneticSharp.Extensions Debug: 0 errors, 21 warnings
  (CA1416 platform + CS8618 nullable, same as c.709)

Submodule pointer NOT bumped (no submodule content change, only
notebook paths). MetaGeneticSharp stays at submodule-main SHA
6a501d967331205dea193c7a415ec1c852766f7c.

c.71x sweep continues with MGS-11+ if window permits (13 MGS notebooks
total remaining after this fix, ordered low-path-count first).

Co-authored-by: Claude-Code <noreply@anthropic.com>
jsboige added a commit that referenced this pull request Jul 20, 2026
…elative paths) (#7607)

Apply the #710 portability pattern (cf #7595 MGS-7, #7598 MGS-10, #7603
MGS-19, #7605 MGS-18) to MGS-16-AlgorithmSelection.ipynb: 6 hardcoded
'#r' references c:/dev/MetaGeneticSharp/... -> ../MetaGeneticSharp/...
(forward-slash, cross-platform portable, matching MGS-3 canonical form
on main).

Re-executed end-to-end via .net-csharp kernel (MetaGeneticSharp.sln Debug
built, 0 errors): 14/14 code cells, exec_count != null, 0 errors, wiring
cell emits 'DLLs chargees. CenterBiasBenchmark' proving the relative
paths load. Outputs regenerated (C.2).

Build config = Debug maintained. Submodule pointer NOT bumped.

See #710

Co-authored-by: Claude <noreply@anthropic.com>
jsboige added a commit that referenced this pull request Jul 20, 2026
… (relative paths) (#7603)

* fix(search,#710): make MGS-19-MetropolisReinsertion notebook portable (relative paths)

Apply the #710 portability pattern (cf #7595 MGS-7, #7598 MGS-10) to
MGS-19-MetropolisReinsertion.ipynb: 5 hardcoded '#r' references
c:/dev/MetaGeneticSharp/... -> ../MetaGeneticSharp/... (forward-slash,
cross-platform portable, matching MGS-3 canonical form on main).

Re-executed end-to-end via .net-csharp kernel (MetaGeneticSharp.sln Debug
built first, 0 errors): 9/9 code cells, exec_count != null, 0 errors,
wiring cell emits 'DLLs chargees. Operateurs de reinsertion du fork :'
proving the relative paths load. Outputs regenerated (C.2).

Build config = Debug maintained. Submodule pointer NOT bumped.

See #710

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

* fix(search): strip probeAddresses banner from MGS-19-MetropolisReinsertion output (banner-guard)

.NET Interactive bootstrap re-injects the probeAddresses banner on every
re-exec; sanctioned strip via scripts/notebook_tools/strip_probe_banner.py
--apply (secrets-hygiene regle 6, not hand-scrubbing). Content unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
jsboige added a commit that referenced this pull request Jul 20, 2026
…hs) (#7605)

* fix(search,#710): make MGS-18-CecBanc notebook portable (relative paths)

Apply the #710 portability pattern (cf #7595 MGS-7, #7598 MGS-10, #7603
MGS-19) to MGS-18-CecBanc.ipynb: 5 hardcoded '#r' references
c:/dev/MetaGeneticSharp/... -> ../MetaGeneticSharp/... (forward-slash,
cross-platform portable, matching MGS-3 canonical form on main).

Re-executed end-to-end via .net-csharp kernel (MetaGeneticSharp.sln Debug
built first, 0 errors): 11/11 code cells, exec_count != null, 0 errors,
wiring cell emits 'DLLs chargees. Moteur de-biais CEC :' proving the
relative paths load. Outputs regenerated (C.2).

Build config = Debug maintained. Submodule pointer NOT bumped.

See #710

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

* fix(search): strip probeAddresses banner from MGS-18-CecBanc output (banner-guard)

.NET Interactive bootstrap re-injects the probeAddresses banner on every
re-exec; sanctioned strip via scripts/notebook_tools/strip_probe_banner.py
--apply (secrets-hygiene regle 6, not hand-scrubbing). Content unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
jsboige added a commit that referenced this pull request Jul 20, 2026
…lative paths) (#7608)

* fix(search,#710): make MGS-15-LandscapeAnalysis notebook portable (relative paths)

Apply the #710 portability pattern (cf #7595 MGS-7, #7598 MGS-10, #7603
MGS-19, #7605 MGS-18, #7607 MGS-16) to MGS-15-LandscapeAnalysis.ipynb:
8 hardcoded '#r' references c:/dev/MetaGeneticSharp/... ->
../MetaGeneticSharp/... (forward-slash, cross-platform portable,
matching MGS-3 canonical form on main).

Re-executed end-to-end via .net-csharp kernel (MetaGeneticSharp.sln Debug
built, 0 errors): 10/10 code cells, exec_count != null, 0 errors, wiring
cell emits 'Benchmarks dispos : SphereFitness, RastriginFitness, AckleyFitness'
proving the relative paths load. Landscape analysis figures regenerated (C.2).

Build config = Debug maintained. Submodule pointer NOT bumped.

See #710

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

* fix(search): strip probeAddresses banner from MGS-15-LandscapeAnalysis output (banner-guard)

.NET Interactive bootstrap re-injects the probeAddresses banner on every
re-exec; sanctioned strip via scripts/notebook_tools/strip_probe_banner.py
--apply (secrets-hygiene regle 6, not hand-scrubbing). Content unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
jsboige added a commit that referenced this pull request Jul 20, 2026
…paths) (#7612)

### Summary

Replaces hardcoded `c:/dev/MetaGeneticSharp/...` paths with portable `..\MetaGeneticSharp\...` (relative to the notebook directory) in `MGS-8-LandscapeExplorer.ipynb`. The pattern follows the c.706 (MGS-7 TSP) and c.710 (MGS-10 CenterBias) precedent: a relative path that resolves correctly when the .NET Interactive kernel cwd is set to the notebook's parent directory.

This unblocks running MGS-8 on any machine that has the `MetaGeneticSharp` submodule checked out alongside the notebook — no symlink to `c:/dev/MetaGeneticSharp` required.

### Changes

| File | Change |
|------|--------|
| `MyIA.AI.Notebooks/Search/Part4-Metaheuristics/MGS-8-LandscapeExplorer.ipynb` | 1 markdown line (build prerequisite) + 7 `#r` paths + 1 `NativeLibrary.Load` path: `c:/dev/MetaGeneticSharp/...` → `..\MetaGeneticSharp\...` |

Source-only diff (cell sources): **9 line changes** in the `#r` and `NativeLibrary.Load` block + 1 markdown prerequisite line. Outputs regenerated by re-execution (cell sources preserved verbatim otherwise).

### Verification

- `dotnet build src/MetaGeneticSharp.Extensions/MetaGeneticSharp.Extensions.csproj -c Debug` → 0 errors (21 pre-existing CA1416/CS8618 warnings, unrelated)
- `scripts/execute_dotnet_notebook.py MyIA.AI.Notebooks/Search/Part4-Metaheuristics/MGS-8-LandscapeExplorer.ipynb 600` → **16/16 cells SUCCESS, 0 errors** (kernel cwd set to `Part4-Metaheuristics/` via `System.IO.Directory.SetCurrentDirectory`)
- `scripts/notebook_tools/validate_pr_notebooks.py origin/main <nb>` → **PASS** (16 cells [.net-csharp])
- `scripts/notebook_tools/strip_probe_banner.py --apply <canonical>` → 0 banners (clean)
- Submodule SHA: `MetaGeneticSharp @ 6a501d96` (unchanged from main)

### Context

- Rollout MGS portability c.706 → c.710 → **c.711** (this PR). 1 notebook per cycle; 13 MGS notebooks remaining (`MGS-3, MGS-4, MGS-6, MGS-9, MGS-11..19`).
- Closes (sub-task of #710 — partial, see #710 for full scope): fixes MGS-8 hardcoded path. Other MGS notebooks to follow in subsequent cycles.
- Sibling PRs: #7598 (c.710 MGS-10, MERGED eb020ca → 4a5419c), #7583 + submodule #41 (c.706 MGS-7 N-D landscape).

### Lessons captured

- `scripts/execute_dotnet_notebook.py` (canonical .NET kernel executor) handles cwd setup via `System.IO.Directory.SetCurrentDirectory(working_dir)` BEFORE executing cells. This is the canonical pattern for re-executing .NET Interactive notebooks with relative paths.
- NotebookEdit tool wipes `execution_count` + `outputs` AND converts `source` list→str — use Python with `nbformat.write` for proper round-trip preservation.
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.

1 participant