---
phase: 04-integration-publishing
plan: 03
type: execute
wave: 1
depends_on: []
files_modified:
  - README.md
autonomous: true

must_haves:
  truths:
    - "README explains what predictive coding is and how it differs from backprop (3-5 paragraphs)"
    - "README includes installation instructions that say 'install PyTorch first' before pip install pcn-torch"
    - "README has a quickstart code snippet that works with the public API"
    - "README has an API overview table listing main classes/functions with brief descriptions"
    - "README has a Results section with expected CIFAR-10 accuracy and training time"
    - "README links to the arXiv paper (arXiv:2506.06332)"
  artifacts:
    - path: "README.md"
      provides: "Full user-facing documentation"
      min_lines: 120
      contains: "pytorch.org"
    - path: "README.md"
      provides: "API overview"
      contains: "PredictiveCodingNetwork"
    - path: "README.md"
      provides: "Results section"
      contains: "45"
  key_links:
    - from: "README.md Installation section"
      to: "pytorch.org"
      via: "explicit link to PyTorch install page"
      pattern: "pytorch.org"
    - from: "README.md quickstart"
      to: "pcn_torch public API"
      via: "from pcn_torch import"
      pattern: "from pcn_torch import"
---

<objective>
Rewrite README.md as the primary user-facing documentation for pcn-torch v1.0.0.

Purpose: The current README is a project planning stub. It needs to become the documentation that users read when they discover the package on PyPI or GitHub. Per locked decisions, the tone is academic but pedagogical — explain the theory, then show how to use it.

Output: README.md with a predictive coding explainer (3-5 paragraphs), installation section (PyTorch peer dependency instruction), quickstart code snippet, API overview table, and Results section with CIFAR-10 accuracy expectations.
</objective>

<execution_context>
@C:\Users\RDCHLEM1\.claude/get-shit-done/workflows/execute-plan.md
@C:\Users\RDCHLEM1\.claude/get-shit-done/templates/summary.md
</execution_context>

<context>
@.planning/PROJECT.md
@.planning/phases/04-integration-publishing/04-CONTEXT.md
@.planning/phases/04-integration-publishing/04-RESEARCH.md
@src/pcn_torch/__init__.py
@README.md
</context>

<tasks>

<task type="auto">
  <name>Task 1: Rewrite README.md with full academic-pedagogical documentation</name>
  <files>README.md</files>
  <action>
Rewrite README.md completely. The current content (project planning stub) should be replaced entirely. Preserve the badge block at the top but update the status badge to "stable" and use the correct install badge.

**Required structure (all sections must be present, in this order):**

1. **Header + badges** — keep the existing badge block, update `status-pre--release-orange` to `status-stable-brightgreen`

2. **One-liner description** — "A clean, PyTorch-native implementation of Predictive Coding Networks (PCNs) from [arXiv:2506.06332v1]."

3. **What are Predictive Coding Networks?** — 3-5 paragraphs explaining the theory accessibly. Must cover:
   - The core idea: the brain as a hierarchical prediction machine (Rao & Ballard, 1999; Friston 2005)
   - Two-timescale dynamics: fast inference (latent updates) then slow learning (weight updates)
   - How this differs from backpropagation: local computations only, no global error signal propagating backward
   - The energy function: L = (1/2) sum ||eps^(l)||^2 where eps^(l) = x^(l) - f^(l)(W^(l) x^(l+1})
   - Why this matters: biologically plausible, naturally local, amenable to hardware that supports local learning
   - Reference: "For a clear derivation and full algorithm, see Stenlund (2025) [arXiv:2506.06332v1]."

4. **Installation** — Two-step process (locked decision: PyTorch is peer dep):
   ```
   ## Installation

   pcn-torch requires PyTorch. Install it first from https://pytorch.org (choose your platform and CUDA version).

   Then install pcn-torch:
   pip install pcn-torch
   ```
   Include a note: "PyTorch is not bundled with pcn-torch to let you choose your hardware variant (CPU, CUDA, ROCm)."

5. **Quickstart** — A complete, runnable code snippet showing the key workflow. Must include:
   - Import from pcn_torch
   - Construct PredictiveCodingNetwork with dims
   - Create a TrainConfig with RichCallback
   - Call train_pcn
   - Call test_pcn
   Example:
   ```python
   import torch
   from torch.utils.data import DataLoader, TensorDataset
   from pcn_torch import (
       PredictiveCodingNetwork,
       RichCallback,
       TrainConfig,
       train_pcn,
       test_pcn,
   )

   # Toy classification: 64-dim input, 10 classes
   X = torch.randn(500, 64)
   y = torch.randint(0, 10, (500,))
   loader = DataLoader(TensorDataset(X, y), batch_size=32)

   model = PredictiveCodingNetwork(
       dims=[64, 128, 64],   # input=64, hidden=128, top_latent=64
       activation="relu",
       output_dim=10,
       mode="classification",
   )

   config = TrainConfig(
       task="classification",
       T_infer=50,
       lr_infer=0.05,
       lr_learn=0.005,
       num_epochs=4,
       callback=RichCallback(),
   )

   history = train_pcn(model, loader, config)
   results = test_pcn(model, loader, config)
   print(f"Accuracy: {results['accuracy']:.1%}")
   ```

6. **API Overview** — Markdown table with two columns: Name and Description. List all exported names from `__all__`:

   | Name | Description |
   |------|-------------|
   | `PredictiveCodingNetwork` | Full PCN hierarchy: manages layers, latents, errors, and readout |
   | `PCNLayer` | Single generative layer wrapping top-down weights and activation function |
   | `train_pcn` | Train a network for multiple epochs using inference then learning loops |
   | `test_pcn` | Evaluate a trained network on a DataLoader, returns accuracy and energy |
   | `TrainConfig` | Dataclass holding all training hyperparameters (T_infer, lr_infer, etc.) |
   | `TrainHistory` | Training history object returned by train_pcn (per-epoch and per-batch logs) |
   | `EnergyHistory` | Energy trajectories (per_step, per_batch, per_epoch) within TrainHistory |
   | `RichCallback` | Rich-powered progress bar and live metrics display during training |
   | `TrainCallback` | Base class for custom callbacks; subclass to add your own logging |
   | `compute_energy` | Compute scalar PCN energy from a network's current error state |
   | `compute_energy_per_layer` | Per-layer energy breakdown as a list of floats |
   | `get_activation` | Retrieve an (activation_fn, derivative_fn) pair by name ("relu", "tanh", "sigmoid") |
   | `PCNErrors` | NamedTuple holding per-layer errors (eps) and gain-modulated errors (h) |
   | `ActivationFn` | Type alias for activation functions: Callable[[Tensor], Tensor] |
   | `ActivationDeriv` | Type alias for derivative functions: Callable[[Tensor], Tensor] |
   | `ActivationPair` | NamedTuple of (fn: ActivationFn, deriv: ActivationDeriv) |
   | `__version__` | Package version string (e.g., "1.0.0") |

7. **Results** — CIFAR-10 benchmark section:
   ```
   ## Results

   The `examples/cifar10.py` script trains a 3-hidden-layer MLP PCN on CIFAR-10:

   | Metric | Value |
   |--------|-------|
   | Architecture | dims=[3072, 1024, 1024, 512], output_dim=10 |
   | Inference steps (T_infer) | 20 |
   | Epochs | 10 |
   | Batch size | 128 |
   | Expected test accuracy | 45–55% |
   | Training time (CPU) | ~5–15 minutes |

   Note: A fully-connected MLP is architecturally limited on CIFAR-10 regardless of the learning
   rule — both backprop and PCN achieve similar accuracy with the same architecture. The example
   demonstrates that the PCN learning algorithm works correctly, not that MLPs are competitive
   with convolutional networks on vision tasks.
   ```

8. **How It Works** — Brief algorithmic overview (2 paragraphs max):
   - Inference phase: For T_infer steps, update each latent x^(l) to minimize local prediction error eps^(l)
   - Learning phase: For T_learn steps, update weights W^(l) via local Hebbian-like rule using batch-averaged outer product of errors
   - "All operations run under torch.no_grad() — no autograd graph is constructed."

9. **References** — Keep existing references section:
   ```
   ## References

   - **Paper:** Stenlund, M. (2025). "Introduction to Predictive Coding Networks for Machine Learning." [arXiv:2506.06332v1](https://arxiv.org/abs/2506.06332)
   - **Reference implementation:** [github.com/Monadillo/pcn-intro](https://github.com/Monadillo/pcn-intro)
   ```

**IMPORTANT — remove entirely from the new README:**
- The "Project Planning" section with the table of .planning/ documents
- The "Roadmap Overview" section (1/2/3/4 bullet list)
These are internal planning docs, not user documentation.

**Tone guidance:** Write as if explaining to a ML researcher or advanced practitioner who knows what neural networks are but may not know predictive coding. Don't be condescending, but do explain the intuition. The energy equation can be shown in LaTeX-friendly notation inline (use backtick formatting for inline math).
  </action>
  <verify>
```bash
# 1. Verify README exists and has content
wc -l README.md
# Expected: at least 120 lines

# 2. Verify PyTorch peer dep instruction is present
grep -i "pytorch.org" README.md
# Expected: link to pytorch.org in Installation section

# 3. Verify the "install PyTorch first" language is present
grep -i "install.*pytorch\|pytorch.*first\|install.*torch first" README.md -i
# Expected: some instruction about installing PyTorch first

# 4. Verify API table is present
grep "PredictiveCodingNetwork" README.md | head -5
# Expected: appears in API table and quickstart

# 5. Verify Results section is present
grep -i "results\|45\|55%" README.md
# Expected: Results section with accuracy range

# 6. Verify arXiv link is present
grep "2506.06332" README.md
# Expected: arXiv link

# 7. Verify planning docs section is GONE (internal docs should not be in user README)
grep "\.planning" README.md
# Expected: no output (planning links removed)

# 8. Verify quickstart has from pcn_torch import
grep "from pcn_torch import" README.md
# Expected: import block in quickstart section
```
  </verify>
  <done>
- README.md rewritten from planning stub to full user documentation
- "What are Predictive Coding Networks?" section: 3-5 paragraphs with theory + diff from backprop
- Installation section: explicit "install PyTorch first from pytorch.org" instruction
- Quickstart section: runnable code snippet using public API
- API Overview: Markdown table covering all 17 exported names from __all__
- Results section: CIFAR-10 accuracy table (45-55%, 5-15 min) and honest interpretation
- References section: arXiv paper link preserved
- No planning docs (internal .planning/ links removed)
  </done>
</task>

</tasks>

<verification>
```bash
# Check that badge block is at the top (preserved from original)
head -10 README.md | grep "img.shields.io"
# Expected: badge lines present

# Verify all 17 __all__ exports appear somewhere in README
uv run python -c "
import ast, re

# Get __all__ from __init__.py
with open('src/pcn_torch/__init__.py') as f:
    tree = ast.parse(f.read())
all_names = []
for node in ast.walk(tree):
    if isinstance(node, ast.Assign):
        for t in node.targets:
            if isinstance(t, ast.Name) and t.id == '__all__':
                all_names = [e.s for e in node.value.elts]

# Check README mentions each
with open('README.md') as f:
    readme = f.read()

missing = [n for n in all_names if n not in readme]
if missing:
    print('Missing from README:', missing)
else:
    print('All', len(all_names), 'exported names mentioned in README')
"
# Expected: All 17 exported names mentioned in README
```
</verification>

<success_criteria>
- README.md is rewritten (not the planning stub)
- "What are Predictive Coding Networks?" has 3-5 explanatory paragraphs
- Installation says "install PyTorch first from pytorch.org" before `pip install pcn-torch`
- Quickstart shows complete workflow: import, build model, configure, train, evaluate
- API Overview table covers all 17 names from __all__
- Results section shows expected CIFAR-10 accuracy (45-55%) and training time (5-15 min)
- arXiv:2506.06332 is linked
- No .planning/ internal links in the user-facing README
</success_criteria>

<output>
After completion, create `.planning/phases/04-integration-publishing/04-03-SUMMARY.md`
</output>
