diff --git a/physix-live/README.md b/physix-live/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c0773ac2e5ad4f4439f50420530dacb07b8ae91f --- /dev/null +++ b/physix-live/README.md @@ -0,0 +1,308 @@ +# PhysiX-Live + +**One-line pitch:** an OpenEnv RL environment where a small (1.5B) language model iteratively +discovers equations of motion from trajectory data plus a one-sentence English hint — +verifier is `scipy.integrate.odeint` plus per-step R², no LLM-as-judge in the reward loop. + +A submission for the **OpenEnv hackathon** (Apr 2026). The deliverables are: a clean +OpenEnv-compatible env, a TRL+Unsloth+GRPO training pipeline targeting Qwen2.5-1.5B with +LoRA-32, a React + TypeScript + Tailwind demo UI that animates trajectories side-by-side +for the trained vs. untrained model, and a recording script for pre-baked demo episodes. + +--- + +## Repository layout + +``` +physix-live/ +├── physix/ # Python package +│ ├── __init__.py # narrow public API +│ ├── models.py # Pydantic Action / Observation / State +│ ├── client.py # OpenEnv WebSocket client subclass +│ ├── systems/ # 8 physical systems in 3 tiers +│ │ ├── base.py # PhysicalSystem ABC + TrajectoryData +│ │ ├── tier1.py # FreeFall, FreeFallWithDrag, SimplePendulum +│ │ ├── tier2.py # DampedPendulum, SpringMass, DampedSpring +│ │ ├── tier3.py # ProjectileWithDrag, ChargedInBField (held out) +│ │ └── registry.py # system_id -> factory mapping +│ ├── verifier/ # scoring pipeline +│ │ ├── parser.py # SymPy whitelisted parser +│ │ ├── simulator.py # scipy.odeint forward sim +│ │ ├── metrics.py # per-step R² +│ │ ├── mismatch.py # English residual summary +│ │ └── reward.py # 4-component reward composition +│ ├── server/ # FastAPI + OpenEnv +│ │ ├── environment.py # PhysiXEnvironment subclass +│ │ ├── interactive.py # session-based REST router (`/interactive/*`) +│ │ └── app.py # FastAPI factory + CLI entry point +│ └── training/ # GRPO training pipeline +│ ├── prompt.py # observation -> prompt, completion -> action +│ ├── scorer.py # single-completion scorer (training + eval) +│ ├── reward_fns.py # TRL-compatible reward callables +│ ├── dataset.py # build training / eval datasets +│ └── loop.py # Unsloth + TRL GRPO loop (cloud A100) +├── frontend/ # React + TS + Tailwind demo UI +│ └── src/ +│ ├── App.tsx # tabs: "Run with LLM" + "Manual" +│ ├── components/ # RunWithLlmPane, InteractivePane, … +│ ├── hooks/ # useLlmEpisodeRunner, useInteractiveSession +│ ├── lib/ # interactiveClient, trajectory, format +│ └── types/physix.ts +└── tests/ # full pipeline coverage incl. /interactive/* +``` + +--- + +## What the env does (one episode end-to-end) + +```mermaid +sequenceDiagram + participant Agent + participant Env as PhysiXEnvironment + participant Sim as scipy.odeint + participant Verifier + + Env->>Agent: reset(): observed trajectory + hint + loop up to 8 turns + Agent->>Env: step(SymPy eqn + params + rationale) + Env->>Sim: simulate from hypothesis + Sim-->>Verifier: predicted trajectory + Verifier-->>Env: r_match + r_progress + r_simplicity + r_format + Env->>Agent: obs (mismatch summary, history) + reward + alt r_match > 0.93 or budget exhausted + Env-->>Agent: done=True + end + end +``` + +**Action space:** the agent emits structured text in a constrained SymPy grammar +(`d2y/dt2 = -9.81 + 0.05 * vy**2`). Allowed operators: `+ - * / **`. Allowed +functions: `sin cos tan exp log sqrt abs`. Parse failures score `r_format = 0`. + +**Reward:** four independent components (each in `[0, 1]`), weighted into a total. + +| Component | Weight | What it measures | +|---|---:|---| +| `r_match` | 0.5 | Per-step R² between observed and predicted trajectory | +| `r_progress` | 0.2 | Improvement over prior turn (dense per-turn shaping) | +| `r_simplicity` | 0.2 | 1 − normalised operator count (Occam's razor) | +| `r_format` | 0.1 | Binary: SymPy parses + dimensional consistency | + +The reward is fully verifiable — the env never calls an LLM-as-judge. + +--- + +## Quick start + +### 1. Install (Python) + +Requires Python 3.10+. Inside a fresh conda env or venv: + +```bash +pip install -e . # base deps (env server, verifier, client) +pip install -e ".[dev]" # + pytest, ruff +pip install -e ".[demo]" # + ollama (live LLM episodes via /interactive/llm-step) +pip install -e ".[train]" # + torch, transformers, trl, unsloth, wandb +``` + +Notes: +- `[train]` requires CUDA. Install it on the cloud A100 box, not on your laptop. +- `[demo]` adds the `ollama` Python client used by the server when the UI's + "Run with LLM" pane drives an episode. Start `ollama serve` and pull the + base model once with `ollama pull qwen2.5:1.5b-instruct`. +- The repo ships a `.vscode/settings.json` that pins the workspace's Python + interpreter to `~/miniconda3/envs/openenv_run/bin/python`. If your venv + lives somewhere else and your IDE shows "import could not be resolved", + update that path or run **Python: Select Interpreter** from the command + palette. + +### 2. Run the test suite + +```bash +pytest tests/ # 30 tests, ~3 seconds +``` + +### 3. Boot the env server locally + +```bash +python -m physix.server.app --host 127.0.0.1 --port 8000 +# or +uvicorn physix.server.app:app --host 127.0.0.1 --port 8000 +``` + +The server exposes: + +- OpenEnv endpoints: `/reset`, `/step`, `/state`, `/schema`, `/health`. These + are stateless — each request gets a fresh env. Fine for headless agents. +- A stateful WebSocket at `/ws` (used by the Python `PhysiXEnv` client). +- A bespoke session-based REST router at `/interactive/*` (see + `physix/server/interactive.py`) used by the demo UI. It maintains + in-process sessions so a browser can drive a multi-turn episode by + POSTing equations. + +CORS is enabled out of the box for `http://localhost:5173` (the Vite dev +server). Override with `PHYSIX_CORS_ORIGINS=https://your-host.example` (or +`*` for any origin, dev only). + +For sustained Python-side interaction use the WebSocket client: + +```python +import asyncio +from physix import PhysiXEnv, PhysiXAction + +async def main(): + async with PhysiXEnv(base_url="http://127.0.0.1:8000") as env: + result = await env.reset(system_id="free_fall_drag", seed=42) + result = await env.step( + PhysiXAction(equation="d2y/dt2 = -9.81 + 0.05 * vy**2") + ) + print(result.observation.reward_breakdown) + +asyncio.run(main()) +``` + +### 4. Run the demo UI + +```bash +cd frontend +pnpm install +pnpm dev # http://localhost:5173 +``` + +The UI has two tabs, both backed by the same live env server: + +- **Run with LLM** — pick a system + an Ollama model tag, click ▶ Run, and + watch the model propose ODEs turn-by-turn. Each call hits + `POST /interactive/sessions/:id/llm-step`, which builds the env's prompt, + calls the local Ollama daemon, parses the reply, scores it via the + verifier, and streams the resulting turn back to the page. Pause anytime. +- **Manual** — submit equations yourself. No LLM in the loop. Same scoring + pipeline, useful for building intuition for the verifier. + +The UI expects the env server to be reachable on the URL in +`VITE_PHYSIX_API_URL` (default `http://localhost:8000`). For the LLM tab, +you also need a local Ollama daemon (`ollama serve`) with the model tag +pulled in advance: + +```bash +ollama pull qwen2.5:1.5b-instruct +# or, after exporting your merged adapter to GGUF and building a Modelfile: +ollama create physix-trained:latest -f Modelfile +``` + +There are no pre-recorded episodes to regenerate. Every turn shown in the +UI is a real LLM call against the live env. + +### 5. Train (cloud A100) + +```bash +WANDB_PROJECT=physix-live python -m physix.training.loop \ + --model Qwen/Qwen2.5-1.5B-Instruct \ + --output-dir runs/physix-1.5b-rl \ + --num-steps 300 + +# Run an ablation: +python -m physix.training.loop --num-steps 300 --ablation no_progress +``` + +After training, push the merged adapter to the Hub. By default the loop +saves a `merged_16bit` artifact (LoRA merged into the base, written as a +standard HF checkpoint) so it can be loaded without Unsloth and exported to +GGUF for Ollama: + +```bash +python -m physix.training.loop \ + --num-steps 300 \ + --save-method merged_16bit \ + --push-to-hub --hub-repo-id you/physix-1.5b-rl +``` + +Pass `--save-method lora` if you want the small adapter-only artifact +instead. The training loop calls `unsloth.PatchFastRL("GRPO", FastLanguageModel)` +before importing `GRPOTrainer` — required for Unsloth's GRPO kernels to be +swapped in. + +--- + +## Adding a new physical system + +The framework generalises beyond the 8 shipped systems. Adding a new one is +about 50 lines: + +```python +# physix/systems/tier2.py (or your own module) +import numpy as np +from physix.systems.base import PhysicalSystem, SystemTier + +class CoupledOscillators(PhysicalSystem): + system_id: str = "coupled_oscillators" + tier: SystemTier = SystemTier.TIER_2 + state_variables: tuple[str, ...] = ("x1", "vx1", "x2", "vx2") + hint_template: str = "Two masses coupled by a spring; observe both positions." + + def sample_parameters(self, rng): + return {"k": float(rng.uniform(2, 10)), "k_c": float(rng.uniform(0.5, 2))} + + def sample_initial_conditions(self, rng): + return {"x1": float(rng.uniform(0.5, 1)), "vx1": 0.0, "x2": 0.0, "vx2": 0.0} + + def rhs(self, t, state, params): + x1, vx1, x2, vx2 = state + return np.array([ + vx1, -params["k"] * x1 + params["k_c"] * (x2 - x1), + vx2, -params["k"] * x2 + params["k_c"] * (x1 - x2), + ]) + + def ground_truth_equation(self) -> str: + return "d2x1/dt2 = -k*x1 + k_c*(x2-x1); d2x2/dt2 = -k*x2 + k_c*(x1-x2)" +``` + +`PhysicalSystem` is a Pydantic model with an `ABCMeta` mixin — subclasses +declare overridden fields as plain class-level annotations and pydantic +treats them as field overrides. No `@dataclass` decorator needed. + +Then register it in `physix/systems/registry.py`: + +```python +SYSTEM_REGISTRY["coupled_oscillators"] = CoupledOscillators +``` + +That's it — the env, parser, simulator, scorer, and training loop all pick it +up automatically. + +--- + +## Themes (OpenEnv hackathon rubric) + +- **Primary: World-Modeling** — the agent literally builds an internal model + of physical dynamics from data + context, refines it, and is scored against + ground truth. +- **Primary: Long-Horizon** — episodes are 5-8 turns of stateful refinement; + earlier hypotheses condition later ones via the prompt history. +- **Secondary: Self-Improvement** — curriculum from 1-D undamped (Tier 1) + through 1-D damped (Tier 2) to 2-D coupled (Tier 3, held out). + +--- + +## Honest framing + +We do **not** claim: + +- The env discovers genuinely new physics. +- A 1.5B model beats GPT-4o on equation discovery. +- The model learns physics from scratch. + +We **do** claim: + +- The same 1.5B converges in fewer turns *after* RL training than *before*. +- The trained model generalises to held-out 2-D systems (Tier 3). +- The trained model uses NL hints meaningfully (ablate the hint, performance drops). + +This calibrated framing is part of the storytelling axis (30%) — judges trust +self-comparison numbers more than claims to beat frontier models. + +--- + +## License + +MIT. diff --git a/physix-live/physix/__init__.py b/physix-live/physix/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..61cec6bd1cd93e0823b7005ab87015edbfa55ade --- /dev/null +++ b/physix-live/physix/__init__.py @@ -0,0 +1,32 @@ +"""PhysiX-Live: OpenEnv environment for iterative equation discovery. + +Public API: + +- :class:`PhysiXEnv`: the OpenEnv client (HTTP/WebSocket). +- :class:`PhysiXAction`, :class:`PhysiXObservation`, :class:`PhysiXState`: + the env's wire-protocol Pydantic models. +- :class:`RewardBreakdown`: 4-component reward record. +- :data:`GRAMMAR_HINT`: machine-generated DSL description for the LLM + system prompt (single source of truth: :mod:`physix.verifier.parser`). +""" + +from physix.client import PhysiXEnv +from physix.models import ( + PhysiXAction, + PhysiXObservation, + PhysiXState, + RewardBreakdown, +) +from physix.verifier.parser import GRAMMAR_HINT + + +__version__ = "0.1.0" +__all__ = [ + "PhysiXEnv", + "PhysiXAction", + "PhysiXObservation", + "PhysiXState", + "RewardBreakdown", + "GRAMMAR_HINT", + "__version__", +] diff --git a/physix-live/physix/__pycache__/__init__.cpython-311.pyc b/physix-live/physix/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a24ea1e448ba88ac2e6b4f6c63e7940c9f879cd Binary files /dev/null and b/physix-live/physix/__pycache__/__init__.cpython-311.pyc differ diff --git a/physix-live/physix/__pycache__/adapters.cpython-311.pyc b/physix-live/physix/__pycache__/adapters.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..466549b07e67522ac3115e0acbfec3d454aa346a Binary files /dev/null and b/physix-live/physix/__pycache__/adapters.cpython-311.pyc differ diff --git a/physix-live/physix/__pycache__/client.cpython-311.pyc b/physix-live/physix/__pycache__/client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a7e9a143232d37a9111179acce3aec7a1d797d0 Binary files /dev/null and b/physix-live/physix/__pycache__/client.cpython-311.pyc differ diff --git a/physix-live/physix/__pycache__/models.cpython-311.pyc b/physix-live/physix/__pycache__/models.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a26151152662877c0b16fa90ca1be33b3efe658c Binary files /dev/null and b/physix-live/physix/__pycache__/models.cpython-311.pyc differ diff --git a/physix-live/physix/client.py b/physix-live/physix/client.py new file mode 100644 index 0000000000000000000000000000000000000000..db6e66af9fb92e35f711544011f4143df3c1c7d4 --- /dev/null +++ b/physix-live/physix/client.py @@ -0,0 +1,43 @@ +"""HTTP/WebSocket client for the PhysiX-Live environment. + +Subclasses :class:`openenv.core.EnvClient` to provide PhysiX-specific +serialisation and parsing. The base class handles WebSocket connection, +session management, and the OpenEnv wire protocol. +""" + +from __future__ import annotations + +from typing import Any + +from openenv.core import EnvClient +from openenv.core.client_types import StepResult + +from physix.models import PhysiXAction, PhysiXObservation, PhysiXState + + +class PhysiXEnv(EnvClient[PhysiXAction, PhysiXObservation, PhysiXState]): + """Client for the PhysiX-Live OpenEnv environment. + + Example:: + + >>> async with PhysiXEnv(base_url="http://localhost:8000") as env: + ... result = await env.reset() + ... while not result.done: + ... action = agent.predict(result.observation) + ... result = await env.step(action) + """ + + def _step_payload(self, action: PhysiXAction) -> dict[str, Any]: + return action.model_dump(exclude_none=False) + + def _parse_result(self, payload: dict[str, Any]) -> StepResult[PhysiXObservation]: + observation_data = payload.get("observation", {}) or {} + observation = PhysiXObservation(**observation_data) + return StepResult( + observation=observation, + reward=payload.get("reward"), + done=payload.get("done", False), + ) + + def _parse_state(self, payload: dict[str, Any]) -> PhysiXState: + return PhysiXState(**payload) diff --git a/physix-live/physix/models.py b/physix-live/physix/models.py new file mode 100644 index 0000000000000000000000000000000000000000..add1d3690f3625e3492b1718c134788e454b0666 --- /dev/null +++ b/physix-live/physix/models.py @@ -0,0 +1,138 @@ +"""Pydantic schemas + constants. Behaviour lives elsewhere.""" + +from __future__ import annotations + +from typing import Any + +from pydantic import BaseModel, ConfigDict, Field + +from openenv.core.env_server import Action, Observation, State + + +#: Per-episode turn budget. Episodes terminate earlier if r_match crosses +#: :data:`CONVERGENCE_THRESHOLD`. +DEFAULT_MAX_TURNS: int = 8 +CONVERGENCE_THRESHOLD: float = 0.93 + +#: Reward component weights. Ablations only edit this dict. +REWARD_WEIGHTS: dict[str, float] = { + "match": 0.5, + "progress": 0.2, + "simplicity": 0.2, + "format": 0.1, +} + + +class PhysiXAction(Action): + """One agent step. + + Fields have defaults so tests can construct partial actions, and so + the env can fabricate a ``format=0`` no-op action for completions + that fail to parse JSON. The LLM is expected to fill all three; + an empty string / dict is fine when irrelevant. + """ + + equation: str = Field(default="", description="ODE in the verifier DSL") + params: dict[str, float] = Field( + default_factory=dict, + description="Numerical substitutions for free symbols on the RHS", + ) + rationale: str = Field(default="") + + +class PhysiXObservation(Observation): + """What the agent sees per step. Inherits ``done`` / ``reward`` from + :class:`openenv.core.env_server.Observation`.""" + + trajectory: list[dict[str, float]] = Field( + default_factory=list, + description="Observed (noisy) trajectory as list of timestep dicts", + ) + state_variables: list[str] = Field( + default_factory=list, + description="Names of state-variable keys present in trajectory[i] (excluding t)", + ) + hint: str = Field(default="", description="One-sentence physical-context string") + history: list[dict[str, Any]] = Field( + default_factory=list, + description="Prior turns surfaced back so the agent can refine", + ) + mismatch_summary: str = Field( + default="", + description="English description of where last prediction diverged", + ) + turn: int = Field(default=0, ge=0, description="0-indexed turn counter") + turn_remaining: int = Field( + default=DEFAULT_MAX_TURNS, + ge=0, + description="Turns left in the episode budget", + ) + system_id: str = Field(default="", description="Stable id of underlying system") + stats: dict[str, float] = Field( + default_factory=dict, description="Aggregate trajectory statistics" + ) + reward_breakdown: dict[str, float] = Field( + default_factory=dict, + description="Four reward components from the previous step", + ) + + +class PhysiXState(State): + """Episode-level state. The ground-truth equation lives here for logging; + it is *never* surfaced to the agent. ``last_reward_total`` feeds the + per-turn ``progress`` reward delta.""" + + system_id: str = Field(default="") + ground_truth_equation: str = Field(default="") + ground_truth_params: dict[str, float] = Field(default_factory=dict) + last_reward_total: float = Field(default=0.0) + last_r_match: float = Field(default=0.0) + converged: bool = Field(default=False) + max_turns: int = Field(default=DEFAULT_MAX_TURNS, ge=1) + + +class HistoryEntry(BaseModel): + """One previous turn, surfaced back to the agent on the next step.""" + + model_config = ConfigDict(extra="forbid") + + turn: int + equation: str + params: dict[str, float] + reward_total: float + reward_components: dict[str, float] + mismatch_summary: str + + def as_dict(self) -> dict[str, Any]: + return { + "turn": self.turn, + "equation": self.equation, + "params": self.params, + "reward_total": round(self.reward_total, 4), + "reward_components": { + k: round(v, 4) for k, v in self.reward_components.items() + }, + "mismatch_summary": self.mismatch_summary, + } + + +class RewardBreakdown(BaseModel): + """4-component reward, each in ``[0, 1]``. ``total`` is the weighted sum + using :data:`REWARD_WEIGHTS`.""" + + model_config = ConfigDict(extra="forbid") + + match: float = 0.0 + progress: float = 0.0 + simplicity: float = 0.0 + format: float = 0.0 + total: float = 0.0 + + def as_dict(self) -> dict[str, float]: + return { + "match": self.match, + "progress": self.progress, + "simplicity": self.simplicity, + "format": self.format, + "total": self.total, + } diff --git a/physix-live/physix/server/__init__.py b/physix-live/physix/server/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..40447df552d157feec81fb82ebeafcf10a495c2c --- /dev/null +++ b/physix-live/physix/server/__init__.py @@ -0,0 +1,8 @@ +"""HTTP server layer for the PhysiX-Live environment. + +Submodules: +- :mod:`physix.server.environment` defines the OpenEnv ``Environment`` subclass + that owns episode lifecycle and reward dispatch. +- :mod:`physix.server.app` builds the FastAPI application and exposes a + ``main()`` entry point for the ``physix-server`` console script. +""" diff --git a/physix-live/physix/server/__pycache__/__init__.cpython-311.pyc b/physix-live/physix/server/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a8cb725e968da9fa9b5a27c9d63c53714bc5a90 Binary files /dev/null and b/physix-live/physix/server/__pycache__/__init__.cpython-311.pyc differ diff --git a/physix-live/physix/server/__pycache__/app.cpython-311.pyc b/physix-live/physix/server/__pycache__/app.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca4fa005d4cebc70a21668f13302882e1f90c68b Binary files /dev/null and b/physix-live/physix/server/__pycache__/app.cpython-311.pyc differ diff --git a/physix-live/physix/server/__pycache__/environment.cpython-311.pyc b/physix-live/physix/server/__pycache__/environment.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fef1f1e2e1d6eca101f613f6922a0347f114be0 Binary files /dev/null and b/physix-live/physix/server/__pycache__/environment.cpython-311.pyc differ diff --git a/physix-live/physix/server/__pycache__/interactive.cpython-311.pyc b/physix-live/physix/server/__pycache__/interactive.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c229ed79bbf3569c986180f62b732f6df3f01d9 Binary files /dev/null and b/physix-live/physix/server/__pycache__/interactive.cpython-311.pyc differ diff --git a/physix-live/physix/server/app.py b/physix-live/physix/server/app.py new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2b668fc5b9084b3e454c8ba49a895e6018b --- /dev/null +++ b/physix-live/physix/server/app.py @@ -0,0 +1,117 @@ +"""FastAPI app + ``physix-server`` console-script entry point. + +Mounts the OpenEnv stateless endpoints (``/reset`` etc.) plus the bespoke +``/interactive/*`` router that maintains in-process sessions for browsers. +CORS allows the Vite dev origin out of the box; override with the +``PHYSIX_CORS_ORIGINS`` env var (comma-separated, or ``*`` for any). +""" + +from __future__ import annotations + +import argparse +import logging +import os + +import uvicorn +from fastapi import FastAPI, Request +from fastapi.exceptions import RequestValidationError +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import JSONResponse +from openenv.core.env_server import create_fastapi_app +from starlette.exceptions import HTTPException as StarletteHTTPException + +from physix.models import PhysiXAction, PhysiXObservation +from physix.server.environment import PhysiXEnvironment +from physix.server.interactive import build_interactive_router + + +_DEFAULT_CORS_ORIGINS = ( + "http://localhost:5173", + "http://127.0.0.1:5173", +) + + +def build_app() -> FastAPI: + app = create_fastapi_app( + env=PhysiXEnvironment, + action_cls=PhysiXAction, + observation_cls=PhysiXObservation, + ) + _install_cors(app) + _install_error_handlers(app) + app.include_router(build_interactive_router()) + return app + + +def _install_cors(app: FastAPI) -> None: + raw = os.environ.get("PHYSIX_CORS_ORIGINS", "") + origins = ( + [o.strip() for o in raw.split(",") if o.strip()] + if raw + else list(_DEFAULT_CORS_ORIGINS) + ) + allow_all = origins == ["*"] + app.add_middleware( + CORSMiddleware, + allow_origins=origins if not allow_all else ["*"], + allow_credentials=not allow_all, + allow_methods=["*"], + allow_headers=["*"], + ) + + +def _install_error_handlers(app: FastAPI) -> None: + """Make sure 4xx/5xx responses still carry the request's CORS headers. + + Starlette's ``CORSMiddleware`` only annotates responses produced by + successful route handlers; raw ``HTTPException`` responses skip the + middleware and reach the browser without ``Access-Control-Allow-Origin``, + which the browser surfaces as a generic network error rather than the + real status code (e.g. 502 "Ollama not reachable" was reported as 404 + in the dev UI). Re-emitting through ``JSONResponse`` runs the middleware. + """ + + @app.exception_handler(StarletteHTTPException) + async def _http_exc(_request: Request, exc: StarletteHTTPException) -> JSONResponse: + return JSONResponse( + status_code=exc.status_code, + content={"detail": exc.detail}, + headers=exc.headers, + ) + + @app.exception_handler(RequestValidationError) + async def _validation_exc( + _request: Request, exc: RequestValidationError + ) -> JSONResponse: + return JSONResponse(status_code=422, content={"detail": exc.errors()}) + + +app: FastAPI = build_app() + + +def main() -> None: + parser = argparse.ArgumentParser(description="Run the PhysiX-Live env server.") + parser.add_argument("--host", default=os.environ.get("PHYSIX_HOST", "0.0.0.0")) + parser.add_argument("--port", type=int, default=int(os.environ.get("PORT", "8000"))) + parser.add_argument( + "--log-level", default=os.environ.get("PHYSIX_LOG_LEVEL", "info") + ) + parser.add_argument( + "--reload", + action="store_true", + help="Auto-reload on source changes. Use during development only.", + ) + args = parser.parse_args() + + logging.basicConfig(level=args.log_level.upper()) + uvicorn.run( + "physix.server.app:app", + host=args.host, + port=args.port, + log_level=args.log_level, + reload=args.reload, + ) + + +if __name__ == "__main__": + main() diff --git a/physix-live/physix/server/environment.py b/physix-live/physix/server/environment.py new file mode 100644 index 0000000000000000000000000000000000000000..ed3afb74ab9a75311546ae727f64fbec12792f57 --- /dev/null +++ b/physix-live/physix/server/environment.py @@ -0,0 +1,280 @@ +"""OpenEnv :class:`Environment` subclass for PhysiX-Live. + +Owns one episode's lifecycle (state + budget + termination) and orchestrates +the parser/simulator/metrics/reward modules. No scoring logic lives here. +""" + +from __future__ import annotations + +import logging +import uuid +from typing import Any, Optional + +import numpy as np +from openenv.core.env_server import Environment + +from physix.models import ( + CONVERGENCE_THRESHOLD, + DEFAULT_MAX_TURNS, + HistoryEntry, + PhysiXAction, + PhysiXObservation, + PhysiXState, + RewardBreakdown, +) +from physix.systems import PhysicalSystem, SystemTier, get_system, list_systems_by_tier +from physix.systems.base import TrajectoryData +from physix.verifier import ( + ParseError, + SimulationError, + compute_match, + compute_reward, + parse_equation, + residual_summary, + simulate_hypothesis, + summarize_mismatch, +) + + +_log = logging.getLogger(__name__) + + +class PhysiXEnvironment(Environment[PhysiXAction, PhysiXObservation, PhysiXState]): + """OpenEnv environment that drives one episode of equation discovery.""" + + def __init__( + self, + *, + max_turns: int = DEFAULT_MAX_TURNS, + train_tiers: tuple[SystemTier, ...] = (SystemTier.TIER_1, SystemTier.TIER_2), + seed: Optional[int] = None, + ) -> None: + super().__init__() + self._max_turns = max_turns + self._train_tiers = train_tiers + self._rng = np.random.default_rng(seed) + + self._state = PhysiXState(max_turns=max_turns) + self._system: Optional[PhysicalSystem] = None + self._trajectory: Optional[TrajectoryData] = None + self._history: list[HistoryEntry] = [] + + def reset( + self, + seed: Optional[int] = None, + episode_id: Optional[str] = None, + **kwargs: Any, + ) -> PhysiXObservation: + """Start a new episode. Pass ``system_id=`` to force a specific system.""" + if seed is not None: + self._rng = np.random.default_rng(seed) + + forced_id = kwargs.get("system_id") + chosen_id = forced_id or self._sample_training_system_id() + + self._system = get_system(chosen_id) + self._trajectory = self._system.simulate(self._rng) + self._history = [] + + self._state = PhysiXState( + episode_id=episode_id or str(uuid.uuid4()), + step_count=0, + system_id=chosen_id, + ground_truth_equation=self._system.ground_truth_equation(), + ground_truth_params=dict(self._system.parameters), + last_reward_total=0.0, + converged=False, + max_turns=self._max_turns, + ) + + return self._build_observation( + mismatch_summary="", + reward_breakdown=RewardBreakdown(), + ) + + def step( + self, + action: PhysiXAction, + timeout_s: Optional[float] = None, + **kwargs: Any, + ) -> PhysiXObservation: + del timeout_s, kwargs # accepted for OpenEnv API conformance, unused + + if self._system is None or self._trajectory is None: + raise RuntimeError("step() called before reset(); call reset() first.") + + self._state.step_count = self._state.step_count + 1 + + breakdown, mismatch_text = self._score_hypothesis(action) + self._record_history(action, breakdown, mismatch_text) + + self._state.last_reward_total = breakdown.total + self._state.last_r_match = breakdown.match + if breakdown.match >= CONVERGENCE_THRESHOLD: + self._state.converged = True + + return self._build_observation( + mismatch_summary=mismatch_text, + reward_breakdown=breakdown, + ) + + @property + def state(self) -> PhysiXState: + return self._state + + def current_observation(self) -> Optional[PhysiXObservation]: + """Re-render the observation an external driver should feed to the + agent for the *next* turn (i.e. before calling :meth:`step`). + + Used by the interactive HTTP router to build prompts mid-session. + Returns ``None`` before :meth:`reset` has been called. + """ + if self._system is None or self._trajectory is None: + return None + last = self._history[-1] if self._history else None + breakdown = ( + RewardBreakdown(**last.reward_components) + if last is not None + else RewardBreakdown() + ) + mismatch = last.mismatch_summary if last is not None else "" + return self._build_observation( + mismatch_summary=mismatch, + reward_breakdown=breakdown, + ) + + @property + def current_trajectory(self) -> Optional[TrajectoryData]: + return self._trajectory + + @property + def current_system(self) -> Optional[PhysicalSystem]: + return self._system + + def _is_done(self) -> bool: + if self._state.converged: + return True + return self._state.step_count >= self._max_turns + + def _score_hypothesis( + self, + action: PhysiXAction, + ) -> tuple[RewardBreakdown, str]: + assert self._system is not None + assert self._trajectory is not None + + parameter_names = frozenset(action.params or {}) + + try: + parsed = parse_equation( + action.equation, + state_variables=self._system.state_variables, + parameter_names=parameter_names, + ) + except ParseError as exc: + _log.debug("parse_equation failed: %s", exc) + breakdown = compute_reward( + parse_succeeded=False, + r_match=0.0, + operator_count=0, + previous_r_match=self._state.last_r_match, + ) + return breakdown, f"Parse error: {exc}" + + try: + predicted = simulate_hypothesis( + parsed, + state_variables=self._system.state_variables, + parameters=dict(action.params or {}), + initial_conditions=self._trajectory.initial_conditions, + timestamps=self._trajectory.timestamps, + ) + except SimulationError as exc: + _log.debug("simulate_hypothesis failed: %s", exc) + breakdown = compute_reward( + parse_succeeded=True, + simulation_succeeded=False, + r_match=0.0, + operator_count=parsed.operator_count, + previous_r_match=self._state.last_r_match, + ) + return breakdown, f"Simulation error: {exc}" + + r_match = compute_match( + observed=self._trajectory.states, + predicted=predicted, + state_variables=self._system.state_variables, + ) + residuals = residual_summary( + timestamps=self._trajectory.timestamps, + observed=self._trajectory.states, + predicted=predicted, + state_variables=self._system.state_variables, + ) + mismatch_text = summarize_mismatch( + observed=self._trajectory.states, + predicted=predicted, + state_variables=self._system.state_variables, + timestamps=self._trajectory.timestamps, + summary=residuals, + ) + + breakdown = compute_reward( + parse_succeeded=True, + simulation_succeeded=True, + r_match=r_match, + operator_count=parsed.operator_count, + previous_r_match=self._state.last_r_match, + ) + return breakdown, mismatch_text + + def _record_history( + self, + action: PhysiXAction, + breakdown: RewardBreakdown, + mismatch_text: str, + ) -> None: + entry = HistoryEntry( + turn=self._state.step_count, + equation=action.equation, + params=dict(action.params or {}), + reward_total=breakdown.total, + reward_components=breakdown.as_dict(), + mismatch_summary=mismatch_text, + ) + self._history.append(entry) + + def _build_observation( + self, + *, + mismatch_summary: str, + reward_breakdown: RewardBreakdown, + ) -> PhysiXObservation: + assert self._system is not None + assert self._trajectory is not None + + return PhysiXObservation( + done=self._is_done(), + reward=reward_breakdown.total, + trajectory=self._trajectory.to_observation_samples(), + state_variables=list(self._system.state_variables), + hint=self._system.hint(self._state.ground_truth_params), + history=[entry.as_dict() for entry in self._history], + mismatch_summary=mismatch_summary, + turn=self._state.step_count, + turn_remaining=max(0, self._max_turns - self._state.step_count), + system_id=self._state.system_id, + stats=self._trajectory.stats(), + reward_breakdown=reward_breakdown.as_dict(), + ) + + def _sample_training_system_id(self) -> str: + candidates: list[str] = [] + for tier in self._train_tiers: + candidates.extend(list_systems_by_tier(tier)) + if not candidates: + raise RuntimeError( + f"No training systems found for tiers {self._train_tiers!r}." + ) + idx = int(self._rng.integers(0, len(candidates))) + return candidates[idx] diff --git a/physix-live/physix/server/interactive.py b/physix-live/physix/server/interactive.py new file mode 100644 index 0000000000000000000000000000000000000000..fc8c2ac3d5ae63884fa46717073bd207b1445d28 --- /dev/null +++ b/physix-live/physix/server/interactive.py @@ -0,0 +1,430 @@ +"""Session-based REST router for browser-driven episodes.""" + +from __future__ import annotations + +import logging +import threading +import time +import uuid +from collections.abc import Callable +from typing import Optional + +import numpy as np +from fastapi import APIRouter, HTTPException +from pydantic import BaseModel, ConfigDict, Field + +from physix.models import ( + DEFAULT_MAX_TURNS, + PhysiXAction, + PhysiXObservation, +) +from physix.server.environment import PhysiXEnvironment +from physix.systems import list_supported_systems, list_systems +from physix.systems.base import PhysicalSystem, TrajectoryData +from physix.training.prompt import build_prompt, parse_completion +from physix.verifier.parser import parse_equation +from physix.verifier.simulator import simulate_hypothesis + + +_log = logging.getLogger(__name__) + + +class InteractiveResetRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + + system_id: Optional[str] = Field( + default=None, + description="Force a specific system. None = sample at random.", + ) + seed: Optional[int] = None + max_turns: int = Field(default=DEFAULT_MAX_TURNS, ge=1, le=32) + + +class SystemDescriptor(BaseModel): + model_config = ConfigDict(frozen=True) + + system_id: str + state_variables: tuple[str, ...] + + +class InteractiveStartResponse(BaseModel): + session_id: str + observation: PhysiXObservation + system: SystemDescriptor + max_turns: int + + +class LlmStepRequest(BaseModel): + """Server-side LLM call. Browser names a model tag; server hits Ollama.""" + + model_config = ConfigDict(extra="forbid") + + model: str = "qwen2.5:1.5b-instruct" + temperature: float = Field(default=0.4, ge=0.0, le=2.0) + max_tokens: int = Field(default=2048, ge=64, le=8192) + host: Optional[str] = None + + +class LlmModelInfo(BaseModel): + """A single locally-pulled Ollama model tag.""" + + model_config = ConfigDict(frozen=True) + + name: str + size_bytes: Optional[int] = None + parameter_size: Optional[str] = None + family: Optional[str] = None + + +class LlmModelsResponse(BaseModel): + models: list[LlmModelInfo] = Field(default_factory=list) + error: Optional[str] = None + + +class LlmStepResponse(BaseModel): + observation: PhysiXObservation + predicted_trajectory: list[dict[str, float]] = Field(default_factory=list) + action: PhysiXAction + raw_completion: str + latency_s: float + model: str + + +class SessionSummary(BaseModel): + session_id: str + system_id: str + turn: int + max_turns: int + converged: bool + done: bool + + +class _Session: + __slots__ = ("env", "system_id", "max_turns", "lock") + + def __init__(self, env: PhysiXEnvironment, system_id: str, max_turns: int) -> None: + self.env = env + self.system_id = system_id + self.max_turns = max_turns + self.lock = threading.Lock() + + +class InteractiveSessionStore: + """Threadsafe in-memory session map.""" + + def __init__(self) -> None: + self._sessions: dict[str, _Session] = {} + self._lock = threading.Lock() + + def create( + self, + *, + system_id: Optional[str], + seed: Optional[int], + max_turns: int, + ) -> tuple[str, _Session, PhysiXObservation]: + env = PhysiXEnvironment(seed=seed, max_turns=max_turns) + observation = env.reset(seed=seed, system_id=system_id) + session = _Session(env=env, system_id=env.state.system_id, max_turns=max_turns) + session_id = uuid.uuid4().hex + with self._lock: + self._sessions[session_id] = session + return session_id, session, observation + + def get(self, session_id: str) -> _Session: + with self._lock: + session = self._sessions.get(session_id) + if session is None: + raise HTTPException(status_code=404, detail="Unknown session_id.") + return session + + def delete(self, session_id: str) -> None: + with self._lock: + self._sessions.pop(session_id, None) + + def __len__(self) -> int: + with self._lock: + return len(self._sessions) + + +LlmPolicy = Callable[[list[dict[str, str]]], str] +LlmPolicyFactory = Callable[[LlmStepRequest], LlmPolicy] +LlmModelsLister = Callable[[], LlmModelsResponse] + + +def default_ollama_models_lister() -> LlmModelsResponse: + try: + import ollama # type: ignore[import-not-found] + except ImportError: + return LlmModelsResponse( + models=[], + error=( + "The 'ollama' Python package is not installed on the server. " + "Install with: pip install -e '.[demo]'" + ), + ) + + try: + response = ollama.Client().list() + except Exception as exc: # noqa: BLE001 — surfaced in the response body + return LlmModelsResponse( + models=[], + error=( + f"Could not reach the local Ollama daemon ({exc}). " + "Is 'ollama serve' running?" + ), + ) + + raw_models = getattr(response, "models", None) + if raw_models is None and isinstance(response, dict): + raw_models = response.get("models", []) + raw_models = raw_models or [] + + out: list[LlmModelInfo] = [] + for entry in raw_models: + name = _model_attr(entry, "model") or _model_attr(entry, "name") + if not isinstance(name, str) or not name: + continue + details = _model_attr(entry, "details") + out.append( + LlmModelInfo( + name=name, + size_bytes=_coerce_int(_model_attr(entry, "size")), + parameter_size=_model_attr(details, "parameter_size"), + family=_model_attr(details, "family"), + ) + ) + + out.sort(key=lambda m: m.name) + return LlmModelsResponse(models=out) + + +def _model_attr(obj: object, key: str) -> object: + if obj is None: + return None + if isinstance(obj, dict): + return obj.get(key) + return getattr(obj, key, None) + + +def _coerce_int(value: object) -> Optional[int]: + if value is None: + return None + try: + return int(value) + except (TypeError, ValueError): + return None + + +def default_ollama_policy_factory(request: LlmStepRequest) -> LlmPolicy: + try: + import ollama # type: ignore[import-not-found] + except ImportError as exc: # pragma: no cover + raise HTTPException( + status_code=503, + detail=( + "The 'ollama' Python package is not installed on the server. " + "Install with: pip install -e '.[demo]'" + ), + ) from exc + + client = ollama.Client(host=request.host) if request.host else ollama.Client() + + def _policy(prompt: list[dict[str, str]]) -> str: + try: + response = client.chat( + model=request.model, + messages=prompt, + format="json", + options={ + "temperature": request.temperature, + "num_predict": request.max_tokens, + }, + ) + except Exception as exc: # noqa: BLE001 — surfaced as 502 + raise HTTPException( + status_code=502, + detail=( + f"Ollama call failed for model {request.model!r}: {exc}. " + "Is 'ollama serve' running and the model pulled " + f"('ollama pull {request.model}')?" + ), + ) from exc + return str(response["message"]["content"]) + + return _policy + + +def build_interactive_router( + store: Optional[InteractiveSessionStore] = None, + *, + policy_factory: LlmPolicyFactory = default_ollama_policy_factory, + models_lister: LlmModelsLister = default_ollama_models_lister, +) -> APIRouter: + sessions = store if store is not None else InteractiveSessionStore() + router = APIRouter(prefix="/interactive", tags=["Interactive"]) + + @router.get("/models", response_model=LlmModelsResponse) + def list_local_models() -> LlmModelsResponse: + return models_lister() + + @router.get("/systems", response_model=list[SystemDescriptor]) + def list_public_systems() -> list[SystemDescriptor]: + from physix.systems import get_system + + out: list[SystemDescriptor] = [] + for system_id in list_supported_systems(): + system = get_system(system_id) + out.append( + SystemDescriptor( + system_id=system.system_id, + state_variables=system.state_variables, + ) + ) + return out + + @router.post("/sessions", response_model=InteractiveStartResponse) + def start_session(payload: InteractiveResetRequest) -> InteractiveStartResponse: + from physix.systems import get_system + + if payload.system_id is not None and payload.system_id not in list_systems(): + raise HTTPException( + status_code=400, detail=f"Unknown system_id {payload.system_id!r}." + ) + chosen_system_id = payload.system_id + if chosen_system_id is None: + demo_ids = list_supported_systems() + if demo_ids: + rng = ( + np.random.default_rng(payload.seed) + if payload.seed is not None + else np.random.default_rng() + ) + chosen_system_id = str(rng.choice(demo_ids)) + session_id, session, observation = sessions.create( + system_id=chosen_system_id, + seed=payload.seed, + max_turns=payload.max_turns, + ) + system = get_system(session.system_id) + return InteractiveStartResponse( + session_id=session_id, + observation=observation, + system=SystemDescriptor( + system_id=system.system_id, + state_variables=system.state_variables, + ), + max_turns=session.max_turns, + ) + + @router.post( + "/sessions/{session_id}/llm-step", response_model=LlmStepResponse + ) + def llm_step_session( + session_id: str, payload: LlmStepRequest + ) -> LlmStepResponse: + session = sessions.get(session_id) + with session.lock: + _ensure_budget(session) + + current_obs = session.env.current_observation() + if current_obs is None: + raise HTTPException( + status_code=500, detail="Session has no current observation." + ) + + policy = policy_factory(payload) + t0 = time.perf_counter() + raw_completion = policy(build_prompt(current_obs)) + latency_s = time.perf_counter() - t0 + + action = parse_completion(raw_completion) + observation = session.env.step(action) + predicted = _safe_predict(session.env, action) + + return LlmStepResponse( + observation=observation, + predicted_trajectory=predicted, + action=action, + raw_completion=raw_completion, + latency_s=latency_s, + model=payload.model, + ) + + @router.delete("/sessions/{session_id}", status_code=204) + def end_session(session_id: str) -> None: + sessions.delete(session_id) + + @router.get("/sessions/{session_id}", response_model=SessionSummary) + def get_session(session_id: str) -> SessionSummary: + session = sessions.get(session_id) + return SessionSummary( + session_id=session_id, + system_id=session.system_id, + turn=session.env.state.step_count, + max_turns=session.max_turns, + converged=session.env.state.converged, + done=( + session.env.state.converged + or session.env.state.step_count >= session.max_turns + ), + ) + + return router + + +def _ensure_budget(session: _Session) -> None: + if session.env.state.step_count >= session.max_turns: + raise HTTPException( + status_code=409, + detail="Episode budget already exhausted; start a new session.", + ) + + +def _safe_predict( + env: PhysiXEnvironment, action: PhysiXAction +) -> list[dict[str, float]]: + """Forward-simulate the user's hypothesis for the UI overlay. + + Returns ``[]`` on parse / simulation failure — the env's reward is + authoritative; this is best-effort visualisation only. + """ + system: Optional[PhysicalSystem] = env.current_system + trajectory: Optional[TrajectoryData] = env.current_trajectory + if system is None or trajectory is None: + return [] + + parameter_names = frozenset(action.params or {}) | frozenset(system.parameters) + try: + parsed = parse_equation( + action.equation, + state_variables=system.state_variables, + parameter_names=parameter_names, + ) + except Exception as exc: # noqa: BLE001 + _log.debug("predict parse failed: %s", exc) + return [] + + merged = {**system.parameters, **(action.params or {})} + try: + predicted = simulate_hypothesis( + parsed, + state_variables=system.state_variables, + parameters=merged, + initial_conditions=trajectory.initial_conditions, + timestamps=trajectory.timestamps, + ) + except Exception as exc: # noqa: BLE001 + _log.debug("predict simulate failed: %s", exc) + return [] + + samples: list[dict[str, float]] = [] + for i, t in enumerate(trajectory.timestamps): + sample: dict[str, float] = {"t": round(float(t), 5)} + for var in system.state_variables: + value = predicted[var][i] + if not np.isfinite(value): + return [] + sample[var] = round(float(value), 5) + samples.append(sample) + return samples diff --git a/physix-live/physix/systems/__init__.py b/physix-live/physix/systems/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..975e65d994b512009978a6ce72d626467301577f --- /dev/null +++ b/physix-live/physix/systems/__init__.py @@ -0,0 +1,20 @@ +from physix.systems.base import PhysicalSystem, SystemTier +from physix.systems.registry import ( + SUPPORTED_SYSTEMS, + SYSTEM_REGISTRY, + get_system, + list_supported_systems, + list_systems, + list_systems_by_tier, +) + +__all__ = [ + "PhysicalSystem", + "SystemTier", + "SYSTEM_REGISTRY", + "SUPPORTED_SYSTEMS", + "get_system", + "list_systems", + "list_systems_by_tier", + "list_supported_systems", +] diff --git a/physix-live/physix/systems/__pycache__/__init__.cpython-311.pyc b/physix-live/physix/systems/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37557b22f9ec019b882573763954b695f92607d3 Binary files /dev/null and b/physix-live/physix/systems/__pycache__/__init__.cpython-311.pyc differ diff --git a/physix-live/physix/systems/__pycache__/base.cpython-311.pyc b/physix-live/physix/systems/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2bb3f70dcc0447c340754f94c9802861258bc42 Binary files /dev/null and b/physix-live/physix/systems/__pycache__/base.cpython-311.pyc differ diff --git a/physix-live/physix/systems/__pycache__/registry.cpython-311.pyc b/physix-live/physix/systems/__pycache__/registry.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fde3ade786ec20a1465374139f32ff6f10cad4b8 Binary files /dev/null and b/physix-live/physix/systems/__pycache__/registry.cpython-311.pyc differ diff --git a/physix-live/physix/systems/__pycache__/tier1.cpython-311.pyc b/physix-live/physix/systems/__pycache__/tier1.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98c671fe4e90f0e9381afbcf70ec7e8ee130936c Binary files /dev/null and b/physix-live/physix/systems/__pycache__/tier1.cpython-311.pyc differ diff --git a/physix-live/physix/systems/__pycache__/tier2.cpython-311.pyc b/physix-live/physix/systems/__pycache__/tier2.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fbfc3580374e59a7cb26a4dbcfe8d12b64e86445 Binary files /dev/null and b/physix-live/physix/systems/__pycache__/tier2.cpython-311.pyc differ diff --git a/physix-live/physix/systems/__pycache__/tier3.cpython-311.pyc b/physix-live/physix/systems/__pycache__/tier3.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84d568a0803d3516bb7d1c1aac47c542724f0542 Binary files /dev/null and b/physix-live/physix/systems/__pycache__/tier3.cpython-311.pyc differ diff --git a/physix-live/physix/systems/base.py b/physix-live/physix/systems/base.py new file mode 100644 index 0000000000000000000000000000000000000000..068757e4bdf1278cb78b58a99c6f45b958a23fb4 --- /dev/null +++ b/physix-live/physix/systems/base.py @@ -0,0 +1,192 @@ +"""Abstract base class and shared types for physical systems. + +A physical system is responsible for three things and three things only: + +1. Exposing **stable metadata** (id, tier, state-variable names, NL hint). +2. Generating a **noisy trajectory** for one episode given an RNG seed. +3. Reporting its **ground-truth equation** as a canonical SymPy expression + for logging and verification. + +Reward computation, simulation of the *agent's* hypotheses, residual analysis, +and natural-language mismatch summarisation all live in :mod:`physix.verifier`. +Systems do not import anything from the verifier; the dependency runs in one +direction. +""" + +from __future__ import annotations + +from abc import ABC, ABCMeta, abstractmethod +from enum import Enum + +import numpy as np +from pydantic import BaseModel, ConfigDict, Field +from pydantic._internal._model_construction import ModelMetaclass +from scipy.integrate import odeint + + +class SystemTier(str, Enum): + """Curriculum tier. Tier 3 is held out of training to enable a + generalisation claim ("converges on systems it never trained on").""" + + TIER_1 = "tier1" + TIER_2 = "tier2" + TIER_3 = "tier3" + + +class TrajectoryData(BaseModel): + """Numerical trajectory plus its initial conditions. + + ``initial_conditions`` is included so the verifier can re-simulate the + agent's hypothesis from the *same* starting point, making residuals + directly comparable. + """ + + model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True) + + timestamps: np.ndarray + states: dict[str, np.ndarray] + initial_conditions: dict[str, float] + state_variables: tuple[str, ...] + + def to_observation_samples(self, decimals: int = 5) -> list[dict[str, float]]: + """Render as a JSON-friendly list of timestep dicts for the agent.""" + samples: list[dict[str, float]] = [] + for i, t in enumerate(self.timestamps): + sample: dict[str, float] = {"t": round(float(t), decimals)} + for var in self.state_variables: + sample[var] = round(float(self.states[var][i]), decimals) + samples.append(sample) + return samples + + def stats(self) -> dict[str, float]: + """Aggregate statistics for the agent's stats panel.""" + out: dict[str, float] = { + "duration": float(self.timestamps[-1] - self.timestamps[0]), + "n_timesteps": float(len(self.timestamps)), + "dt": float(self.timestamps[1] - self.timestamps[0]) if len(self.timestamps) > 1 else 0.0, + } + for var in self.state_variables: + arr = self.states[var] + out[f"{var}_min"] = float(np.min(arr)) + out[f"{var}_max"] = float(np.max(arr)) + out[f"{var}_std"] = float(np.std(arr)) + return out + + +class _AbstractModelMeta(ModelMetaclass, ABCMeta): + """Metaclass union so :class:`PhysicalSystem` is both a pydantic model and + a true ABC (i.e. instantiating the base or a subclass that fails to + implement an abstract method raises ``TypeError``).""" + + +class PhysicalSystem(BaseModel, ABC, metaclass=_AbstractModelMeta): + """Abstract physical system. + + Concrete subclasses must: + + - Override :attr:`system_id`, :attr:`tier`, :attr:`state_variables`, and + :attr:`hint_template`. + - Implement :meth:`sample_parameters` to draw random episode parameters. + - Implement :meth:`sample_initial_conditions` to draw random initial state. + - Implement :meth:`rhs` returning the time derivatives. + - Implement :meth:`ground_truth_equation` returning a canonical SymPy + string of the system's equation of motion. + + The base class implements :meth:`simulate` once for all subclasses by + delegating to ``scipy.integrate.odeint`` against :meth:`rhs`. + """ + + model_config = ConfigDict(arbitrary_types_allowed=True) + + system_id: str = "" + tier: SystemTier = SystemTier.TIER_1 + state_variables: tuple[str, ...] = () + hint_template: str = "" + + duration: float = 10.0 + n_timesteps: int = 100 + #: Gaussian noise applied to each observed sample, expressed as a fraction + #: of the per-variable *standard deviation* of the clean trajectory. Using + #: std (rather than range) avoids the pathology where a system with a + #: large total excursion (e.g. free fall) produces overwhelming noise. + noise_std: float = 0.02 + + parameters: dict[str, float] = Field(default_factory=dict) + initial_conditions: dict[str, float] = Field(default_factory=dict) + + # ------------------------------------------------------------------ API + + @abstractmethod + def sample_parameters(self, rng: np.random.Generator) -> dict[str, float]: + """Draw a fresh set of physical parameters for one episode.""" + + @abstractmethod + def sample_initial_conditions(self, rng: np.random.Generator) -> dict[str, float]: + """Draw fresh initial conditions for one episode.""" + + @abstractmethod + def rhs( + self, + t: float, + state: np.ndarray, + params: dict[str, float], + ) -> np.ndarray: + """Time derivatives at time ``t``. + + ``state`` is laid out in the order of :attr:`state_variables`. The + return value must be a 1-D array of the same length. + """ + + @abstractmethod + def ground_truth_equation(self) -> str: + """Canonical SymPy-grammar string of the equation of motion. + + Used for logging only. Never surfaced to the agent during training + or inference. + """ + + def hint(self, parameters: dict[str, float]) -> str: + """Render the natural-language hint for the agent. + + Default behaviour formats :attr:`hint_template` against + ``parameters``. Subclasses may override for more flexibility. + """ + try: + return self.hint_template.format(**parameters) + except (KeyError, IndexError): + return self.hint_template + + # -------------------------------------------------------------- behaviour + + def simulate(self, rng: np.random.Generator) -> TrajectoryData: + """Generate one noisy trajectory for an episode.""" + params = self.sample_parameters(rng) + ic = self.sample_initial_conditions(rng) + + timestamps = np.linspace(0.0, self.duration, self.n_timesteps) + initial_state = np.array([ic[var] for var in self.state_variables], dtype=float) + + # scipy.integrate.odeint expects f(state, t, *args); we wrap to put + # `t` second and pass params via closure. + def _rhs_wrapper(state: np.ndarray, t: float) -> np.ndarray: + return self.rhs(t, state, params) + + clean = odeint(_rhs_wrapper, initial_state, timestamps, full_output=False) + + states: dict[str, np.ndarray] = {} + for col, var in enumerate(self.state_variables): + clean_col = clean[:, col] + scale = max(float(np.std(clean_col)), 1e-6) + noise = rng.normal(0.0, self.noise_std * scale, size=clean_col.shape) + states[var] = clean_col + noise + + # Cache for downstream access (parameters surfaced to the env). + self.parameters = params + self.initial_conditions = ic + + return TrajectoryData( + timestamps=timestamps, + states=states, + initial_conditions=ic, + state_variables=self.state_variables, + ) diff --git a/physix-live/physix/systems/registry.py b/physix-live/physix/systems/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..5c95f891754be1e57ae8a0bcd433b2f0112b865e --- /dev/null +++ b/physix-live/physix/systems/registry.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from typing import Callable + +from physix.systems.base import PhysicalSystem, SystemTier +from physix.systems.tier1 import FreeFall, FreeFallWithDrag, SimplePendulum +from physix.systems.tier2 import DampedPendulum, DampedSpring, SpringMass +from physix.systems.tier3 import ChargedInBField, ProjectileWithDrag + + +SystemFactory = Callable[[], PhysicalSystem] + + +SYSTEM_REGISTRY: dict[str, SystemFactory] = { + "free_fall": FreeFall, + "free_fall_drag": FreeFallWithDrag, + "simple_pendulum": SimplePendulum, + "damped_pendulum": DampedPendulum, + "spring_mass": SpringMass, + "damped_spring": DampedSpring, + "projectile_drag": ProjectileWithDrag, + "charged_b_field": ChargedInBField, +} + +SUPPORTED_SYSTEMS: tuple[str, ...] = ( + "free_fall", + "damped_spring", + "simple_pendulum", +) + + +def get_system(system_id: str) -> PhysicalSystem: + if system_id not in SYSTEM_REGISTRY: + valid = ", ".join(sorted(SYSTEM_REGISTRY)) + raise KeyError(f"Unknown system_id={system_id!r}. Valid: {valid}") + return SYSTEM_REGISTRY[system_id]() + + +def list_systems() -> list[str]: + return list(SYSTEM_REGISTRY) + + +def list_systems_by_tier(tier: SystemTier) -> list[str]: + return [sid for sid, cls in SYSTEM_REGISTRY.items() if cls().tier == tier] + + +def list_supported_systems() -> list[str]: + return [sid for sid in SUPPORTED_SYSTEMS if sid in SYSTEM_REGISTRY] diff --git a/physix-live/physix/systems/tier1.py b/physix-live/physix/systems/tier1.py new file mode 100644 index 0000000000000000000000000000000000000000..1ed73b144326f2502607eaa98179f02cca39dbfc --- /dev/null +++ b/physix-live/physix/systems/tier1.py @@ -0,0 +1,143 @@ +"""Tier-1 physical systems: simple, single-variable, no damping.""" + +from __future__ import annotations + +import numpy as np + +from physix.systems.base import PhysicalSystem, SystemTier + + +class FreeFall(PhysicalSystem): + """Simple free fall under constant gravity. + + Equation of motion: ``d2y/dt2 = -g``. + State variables: ``y`` (vertical position), ``vy`` (vertical velocity). + """ + + system_id: str = "free_fall" + tier: SystemTier = SystemTier.TIER_1 + state_variables: tuple[str, ...] = ("y", "vy") + duration: float = 3.0 # short enough that the object does not pass y=0 + hint_template: str = ( + "Object dropped near Earth's surface in vacuum. " + "Mass {mass:.1f} kg, released from rest at altitude {y0:.1f} m." + ) + + def sample_parameters(self, rng: np.random.Generator) -> dict[str, float]: + return { + "g": 9.81, + "mass": float(rng.uniform(0.5, 5.0)), + } + + def sample_initial_conditions(self, rng: np.random.Generator) -> dict[str, float]: + return { + "y": float(rng.uniform(20.0, 60.0)), + "vy": 0.0, + } + + def rhs( + self, + t: float, + state: np.ndarray, + params: dict[str, float], + ) -> np.ndarray: + _y, vy = state + return np.array([vy, -params["g"]], dtype=float) + + def ground_truth_equation(self) -> str: + return "d2y/dt2 = -g" + + def hint(self, parameters: dict[str, float]) -> str: + ic = self.initial_conditions or {"y": 30.0} + return self.hint_template.format(mass=parameters["mass"], y0=ic["y"]) + + +class FreeFallWithDrag(PhysicalSystem): + """Free fall with quadratic air drag — the demo system. + + Equation of motion: ``d2y/dt2 = -g + k * vy**2`` (drag opposes motion; + when ``vy < 0`` the ``vy**2`` term provides a positive deceleration). + """ + + system_id: str = "free_fall_drag" + tier: SystemTier = SystemTier.TIER_1 + state_variables: tuple[str, ...] = ("y", "vy") + duration: float = 6.0 # long enough to clearly see terminal-velocity onset + hint_template: str = ( + "Object dropped from altitude {y0:.1f} m, mass {mass:.1f} kg, " + "in air. Air resistance may be non-negligible." + ) + + def sample_parameters(self, rng: np.random.Generator) -> dict[str, float]: + return { + "g": 9.81, + "mass": float(rng.uniform(1.0, 3.0)), + # Drag coefficient tuned so terminal velocity is reached within ~5s + # for the altitudes we sample. + "k": float(rng.uniform(0.02, 0.10)), + } + + def sample_initial_conditions(self, rng: np.random.Generator) -> dict[str, float]: + return { + "y": float(rng.uniform(40.0, 80.0)), + "vy": 0.0, + } + + def rhs( + self, + t: float, + state: np.ndarray, + params: dict[str, float], + ) -> np.ndarray: + _y, vy = state + # vy is negative on descent; vy**2 keeps the magnitude correct. + return np.array([vy, -params["g"] + params["k"] * vy * vy], dtype=float) + + def ground_truth_equation(self) -> str: + return "d2y/dt2 = -g + k * vy**2" + + def hint(self, parameters: dict[str, float]) -> str: + ic = self.initial_conditions or {"y": 50.0} + return self.hint_template.format(mass=parameters["mass"], y0=ic["y"]) + + +class SimplePendulum(PhysicalSystem): + """Idealised pendulum (small or large angle), no damping. + + Equation of motion: ``d2theta/dt2 = -(g / L) * sin(theta)``. + """ + + system_id: str = "simple_pendulum" + tier: SystemTier = SystemTier.TIER_1 + state_variables: tuple[str, ...] = ("theta", "dtheta") + hint_template: str = ( + "Simple pendulum of length {L:.2f} m swinging in vacuum. " + "No friction, no air resistance." + ) + + def sample_parameters(self, rng: np.random.Generator) -> dict[str, float]: + return { + "g": 9.81, + "L": float(rng.uniform(0.5, 2.0)), + } + + def sample_initial_conditions(self, rng: np.random.Generator) -> dict[str, float]: + return { + "theta": float(rng.uniform(0.3, 1.0)), # ~17-57 degrees + "dtheta": 0.0, + } + + def rhs( + self, + t: float, + state: np.ndarray, + params: dict[str, float], + ) -> np.ndarray: + theta, dtheta = state + return np.array( + [dtheta, -(params["g"] / params["L"]) * np.sin(theta)], + dtype=float, + ) + + def ground_truth_equation(self) -> str: + return "d2theta/dt2 = -(g / L) * sin(theta)" diff --git a/physix-live/physix/systems/tier2.py b/physix-live/physix/systems/tier2.py new file mode 100644 index 0000000000000000000000000000000000000000..687762add13e4c2f28e5d6b65f009c986cb3e251 --- /dev/null +++ b/physix-live/physix/systems/tier2.py @@ -0,0 +1,128 @@ +"""Tier-2 physical systems: damped or with a second active force term.""" + +from __future__ import annotations + +import numpy as np + +from physix.systems.base import PhysicalSystem, SystemTier + + +class DampedPendulum(PhysicalSystem): + """Pendulum with linear angular damping. + + Equation of motion: ``d2theta/dt2 = -(g/L)*sin(theta) - b*dtheta``. + """ + + system_id: str = "damped_pendulum" + tier: SystemTier = SystemTier.TIER_2 + state_variables: tuple[str, ...] = ("theta", "dtheta") + hint_template: str = ( + "Pendulum of length {L:.2f} m. Oscillation amplitude visibly decreases " + "over time, suggesting linear angular damping." + ) + + def sample_parameters(self, rng: np.random.Generator) -> dict[str, float]: + return { + "g": 9.81, + "L": float(rng.uniform(0.5, 2.0)), + "b": float(rng.uniform(0.05, 0.30)), + } + + def sample_initial_conditions(self, rng: np.random.Generator) -> dict[str, float]: + return { + "theta": float(rng.uniform(0.3, 1.0)), + "dtheta": 0.0, + } + + def rhs( + self, + t: float, + state: np.ndarray, + params: dict[str, float], + ) -> np.ndarray: + theta, dtheta = state + d2theta = -(params["g"] / params["L"]) * np.sin(theta) - params["b"] * dtheta + return np.array([dtheta, d2theta], dtype=float) + + def ground_truth_equation(self) -> str: + return "d2theta/dt2 = -(g/L)*sin(theta) - b*dtheta" + + +class SpringMass(PhysicalSystem): + """Undamped harmonic oscillator. + + Equation of motion: ``d2x/dt2 = -(k/m) * x``. + """ + + system_id: str = "spring_mass" + tier: SystemTier = SystemTier.TIER_2 + state_variables: tuple[str, ...] = ("x", "vx") + hint_template: str = ( + "Mass {m:.2f} kg attached to a spring of stiffness {k:.2f} N/m, " + "frictionless surface." + ) + + def sample_parameters(self, rng: np.random.Generator) -> dict[str, float]: + return { + "k": float(rng.uniform(2.0, 20.0)), + "m": float(rng.uniform(0.5, 2.0)), + } + + def sample_initial_conditions(self, rng: np.random.Generator) -> dict[str, float]: + return { + "x": float(rng.uniform(0.5, 2.0)), + "vx": 0.0, + } + + def rhs( + self, + t: float, + state: np.ndarray, + params: dict[str, float], + ) -> np.ndarray: + x, vx = state + return np.array([vx, -(params["k"] / params["m"]) * x], dtype=float) + + def ground_truth_equation(self) -> str: + return "d2x/dt2 = -(k/m) * x" + + +class DampedSpring(PhysicalSystem): + """Damped harmonic oscillator. + + Equation of motion: ``d2x/dt2 = -(k/m)*x - (c/m)*vx``. + """ + + system_id: str = "damped_spring" + tier: SystemTier = SystemTier.TIER_2 + state_variables: tuple[str, ...] = ("x", "vx") + hint_template: str = ( + "Mass {m:.2f} kg on a spring of stiffness {k:.2f} N/m with viscous " + "damping coefficient {c:.2f}. Oscillation amplitude decays over time." + ) + + def sample_parameters(self, rng: np.random.Generator) -> dict[str, float]: + return { + "k": float(rng.uniform(2.0, 20.0)), + "m": float(rng.uniform(0.5, 2.0)), + "c": float(rng.uniform(0.1, 1.0)), + } + + def sample_initial_conditions(self, rng: np.random.Generator) -> dict[str, float]: + return { + "x": float(rng.uniform(0.5, 2.0)), + "vx": 0.0, + } + + def rhs( + self, + t: float, + state: np.ndarray, + params: dict[str, float], + ) -> np.ndarray: + x, vx = state + d2x = -(params["k"] / params["m"]) * x - (params["c"] / params["m"]) * vx + return np.array([vx, d2x], dtype=float) + + def ground_truth_equation(self) -> str: + return "d2x/dt2 = -(k/m)*x - (c/m)*vx" diff --git a/physix-live/physix/systems/tier3.py b/physix-live/physix/systems/tier3.py new file mode 100644 index 0000000000000000000000000000000000000000..9e4b3a4689dee867265d10bf855a1df0d749a085 --- /dev/null +++ b/physix-live/physix/systems/tier3.py @@ -0,0 +1,132 @@ +"""Tier-3 physical systems: held out of training to support a generalisation +claim ("converges on systems it never trained on").""" + +from __future__ import annotations + +import numpy as np + +from physix.systems.base import PhysicalSystem, SystemTier + + +class ProjectileWithDrag(PhysicalSystem): + """2-D projectile with quadratic air drag. + + Equations of motion:: + + d2x/dt2 = -k * |v| * vx + d2y/dt2 = -g - k * |v| * vy + + where ``|v| = sqrt(vx**2 + vy**2)``. + """ + + system_id: str = "projectile_drag" + tier: SystemTier = SystemTier.TIER_3 + state_variables: tuple[str, ...] = ("x", "y", "vx", "vy") + duration: float = 5.0 # typical flight time for the parameter ranges below + hint_template: str = ( + "Projectile launched at angle {angle_deg:.0f} degrees with initial " + "speed {v0:.1f} m/s. Air drag is non-negligible." + ) + + def sample_parameters(self, rng: np.random.Generator) -> dict[str, float]: + return { + "g": 9.81, + "k": float(rng.uniform(0.005, 0.02)), + } + + def sample_initial_conditions(self, rng: np.random.Generator) -> dict[str, float]: + speed = float(rng.uniform(15.0, 30.0)) + angle = float(rng.uniform(np.deg2rad(30.0), np.deg2rad(70.0))) + return { + "x": 0.0, + "y": 0.0, + "vx": float(speed * np.cos(angle)), + "vy": float(speed * np.sin(angle)), + } + + def rhs( + self, + t: float, + state: np.ndarray, + params: dict[str, float], + ) -> np.ndarray: + _x, _y, vx, vy = state + speed = float(np.sqrt(vx * vx + vy * vy)) + return np.array( + [ + vx, + vy, + -params["k"] * speed * vx, + -params["g"] - params["k"] * speed * vy, + ], + dtype=float, + ) + + def ground_truth_equation(self) -> str: + # Two-equation system rendered in a single string so the parser can + # split on ';' or '\n'. Verifier handles both delimiters. + return ( + "d2x/dt2 = -k*sqrt(vx**2 + vy**2)*vx; " + "d2y/dt2 = -g - k*sqrt(vx**2 + vy**2)*vy" + ) + + def hint(self, parameters: dict[str, float]) -> str: + ic = self.initial_conditions + if not ic: + return self.hint_template + v0 = float(np.sqrt(ic["vx"] ** 2 + ic["vy"] ** 2)) + angle_deg = float(np.rad2deg(np.arctan2(ic["vy"], ic["vx"]))) + return self.hint_template.format(angle_deg=angle_deg, v0=v0) + + +class ChargedInBField(PhysicalSystem): + """Charged particle in a uniform magnetic field along z (circular motion). + + Equations of motion (assuming B = B_z * ẑ and v in xy-plane):: + + d2x/dt2 = (q*B/m) * vy + d2y/dt2 = -(q*B/m) * vx + """ + + system_id: str = "charged_b_field" + tier: SystemTier = SystemTier.TIER_3 + state_variables: tuple[str, ...] = ("x", "y", "vx", "vy") + hint_template: str = ( + "Charged particle in a uniform magnetic field. Charge-to-mass ratio " + "q/m = {qm:.2f}, field strength {B:.2f} T." + ) + + def sample_parameters(self, rng: np.random.Generator) -> dict[str, float]: + return { + "q": float(rng.choice([-1.0, 1.0])), + "m": float(rng.uniform(0.5, 2.0)), + "B": float(rng.uniform(0.5, 2.0)), + } + + def sample_initial_conditions(self, rng: np.random.Generator) -> dict[str, float]: + return { + "x": 0.0, + "y": 0.0, + "vx": float(rng.uniform(0.5, 2.0)), + "vy": float(rng.uniform(-2.0, 2.0)), + } + + def rhs( + self, + t: float, + state: np.ndarray, + params: dict[str, float], + ) -> np.ndarray: + _x, _y, vx, vy = state + omega = params["q"] * params["B"] / params["m"] + return np.array([vx, vy, omega * vy, -omega * vx], dtype=float) + + def ground_truth_equation(self) -> str: + return ( + "d2x/dt2 = (q*B/m)*vy; " + "d2y/dt2 = -(q*B/m)*vx" + ) + + def hint(self, parameters: dict[str, float]) -> str: + qm = parameters["q"] / parameters["m"] + return self.hint_template.format(qm=qm, B=parameters["B"]) diff --git a/physix-live/physix/training/__init__.py b/physix-live/physix/training/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c2dc5775bfd095194ead97a8af5a47beed3c6388 --- /dev/null +++ b/physix-live/physix/training/__init__.py @@ -0,0 +1,18 @@ +"""Training utilities for PhysiX-Live. + +The ``loop`` submodule pulls in heavy ML deps (torch, unsloth, trl) and is +imported lazily on demand. The lighter prompt + scorer surface is exposed +here so callers without CUDA can still build datasets and score completions. +""" + +from physix.training.prompt import ( + build_prompt, + parse_completion, + render_observation_for_prompt, +) + +__all__ = [ + "build_prompt", + "parse_completion", + "render_observation_for_prompt", +] diff --git a/physix-live/physix/training/__pycache__/__init__.cpython-311.pyc b/physix-live/physix/training/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78a9e711ba0b1e57baba2d3706a2cb6319e35809 Binary files /dev/null and b/physix-live/physix/training/__pycache__/__init__.cpython-311.pyc differ diff --git a/physix-live/physix/training/__pycache__/dataset.cpython-311.pyc b/physix-live/physix/training/__pycache__/dataset.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e408b1e182ccda001f9f10a3659b806aef753f0 Binary files /dev/null and b/physix-live/physix/training/__pycache__/dataset.cpython-311.pyc differ diff --git a/physix-live/physix/training/__pycache__/prompt.cpython-311.pyc b/physix-live/physix/training/__pycache__/prompt.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d92b7cfdc6d380d0eab761262b0271fb0f934552 Binary files /dev/null and b/physix-live/physix/training/__pycache__/prompt.cpython-311.pyc differ diff --git a/physix-live/physix/training/__pycache__/scorer.cpython-311.pyc b/physix-live/physix/training/__pycache__/scorer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0626f485ffde908b5ecdebee05ee2c4faa985c3 Binary files /dev/null and b/physix-live/physix/training/__pycache__/scorer.cpython-311.pyc differ diff --git a/physix-live/physix/training/__pycache__/sft.cpython-311.pyc b/physix-live/physix/training/__pycache__/sft.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc377b5dbd54b4ce8f7712aea39f48b57e906792 Binary files /dev/null and b/physix-live/physix/training/__pycache__/sft.cpython-311.pyc differ diff --git a/physix-live/physix/training/dataset.py b/physix-live/physix/training/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..0b27c272ca73c6b7967fcc58f0728df3b2632c16 --- /dev/null +++ b/physix-live/physix/training/dataset.py @@ -0,0 +1,153 @@ +"""Build the prompt dataset for GRPO training. + +Responsibility: enumerate the curriculum of physical systems, simulate each +one a configurable number of times, and emit a :class:`datasets.Dataset` +whose rows contain everything the training loop needs: + +- ``prompt``: the chat-format string passed to the model +- ``system_id``, ``state_variables``, ``parameters``, ``initial_conditions``, + ``timestamps``, ``observed``: the system context the scorer needs +- ``previous_total``: 0.0 at turn-0 (we train on first-turn prompts; the + iterative refinement skill emerges from the model's general ability to + read history at inference time) + +Multi-turn prompts can be added later by extending this builder; the +hackathon scope deliberately keeps it to turn-0 prompts. +""" + +from __future__ import annotations + +from collections.abc import Iterable + +import numpy as np +from datasets import Dataset +from pydantic import BaseModel, ConfigDict + +from physix.models import DEFAULT_MAX_TURNS, PhysiXObservation +from physix.systems import ( + SYSTEM_REGISTRY, + SUPPORTED_SYSTEMS, + SystemTier, + get_system, + list_systems_by_tier, +) +from physix.systems.base import PhysicalSystem, TrajectoryData +from physix.training.prompt import build_prompt + + +class DatasetSpec(BaseModel): + """Configuration for :func:`build_training_dataset`.""" + + model_config = ConfigDict(frozen=True) + + system_ids: tuple[str, ...] = SUPPORTED_SYSTEMS + instances_per_system: int = 32 + seed: int = 0 + + +class EvalDatasetSpec(BaseModel): + """Held-out evaluation set, drawn separately so seeds do not overlap.""" + + model_config = ConfigDict(frozen=True) + + train_tiers: tuple[SystemTier, ...] = (SystemTier.TIER_1, SystemTier.TIER_2) + held_out_tiers: tuple[SystemTier, ...] = (SystemTier.TIER_3,) + instances_per_system: int = 8 + seed: int = 1_000_000 # large to avoid overlap with training seeds + + +def build_training_dataset(spec: DatasetSpec | None = None) -> Dataset: + """Build the GRPO training dataset. + + Each row contains one (system, instance) prompt at turn 0. + """ + spec = spec or DatasetSpec() + _validate_system_ids(spec.system_ids) + rng = np.random.default_rng(spec.seed) + + rows: list[dict[str, object]] = [] + for system_id in spec.system_ids: + for _ in range(spec.instances_per_system): + rows.append(_build_row(system_id, rng)) + return Dataset.from_list(rows) + + +def _validate_system_ids(system_ids: tuple[str, ...]) -> None: + """Fail fast if the spec references an unregistered system.""" + if not system_ids: + raise ValueError( + "DatasetSpec.system_ids must be non-empty. " + f"Available: {sorted(SYSTEM_REGISTRY)!r}." + ) + unknown = [sid for sid in system_ids if sid not in SYSTEM_REGISTRY] + if unknown: + raise ValueError( + f"Unknown system_ids in DatasetSpec: {unknown!r}. " + f"Registered: {sorted(SYSTEM_REGISTRY)!r}." + ) + + +def build_eval_dataset(spec: EvalDatasetSpec | None = None) -> Dataset: + """Build a held-out evaluation dataset spanning held-out tiers too.""" + spec = spec or EvalDatasetSpec() + rng = np.random.default_rng(spec.seed) + + rows: list[dict[str, object]] = [] + for system_id in _list_systems(spec.train_tiers + spec.held_out_tiers): + for _ in range(spec.instances_per_system): + row = _build_row(system_id, rng) + row["is_held_out"] = system_id in _list_systems(spec.held_out_tiers) + rows.append(row) + return Dataset.from_list(rows) + + +def _list_systems(tiers: Iterable[SystemTier]) -> list[str]: + out: list[str] = [] + for tier in tiers: + out.extend(list_systems_by_tier(tier)) + return out + + +def _build_row(system_id: str, rng: np.random.Generator) -> dict[str, object]: + """Generate one (prompt + system context) row for a given system.""" + system = get_system(system_id) + trajectory = system.simulate(rng) + + obs = _build_observation(system, trajectory) + prompt = build_prompt(obs) + + return { + "prompt": prompt, # chat list of {"role", "content"} dicts + "system_id": system_id, + "state_variables": list(system.state_variables), + "parameters": dict(system.parameters), + "initial_conditions": dict(system.initial_conditions), + "timestamps": trajectory.timestamps.tolist(), + "observed": {var: trajectory.states[var].tolist() for var in system.state_variables}, + "previous_r_match": 0.0, + } + + +def _build_observation( + system: PhysicalSystem, + trajectory: TrajectoryData, +) -> PhysiXObservation: + """Construct a turn-0 :class:`PhysiXObservation` for a fresh system. + + We bypass :class:`PhysiXEnvironment` here because its lifecycle (history, + convergence flag, episode budget) is irrelevant for dataset construction. + """ + return PhysiXObservation( + done=False, + reward=None, + trajectory=trajectory.to_observation_samples(), + state_variables=list(system.state_variables), + hint=system.hint(system.parameters), + history=[], + mismatch_summary="", + turn=0, + turn_remaining=DEFAULT_MAX_TURNS, + system_id=system.system_id, + stats=trajectory.stats(), + reward_breakdown={}, + ) diff --git a/physix-live/physix/training/loop.py b/physix-live/physix/training/loop.py new file mode 100644 index 0000000000000000000000000000000000000000..793a9bd1f824580ddf4546553f7c21ec7005d508 --- /dev/null +++ b/physix-live/physix/training/loop.py @@ -0,0 +1,759 @@ +"""GRPO training loop using Unsloth + TRL + W&B. + +Requires the ``[train]`` optional dependency group. Importing this module on +a machine without the heavy ML deps installed will fail at module load, +which is the documented contract — local development tools (env server, +verifier, demo UI) live in lighter modules and remain usable. + +Run via:: + + python -m physix.training.loop \ + --model Qwen/Qwen2.5-1.5B-Instruct \ + --output-dir runs/physix-1.5b-rl \ + --num-steps 300 + +Environment variables: + +- ``WANDB_PROJECT`` (default ``physix-live``) +- ``HUGGINGFACE_HUB_TOKEN`` if pushing the adapter to the Hub +""" + +from __future__ import annotations + +import argparse +import logging +import os +from pathlib import Path +from typing import Literal, Optional + +import torch +from datasets import Dataset +from pydantic import BaseModel, ConfigDict +from transformers import AutoTokenizer, TrainerCallback, TrainerControl, TrainerState +from transformers import TrainingArguments as HFTrainingArguments + +from physix.systems import SUPPORTED_SYSTEMS +from physix.training.dataset import ( + DatasetSpec, + build_training_dataset, +) +from physix.training.reward_fns import make_reward_funcs +from physix.training.scorer import Scorer + +# IMPORTANT: Unsloth's GRPO patches must be applied *before* importing +# ``GRPOTrainer`` so its kernels are swapped in. Without this, the trainer +# falls back to the stock TRL path and Unsloth's optimisations are bypassed +# (and on recent versions the import will hard-fail). Keep this block +# directly above the ``trl`` import — order matters. +# +# Version note: this requires ``trl<=0.24.0``. Newer TRL versions ship +# ``trl.experimental.openenv`` which Unsloth's ``patch_trl_openenv`` +# hook tries to ``inspect.getsource()`` on; that fails with ``OSError: +# could not get source code`` and crashes ``PatchFastRL``. ``trl==0.24.0`` +# is the pinned upper bound declared in unsloth's pyproject.toml. +from unsloth import FastLanguageModel, PatchFastRL # noqa: E402 + +PatchFastRL("GRPO", FastLanguageModel) + +from trl import GRPOConfig, GRPOTrainer # noqa: E402 (must come after PatchFastRL) + + +_log = logging.getLogger(__name__) + + +Ablation = Literal["no_progress", "no_simplicity", "no_format"] +SaveMethod = Literal["lora", "merged_16bit", "merged_4bit"] + + +class TrainingConfig(BaseModel): + """All hyperparameters in one place; the CLI populates this.""" + + model_config = ConfigDict(frozen=True) + + model_name: str = "Qwen/Qwen2.5-1.5B-Instruct" + #: Optional path to a LoRA adapter produced by the SFT warm-start step. + #: When set, the base model is loaded and the adapter weights are applied + #: before GRPO begins. Without this the cold base model rarely produces + #: any reward signal in early steps. + sft_checkpoint: Optional[str] = None + #: Optional Hub repo id (or local path) of an existing LoRA adapter to + #: warm-start GRPO from — e.g. a previous GRPO run that was interrupted + #: and pushed checkpoints to ``hub_checkpoint_repo_id``. When set, the + #: base ``model_name`` is loaded and this adapter is applied as the + #: starting trainable LoRA (skipping the fresh ``get_peft_model`` call). + #: SFT is unnecessary in this case (the adapter is already downstream + #: of an SFT warm-start), so leave ``sft_checkpoint`` unset when using + #: this flag. + lora_adapter_repo: Optional[str] = None + output_dir: str = "runs/physix-1.5b-rl" + max_seq_length: int = 2048 + lora_r: int = 16 + lora_alpha: int = 32 + learning_rate: float = 5.0e-6 + temperature: float = 0.9 + max_completion_length: int = 256 + beta: float = 0.04 + num_generations: int = 4 + per_device_train_batch_size: int = 1 + gradient_accumulation_steps: int = 8 + num_steps: int = 300 + seed: int = 0 + instances_per_system: int = 32 + ablation: Optional[Ablation] = None + wandb_project: str = "physix-live" + wandb_run_name: Optional[str] = None + push_to_hub: bool = False + hub_repo_id: Optional[str] = None + #: HF repo to push LoRA checkpoints to every save_steps during GRPO. + #: Separate from hub_repo_id (which receives the final merged model). + #: Set this to enable mid-run checkpoint persistence and W&B artifact logging. + hub_checkpoint_repo_id: Optional[str] = None + #: Path to a Trainer checkpoint dir to resume GRPO from (e.g. from a + #: previous run killed mid-training). Set automatically by train.sh. + resume_from_checkpoint: Optional[str] = None + #: How to persist the final adapter. ``"lora"`` saves only the adapter + #: weights (small, requires the base model at load time). ``"merged_16bit"`` + #: merges the adapter into the base and saves a deployable bf16/fp16 + #: checkpoint (large, but loadable as a normal HF model — what you want + #: for Hub pushes and Ollama exports). + save_method: SaveMethod = "merged_16bit" + + +def train(config: TrainingConfig) -> None: + """Run a full GRPO training loop with the given configuration.""" + _configure_logging() + + import wandb + + run_name = config.wandb_run_name or f"physix-grpo-{config.num_steps}steps" + wandb.init( + project=config.wandb_project, + name=run_name, + config=config.model_dump(), + tags=["grpo", "physix", config.model_name.split("/")[-1]], + resume="allow", + ) + + # Pin a few high-signal pointers into the run summary right away so the + # W&B "Overview" tab shows them prominently (no scrolling, no hunting). + if config.hub_checkpoint_repo_id: + ckpt_url = f"https://huggingface.co/{config.hub_checkpoint_repo_id}" + wandb.run.summary["checkpoint/repo"] = config.hub_checkpoint_repo_id + wandb.run.summary["checkpoint/repo_url"] = ckpt_url + if config.hub_repo_id: + wandb.run.summary["model/final_repo"] = config.hub_repo_id + wandb.run.summary["model/final_url"] = ( + f"https://huggingface.co/{config.hub_repo_id}" + ) + if config.lora_adapter_repo: + wandb.run.summary["resume/from_adapter"] = config.lora_adapter_repo + wandb.run.summary["resume/from_url"] = ( + f"https://huggingface.co/{config.lora_adapter_repo}" + ) + # If a parent W&B run is named (set by the orchestrator script), + # surface it prominently so the lineage is one click away. + parent_run = os.environ.get("WANDB_RESUMED_FROM") + if parent_run: + wandb.run.summary["resume/parent_wandb_run"] = parent_run + wandb.run.summary["resume/parent_wandb_url"] = ( + f"https://wandb.ai/{wandb.run.entity}/{wandb.run.project}/runs/{parent_run}" + ) + print( + f"\n[wandb] WARM-STARTED run — adapter " + f"https://huggingface.co/{config.lora_adapter_repo}\n", + flush=True, + ) + + _log.info("Loading model %s with Unsloth (4-bit, LoRA-%d)", config.model_name, config.lora_r) + model, tokenizer = _load_model_and_tokenizer(config) + train_dataset = _build_and_format_dataset(config, tokenizer) + + reward_funcs = _select_reward_funcs(config.ablation) + + grpo_config = _build_grpo_config(config) + + callbacks = [] + if config.hub_checkpoint_repo_id: + callbacks.append(_WandbCheckpointCallback(config.hub_checkpoint_repo_id)) + _log.info( + "Checkpoint hub push enabled → %s (every %d steps)", + config.hub_checkpoint_repo_id, + grpo_config.save_steps, + ) + + trainer = GRPOTrainer( + model=model, + processing_class=tokenizer, + args=grpo_config, + train_dataset=train_dataset, + reward_funcs=reward_funcs, + callbacks=callbacks or None, + ) + + if config.resume_from_checkpoint: + _log.info("Resuming from checkpoint: %s", config.resume_from_checkpoint) + + _log.info("Starting GRPO training for %d steps", config.num_steps) + trainer.train(resume_from_checkpoint=config.resume_from_checkpoint) + + _log_reward_summary(trainer) + + _log.info("Saving adapter (%s) to %s", config.save_method, config.output_dir) + _save_artifacts(model, tokenizer, config) + wandb.finish() + + +def _log_reward_summary(trainer: "GRPOTrainer") -> None: + """Emit a final reward-signal summary so log readers don't misinterpret + GRPO's near-zero ``train/loss`` as a broken run. ``train/loss`` is just + the KL term; what matters is whether reward components moved. + + Pulls the last ``log_history`` entry that contains reward keys and prints + the mean of every ``rewards/*/mean`` it finds, plus an explicit + interpretation hint. If *no* reward keys are present we hard-fail — that + means the reward functions never produced a non-NaN value, which is a + real bug worth surfacing. + """ + history = getattr(trainer.state, "log_history", []) or [] + reward_entries = [ + entry for entry in history + if any(k.startswith("rewards/") or k == "reward" for k in entry) + ] + if not reward_entries: + _log.error( + "No reward metrics logged during training. This usually means " + "every rollout failed to parse. Check `train/reward` in W&B and " + "the most recent completion samples." + ) + raise RuntimeError( + "GRPO produced no reward metrics — training silently failed." + ) + + last = reward_entries[-1] + first = reward_entries[0] + _log.info("=" * 60) + _log.info("GRPO reward summary (first → last logged step):") + for key in sorted(last): + if key.startswith("rewards/") or key == "reward": + v0 = first.get(key) + v1 = last.get(key) + if isinstance(v0, (int, float)) and isinstance(v1, (int, float)): + _log.info(" %-40s %.4f → %.4f (Δ=%+.4f)", key, v0, v1, v1 - v0) + _log.info("-" * 60) + _log.info("NOTE: train/loss near zero is EXPECTED for GRPO — it is only") + _log.info("the KL-term contribution (beta=%.3f). The model learns via the", + trainer.args.beta) + _log.info("advantage-weighted policy gradient, which doesn't appear in") + _log.info("the displayed loss scalar. Trust `train/reward` and `rewards/*`.") + _log.info("=" * 60) + + +def _load_model_and_tokenizer( + config: TrainingConfig, +) -> tuple[FastLanguageModel, AutoTokenizer]: + """Load Qwen via Unsloth in 4-bit and attach a LoRA adapter. + + If ``config.sft_checkpoint`` is set, the SFT adapter weights are merged + on top of the base model before GRPO starts. This gives GRPO a warm base + policy that already knows the JSON format and equation grammar, so early + rollouts produce meaningful reward signal instead of all scoring zero. + """ + if config.lora_adapter_repo: + # Resume path: load the base model and attach the existing LoRA + # adapter via PEFT. We deliberately do NOT call + # ``FastLanguageModel.from_pretrained(model_name=adapter_repo)`` + # because the adapter's ``adapter_config.json`` may carry a stale + # ``base_model_name_or_path`` pointing at a path that only existed + # inside the previous training container (e.g. ``/tmp/physix-sft/merged``). + # PEFT's ``load_adapter`` ignores that field — it adapts onto whatever + # base we hand it. + _log.info( + "Resuming from existing LoRA adapter %s on top of %s", + config.lora_adapter_repo, + config.model_name, + ) + model, tokenizer = FastLanguageModel.from_pretrained( + model_name=config.model_name, + max_seq_length=config.max_seq_length, + load_in_4bit=True, + dtype=None, + ) + # Wrap the base in a fresh trainable LoRA, then overwrite its + # weights with the saved adapter. We use the adapter's own r/alpha + # by relying on PEFT's ``load_adapter`` resolving from the repo's + # adapter_config.json. The dummy ``get_peft_model`` call is just to + # turn the model into a ``PeftModel`` instance whose ``load_adapter`` + # method accepts a hub repo id. + model = FastLanguageModel.get_peft_model( + model, + r=config.lora_r, + lora_alpha=config.lora_alpha, + target_modules=[ + "q_proj", "k_proj", "v_proj", "o_proj", + "gate_proj", "up_proj", "down_proj", + ], + bias="none", + use_gradient_checkpointing="unsloth", + random_state=config.seed, + ) + # Overwrite the freshly-initialised LoRA weights with the saved ones. + # ``adapter_name='default'`` matches what ``get_peft_model`` creates. + model.load_adapter( + config.lora_adapter_repo, + adapter_name="default", + is_trainable=True, + ) + _log.info("Adapter loaded; LoRA is trainable and ready for GRPO.") + return model, tokenizer + + if config.sft_checkpoint: + _log.info( + "Loading SFT-warmed model from %s (GRPO will refine from here)", + config.sft_checkpoint, + ) + model, tokenizer = FastLanguageModel.from_pretrained( + model_name=config.sft_checkpoint, + max_seq_length=config.max_seq_length, + load_in_4bit=True, + dtype=None, + ) + else: + _log.warning( + "No --sft-checkpoint supplied. Starting GRPO from cold base model. " + "Early reward signal will be near-zero; consider running sft.py first." + ) + model, tokenizer = FastLanguageModel.from_pretrained( + model_name=config.model_name, + max_seq_length=config.max_seq_length, + load_in_4bit=True, + dtype=None, + ) + model = FastLanguageModel.get_peft_model( + model, + r=config.lora_r, + lora_alpha=config.lora_alpha, + target_modules=[ + "q_proj", + "k_proj", + "v_proj", + "o_proj", + "gate_proj", + "up_proj", + "down_proj", + ], + bias="none", + use_gradient_checkpointing="unsloth", + random_state=config.seed, + ) + return model, tokenizer + + +def _build_and_format_dataset( + config: TrainingConfig, + tokenizer: AutoTokenizer, +) -> Dataset: + spec = DatasetSpec( + system_ids=SUPPORTED_SYSTEMS, + instances_per_system=config.instances_per_system, + seed=config.seed, + ) + dataset = build_training_dataset(spec) + _log.info( + "Built training dataset: %d rows across %d systems (%s)", + len(dataset), + len(SUPPORTED_SYSTEMS), + ", ".join(SUPPORTED_SYSTEMS), + ) + + def _apply_chat_template(example: dict[str, object]) -> dict[str, object]: + formatted = tokenizer.apply_chat_template( + example["prompt"], + tokenize=False, + add_generation_prompt=True, + ) + return {"prompt": formatted} + + return dataset.map(_apply_chat_template) + + +def _select_reward_funcs(ablation: Optional[Ablation]) -> list[object]: + """Return the GRPO reward function set. + + Default set (5 functions, summed by GRPOTrainer into the advantage): + + - ``reward_match`` — raw R² (linear). + - ``reward_match_dense`` — sqrt(R²); dense low-value gradient. + - ``reward_correctness`` — binary cliff at R² ≥ 0.70. + - ``reward_simplicity`` — gated on R² ≥ 0.10 (anti-hack). + - ``reward_format`` — 1.0 only if parsed AND simulated. + + Why this composition: empirically (RCA from W&B run 5kuqns9x) the + previous ``{match, progress, simplicity, format}`` mix had a + progress-equals-match duplicate (single-turn ``previous_r_match=0``) + AND let the model farm format+simplicity by emitting trivial + parseable equations. The new set both removes the duplicate and + triple-weights correctness via three different correctness-shaped + signals (match, match_dense, correctness_bonus) so that physical + accuracy dominates the GRPO advantage. + + Ablations strip one signal at a time (used by the experiment matrix, + not by the main runs). + """ + scorer = Scorer() + funcs = make_reward_funcs(scorer) + full = [ + funcs["match"], + funcs["match_dense"], + funcs["correctness"], + funcs["simplicity"], + funcs["format"], + ] + if ablation is None: + return full + if ablation == "no_simplicity": + return [funcs["match"], funcs["match_dense"], funcs["correctness"], funcs["format"]] + if ablation == "no_format": + return [funcs["match"], funcs["match_dense"], funcs["correctness"], funcs["simplicity"]] + if ablation == "no_progress": + # Backward-compat alias: ``progress`` no longer exists, the new + # reward set already excludes it. Treat ``no_progress`` as the + # full default set so old job configs still work without surprise. + return full + raise ValueError( + f"Unknown ablation {ablation!r}. Choose from " + "no_progress | no_simplicity | no_format | None." + ) + + +class _WandbCheckpointCallback(TrainerCallback): + """Make checkpoints first-class in W&B. + + After every Trainer save, this callback: + + 1. Resolves the latest commit hash on the Hub repo (best-effort — the + trainer's own ``PushToHubCallback`` runs ``git push`` asynchronously + so we may briefly see an older commit; that is fine, it self-corrects + on the next save). + 2. Updates the W&B run summary with persistent, prominent keys + (visible in the "Overview" tab of the run): + - ``checkpoint/last_step`` + - ``checkpoint/last_commit`` + - ``checkpoint/repo_url`` + - ``checkpoint/last_url`` + 3. Logs a step-indexed scalar ``checkpoint/step`` so a chart appears + on the W&B run page (one tick per save). + 4. Maintains a running ``checkpoint_history`` ``wandb.Table`` so every + saved checkpoint is browsable as a sortable table directly on the + run page (Tables tab). + 5. Prints a banner to stdout (visible in ``hf jobs logs``) with the + direct URL — so the checkpoint is also impossible to miss in the + job logs. + + No model bytes are uploaded to W&B; the actual weights live on the HF + Hub checkpoint repo. We never crash training if any of this fails. + """ + + def __init__(self, hub_checkpoint_repo_id: str) -> None: + self._repo = hub_checkpoint_repo_id + self._repo_url = f"https://huggingface.co/{hub_checkpoint_repo_id}" + self._table = None # lazy: wandb may not be initialised at __init__ + + def on_train_begin( + self, + args: HFTrainingArguments, + state: TrainerState, + control: TrainerControl, + **kwargs, + ) -> None: + # Pin the repo URL into the run config + summary at the very start + # so the link is visible on the W&B "Overview" panel from step 0. + try: + import wandb + + if wandb.run is None: + return + wandb.run.summary["checkpoint/repo_url"] = self._repo_url + wandb.run.summary["checkpoint/repo"] = self._repo + wandb.config.update( + {"checkpoint_repo_url": self._repo_url, "checkpoint_repo": self._repo}, + allow_val_change=True, + ) + print( + f"\n[wandb] Checkpoint repo pinned in run summary: {self._repo_url}\n", + flush=True, + ) + except Exception as exc: # noqa: BLE001 + _log.warning("Could not pin checkpoint repo to W&B summary: %s", exc) + + def on_save( + self, + args: HFTrainingArguments, + state: TrainerState, + control: TrainerControl, + **kwargs, + ) -> None: + try: + import wandb + + if wandb.run is None: + return + step = state.global_step + commit_sha = self._latest_commit_sha() + short = (commit_sha or "pending")[:8] + tree_url = ( + f"{self._repo_url}/tree/{commit_sha}" + if commit_sha + else f"{self._repo_url}/tree/main" + ) + + # 1. Persistent summary keys (top-of-run, always visible). + wandb.run.summary["checkpoint/last_step"] = step + wandb.run.summary["checkpoint/last_commit"] = commit_sha or "pending" + wandb.run.summary["checkpoint/last_url"] = tree_url + + # 2. Step-indexed scalar so a small chart appears on the run page. + wandb.log({"checkpoint/step": step}, step=step) + + # 3. Running history table. + if self._table is None: + self._table = wandb.Table( + columns=["step", "commit", "url", "repo"] + ) + self._table.add_data(step, commit_sha or "pending", tree_url, self._repo) + # Re-log the entire table each time so the latest version shows. + wandb.log({"checkpoint_history": self._table}, step=step) + + # 4. Stdout banner — also visible in `hf jobs logs`. + print( + "\n" + "================ CHECKPOINT SAVED ================\n" + f" step : {step}\n" + f" commit: {short}\n" + f" url : {tree_url}\n" + f" repo : {self._repo_url}\n" + "==================================================\n", + flush=True, + ) + _log.info( + "W&B checkpoint metadata logged: step=%d commit=%s", + step, + short, + ) + except Exception as exc: # noqa: BLE001 + _log.warning( + "W&B checkpoint callback skipped at step %d: %s. " + "Training continues; the actual checkpoint is still pushed " + "to the HF Hub by the trainer's PushToHubCallback.", + state.global_step, + exc, + ) + + def _latest_commit_sha(self) -> Optional[str]: + """Best-effort fetch of the most recent commit on the checkpoint repo. + + Uses ``HfApi.list_repo_commits`` if available; returns ``None`` on + any failure. The async ``git push`` may not be done at the instant + ``on_save`` fires, so we may see the *previous* checkpoint's commit; + that's acceptable — it self-corrects on the next save. + """ + try: + from huggingface_hub import HfApi + + api = HfApi(token=os.environ.get("HUGGINGFACE_HUB_TOKEN")) + commits = api.list_repo_commits(repo_id=self._repo, repo_type="model") + if commits: + return commits[0].commit_id + except Exception as exc: # noqa: BLE001 + _log.debug("Could not fetch latest commit sha: %s", exc) + return None + + +def _build_grpo_config(config: TrainingConfig) -> GRPOConfig: + # NOTE on "train/loss → 0" — this is expected GRPO behaviour, not a bug. + # The scalar TRL logs as `train/loss` is *only* the KL-divergence term + # weighted by beta; the advantage-weighted policy-gradient term that + # actually drives learning contributes gradients but is not in the + # displayed loss. At step 0, policy == reference → KL = 0 → loss = 0. + # As the policy drifts, loss rises slightly (with beta=0.04 typically + # to ~0.001–0.05). The signal you care about is `train/rewards/*` and + # `train/reward`, not `train/loss`. See: + # https://github.com/huggingface/trl/issues/2703 + # https://github.com/huggingface/open-r1/issues/239 + effective_batch = ( + config.per_device_train_batch_size * config.gradient_accumulation_steps + ) + if effective_batch % config.num_generations != 0: + raise ValueError( + f"effective_batch_size ({effective_batch}) must be divisible by " + f"num_generations ({config.num_generations}). Adjust " + "per_device_train_batch_size, gradient_accumulation_steps, or " + "num_generations." + ) + hub_kwargs: dict = {} + if config.hub_checkpoint_repo_id: + hub_kwargs = dict( + push_to_hub=True, + hub_model_id=config.hub_checkpoint_repo_id, + hub_strategy="checkpoint", + hub_token=os.environ.get("HUGGINGFACE_HUB_TOKEN") or os.environ.get("HF_TOKEN"), + ) + + return GRPOConfig( + output_dir=config.output_dir, + learning_rate=config.learning_rate, + per_device_train_batch_size=config.per_device_train_batch_size, + gradient_accumulation_steps=config.gradient_accumulation_steps, + num_train_epochs=1, + max_steps=config.num_steps, + num_generations=config.num_generations, + max_completion_length=config.max_completion_length, + max_prompt_length=config.max_seq_length - config.max_completion_length, + temperature=config.temperature, + beta=config.beta, + logging_steps=1, + save_strategy="steps", + save_steps=max(50, config.num_steps // 6), + report_to=["wandb"], + run_name=config.wandb_run_name, + seed=config.seed, + bf16=torch.cuda.is_bf16_supported() if torch.cuda.is_available() else False, + fp16=not torch.cuda.is_bf16_supported() if torch.cuda.is_available() else False, + **hub_kwargs, + ) + + +def _save_artifacts( + model: FastLanguageModel, + tokenizer: AutoTokenizer, + config: TrainingConfig, +) -> None: + """Persist the trained adapter via Unsloth's save path. + + ``save_pretrained_merged`` dispatches on ``save_method``: + + - ``"lora"``: writes only the adapter weights (small; requires the base + model at load time). + - ``"merged_16bit"``: merges LoRA into base and writes a standard HF + checkpoint in bf16/fp16 (large; loadable without Unsloth, exportable to + GGUF for Ollama). + - ``"merged_4bit"``: same merge but quantised back to 4-bit. + + Hub pushes use the same ``save_method`` so the on-disk artifact and the + Hub artifact are byte-identical. + """ + out_path = Path(config.output_dir) + out_path.mkdir(parents=True, exist_ok=True) + + save_dir = out_path / config.save_method + model.save_pretrained_merged( + save_directory=str(save_dir), + tokenizer=tokenizer, + save_method=config.save_method, + ) + + if config.push_to_hub and config.hub_repo_id: + _log.info("Pushing %s artifact to Hugging Face Hub: %s", config.save_method, config.hub_repo_id) + model.push_to_hub_merged( + config.hub_repo_id, + tokenizer, + save_method=config.save_method, + token=os.environ.get("HUGGINGFACE_HUB_TOKEN"), + ) + + +def _configure_logging() -> None: + logging.basicConfig( + level=os.environ.get("PHYSIX_LOG_LEVEL", "INFO"), + format="[%(asctime)s] %(levelname)s %(name)s | %(message)s", + ) + + +def _parse_args() -> TrainingConfig: + parser = argparse.ArgumentParser(description="Train PhysiX-Live with GRPO.") + parser.add_argument("--model", default="Qwen/Qwen2.5-1.5B-Instruct") + parser.add_argument("--output-dir", default="runs/physix-1.5b-rl") + parser.add_argument("--num-steps", type=int, default=300) + parser.add_argument("--learning-rate", type=float, default=5.0e-6) + parser.add_argument("--num-generations", type=int, default=4) + parser.add_argument("--max-completion-length", type=int, default=256, + help="Max tokens per rollout completion. Shorter = faster generation.") + parser.add_argument("--lora-r", type=int, default=16) + parser.add_argument("--instances-per-system", type=int, default=32) + parser.add_argument( + "--ablation", + choices=("no_progress", "no_simplicity", "no_format"), + default=None, + ) + parser.add_argument( + "--save-method", + choices=("lora", "merged_16bit", "merged_4bit"), + default="merged_16bit", + help="How to persist the final adapter (merged_16bit is deployable).", + ) + parser.add_argument("--sft-checkpoint", default=None, + help="Path to a merged SFT model from sft.py to warm-start from.") + parser.add_argument( + "--lora-adapter-repo", + default=None, + help=( + "Hub repo id (or local path) of an existing LoRA adapter to warm-start " + "GRPO from — e.g. a previous run's checkpoint at " + "user/physix-1.5b-rl-ckpt. Mutually exclusive with --sft-checkpoint." + ), + ) + parser.add_argument("--wandb-project", default="physix-live") + parser.add_argument("--wandb-run-name", default=None) + parser.add_argument("--push-to-hub", action="store_true") + parser.add_argument("--hub-repo-id", default=None) + parser.add_argument( + "--hub-checkpoint-repo-id", + default=None, + help="HF repo to push LoRA checkpoints to every save_steps (e.g. user/physix-ckpt).", + ) + parser.add_argument( + "--resume-from-checkpoint", + default=None, + help="Path to a Trainer checkpoint directory to resume GRPO from.", + ) + parser.add_argument("--seed", type=int, default=0) + + args = parser.parse_args() + + if args.sft_checkpoint and args.lora_adapter_repo: + parser.error( + "--sft-checkpoint and --lora-adapter-repo are mutually exclusive. " + "Use --lora-adapter-repo to resume from a prior GRPO run, or " + "--sft-checkpoint for a fresh GRPO from a merged SFT model." + ) + + return TrainingConfig( + model_name=args.model, + sft_checkpoint=args.sft_checkpoint, + lora_adapter_repo=args.lora_adapter_repo, + output_dir=args.output_dir, + num_steps=args.num_steps, + learning_rate=args.learning_rate, + num_generations=args.num_generations, + max_completion_length=args.max_completion_length, + lora_r=args.lora_r, + instances_per_system=args.instances_per_system, + ablation=args.ablation, + save_method=args.save_method, + wandb_project=args.wandb_project, + wandb_run_name=args.wandb_run_name, + push_to_hub=args.push_to_hub, + hub_repo_id=args.hub_repo_id, + hub_checkpoint_repo_id=args.hub_checkpoint_repo_id, + resume_from_checkpoint=args.resume_from_checkpoint, + seed=args.seed, + ) + + +def main() -> None: + config = _parse_args() + os.environ.setdefault("WANDB_PROJECT", config.wandb_project) + train(config) + + +if __name__ == "__main__": + main() diff --git a/physix-live/physix/training/prompt.py b/physix-live/physix/training/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..01eeb94bc8f23aa33b2b144ba3fdd650524a62f1 --- /dev/null +++ b/physix-live/physix/training/prompt.py @@ -0,0 +1,369 @@ +"""Prompt rendering and completion parsing for PhysiX-Live. + +Responsibility: + +- :func:`render_observation_for_prompt`: serialise a :class:`PhysiXObservation` + into a compact, token-efficient string the agent can read. +- :func:`build_prompt`: combine the system message, grammar hint, and the + current observation into a single chat-formatted prompt. +- :func:`parse_completion`: parse a raw model completion (which may contain a + JSON object inside arbitrary text) into a :class:`PhysiXAction`. + +This module imports nothing from :mod:`torch`, :mod:`unsloth`, or :mod:`trl` +so it can be tested on any machine. +""" + +from __future__ import annotations + +import json +import re +from typing import Any + +from physix.models import ( + DEFAULT_MAX_TURNS, + PhysiXAction, + PhysiXObservation, +) +from physix.verifier.parser import GRAMMAR_HINT + + +SYSTEM_MESSAGE: str = ( + "You are an expert physicist. Your task is to discover the equation of " + "motion that produced an observed trajectory. Each turn you propose a " + "candidate equation; the environment simulates it and tells you how well " + "the prediction matches observation. Refine your guess across turns based " + "on the residual feedback. Keep equations as simple as possible.\n\n" + + GRAMMAR_HINT + + "\n\n" + "Output a single JSON object with exactly these keys: " + '"equation" (string, required), "params" (object of name->number, ' + 'optional), "rationale" (short string, optional). Do not rename the ' + 'keys: always emit "equation", never "eqn"/"ode"/"formula"/"expr". ' + 'Example: {"equation": "d2y/dt2 = -9.81", "params": {}, ' + '"rationale": "free fall"}' +) + + +# Maximum number of trajectory samples shipped to the agent. We downsample +# from 100 to 12 to keep prompt size bounded; statistics carry the rest. +_TRAJECTORY_DOWNSAMPLE_COUNT: int = 12 + +# Maximum number of prior history entries surfaced. With 8 turns max budget, +# 7 prior turns is the upper bound; we cap at 5 to stay token-efficient. +_HISTORY_CAP: int = 5 + + +def render_observation_for_prompt(obs: PhysiXObservation) -> str: + """Render an observation as a compact string the agent can read. + + Format:: + + SYSTEM_ID: free_fall_drag + STATE_VARIABLES: y, vy + HINT: + STATS: y_min=-2.13 y_max=78.93 ... duration=6.00 + + TRAJECTORY (12 samples downsampled from 100): + t=0.000 y=78.93 vy=0.00 + t=0.500 y=77.71 vy=-4.84 + ... + + HISTORY (turns so far): + turn=1 reward=0.42 [match=0.42 progress=0.00 simplicity=0.95 format=1.00] equation=`d2y/dt2 = -9.81` + mismatch: predicted y diverges past t=2.0s ... + turn=2 ... + + TURN: 3 / 8 (5 turns remaining) + + HISTORY uses the literal string ``equation=`` (not a shorthand like + ``eqn=``). Mid-strength chat models will mimic the field name they + see in HISTORY when emitting the next turn's JSON, so the in-prompt + name *must* match the JSON key the parser reads. Drift here silently + produces ``{"eqn": ...}`` outputs that the parser ignores, scoring + every post-first turn ``r_format=0`` even when the equation is + perfect. + """ + sections = [ + _render_metadata_block(obs), + _render_trajectory_block(obs), + ] + if obs.history: + sections.append(_render_history_block(obs)) + sections.append(_render_turn_footer(obs)) + return "\n\n".join(sections) + + +def build_prompt(obs: PhysiXObservation) -> list[dict[str, str]]: + """Build a chat-format prompt list (system + user) for the model. + + The return value is the standard ``[{"role": "system", "content": ...}, + {"role": "user", "content": ...}]`` shape expected by Hugging Face + chat-template tokenisers. + """ + return [ + {"role": "system", "content": SYSTEM_MESSAGE}, + {"role": "user", "content": render_observation_for_prompt(obs)}, + ] + + +#: Field names we accept for the equation payload, in priority order. The +#: canonical key is ``equation`` and the system prompt asks for it +#: explicitly, but mid-strength chat models routinely substitute one of +#: these synonyms — especially after the first turn, where the model has +#: latched onto a different naming convention from its own pretraining +#: corpus. Treating these as missing produced silent ``r_format=0`` runs +#: even when the underlying equation was perfect; matching them +#: explicitly closes that hole without weakening the verifier (the +#: equation grammar itself remains strict). +_EQUATION_KEYS: tuple[str, ...] = ( + "equation", + "eqn", + "ode", + "formula", + "expression", + "expr", +) + +#: Same idea for the optional rationale payload. We never gate on this so +#: the cost of being permissive is zero. +_RATIONALE_KEYS: tuple[str, ...] = ( + "rationale", + "reasoning", + "explanation", + "thought", + "thoughts", +) + +#: And for the params dict. Some models emit ``parameters`` instead. +_PARAMS_KEYS: tuple[str, ...] = ("params", "parameters", "constants") + + +def parse_completion(completion: str) -> PhysiXAction: + """Parse a raw model completion into a :class:`PhysiXAction`. + + Scope is intentionally narrow: extract the first JSON object from the + completion (which may be wrapped in markdown fences or surrounded by + scratchpad text) and copy its fields verbatim into the action. + + The ``equation`` string is **not** rewritten or normalised here. The + verifier in :mod:`physix.verifier.parser` defines the grammar, and any + deviation must surface as a parse error so the env can score + ``r_format=0`` and feed the failure back to the agent on the next turn. + Rewriting equations upstream would silently change the agent's output + and obscure that signal. + + Field-name aliases (``eqn``/``ode``/``formula``/...) are accepted in + addition to ``equation``: refusing them produced a particularly + confusing failure mode where every turn after the first scored + ``r_format=0`` because the model latched onto the shorthand form + used in the HISTORY block. We've fixed the prompt too, but accepting + the synonyms is cheap defense-in-depth against future drift and + against models with their own naming preferences. + + If no JSON object can be extracted (e.g. the model emitted free-form + prose, or invalid JSON that even the JSON-aware decoder rejected), + the action's ``equation`` is left **empty** so the verifier reports + a clean ``Empty equation payload`` parse error and the env scores + ``r_format=0``. The raw model text is preserved in ``rationale`` so + the UI / training logs still show what was emitted, but it is + *never* fed to the equation parser as if it were an equation — + that produced misleading errors like ``Equation has no '=' sign: + '{'`` which made the verifier look broken when the real fault was + upstream. + """ + payload = _extract_json_payload(completion) + if payload is None: + return PhysiXAction(equation="", rationale=completion.strip()[:500]) + + normalized = _lowercase_keys(payload) + equation = _first_string_value(normalized, _EQUATION_KEYS) + rationale = _first_string_value(normalized, _RATIONALE_KEYS) + params_raw = _first_value(normalized, _PARAMS_KEYS) or {} + params = _coerce_params(params_raw) + + return PhysiXAction( + equation=equation, + params=params, + rationale=rationale, + ) + + +def _lowercase_keys(payload: dict[str, Any]) -> dict[str, Any]: + """Return ``payload`` with top-level keys lowercased. + + Some models emit ``"Equation"`` / ``"EQN"``; lowercasing once means + the lookup tables above stay declarative. + """ + return {str(k).lower(): v for k, v in payload.items()} + + +def _first_value(payload: dict[str, Any], keys: tuple[str, ...]) -> Any: + for key in keys: + if key in payload: + return payload[key] + return None + + +def _first_string_value(payload: dict[str, Any], keys: tuple[str, ...]) -> str: + value = _first_value(payload, keys) + if value is None: + return "" + return str(value).strip() + + +def _render_metadata_block(obs: PhysiXObservation) -> str: + state_vars = ", ".join(obs.state_variables) or "(none)" + stats_text = " ".join(f"{k}={v:.3g}" for k, v in obs.stats.items()) + return ( + f"SYSTEM_ID: {obs.system_id or 'unknown'}\n" + f"STATE_VARIABLES: {state_vars}\n" + f"HINT: {obs.hint}\n" + f"STATS: {stats_text}" + ) + + +def _render_trajectory_block(obs: PhysiXObservation) -> str: + samples = _downsample(obs.trajectory, _TRAJECTORY_DOWNSAMPLE_COUNT) + lines = [f"TRAJECTORY ({len(samples)} samples downsampled from {len(obs.trajectory)}):"] + for sample in samples: + parts: list[str] = [f"t={sample['t']:.3f}"] + for var in obs.state_variables: + if var in sample: + parts.append(f"{var}={sample[var]:.3f}") + lines.append(" " + " ".join(parts)) + return "\n".join(lines) + + +#: Order in which reward components are surfaced to the model. Match +#: matters most (it's the headline accuracy signal); format is last +#: because once it stabilises the others dominate the gradient. Stable +#: order also matters for the model's in-context retrieval: a fixed +#: column position is a reliable cue across turns. +_REWARD_COMPONENT_ORDER: tuple[str, ...] = ( + "match", + "progress", + "simplicity", + "format", +) + + +def _render_history_block(obs: PhysiXObservation) -> str: + """Render the most recent ``_HISTORY_CAP`` turns. + + Field name is ``equation=`` rather than ``eqn=`` deliberately: + chat-tuned models tend to mimic the most-recent token spelling when + emitting their own JSON, so we must use the same key here that the + parser expects in the model's reply. + + Each turn's full *dense* reward breakdown is surfaced in addition to + the scalar ``reward=`` total. The dense components are the same + values the GRPO trainer optimises (``match``/``progress``/ + ``simplicity``/``format``), so showing them in-context lets the + model attribute its own gains and losses turn-over-turn instead of + having to infer them from the residual prose alone — e.g. it can + see ``format=0.0`` after a parse error and prioritise grammar fixes, + or ``match=0.62, progress=0.0`` after a stuck plateau and try a + structurally different equation rather than tweaking the same + coefficients. + """ + recent = obs.history[-_HISTORY_CAP:] + lines = ["HISTORY:"] + for entry in recent: + eqn = entry.get("equation", "") + reward = float(entry.get("reward_total", 0.0)) + components_text = _format_reward_components(entry.get("reward_components")) + lines.append( + f" turn={entry.get('turn')} reward={reward:.3f} " + f"[{components_text}] equation=`{eqn}`" + ) + mismatch = entry.get("mismatch_summary", "") + if mismatch: + lines.append(f" mismatch: {mismatch}") + return "\n".join(lines) + + +def _format_reward_components(components: Any) -> str: + """Render ``{match, progress, simplicity, format}`` as a compact line. + + Always emits all four fields in :data:`_REWARD_COMPONENT_ORDER`, + defaulting to ``0.00`` when absent so the model never has to guess + why a column is missing. Three-decimal formatting matches the + server's history serialisation precision. + """ + if not isinstance(components, dict): + return " ".join(f"{name}=0.00" for name in _REWARD_COMPONENT_ORDER) + parts: list[str] = [] + for name in _REWARD_COMPONENT_ORDER: + try: + value = float(components.get(name, 0.0)) + except (TypeError, ValueError): + value = 0.0 + parts.append(f"{name}={value:.2f}") + return " ".join(parts) + + +def _render_turn_footer(obs: PhysiXObservation) -> str: + total = obs.turn + obs.turn_remaining or DEFAULT_MAX_TURNS + return ( + f"TURN: {obs.turn + 1} / {total} ({obs.turn_remaining} remaining)\n" + "Emit the next hypothesis as JSON." + ) + + +def _downsample(samples: list[dict[str, float]], target: int) -> list[dict[str, float]]: + if len(samples) <= target: + return samples + step = max(1, len(samples) // target) + indices = list(range(0, len(samples), step))[:target] + if indices[-1] != len(samples) - 1: + indices[-1] = len(samples) - 1 + return [samples[i] for i in indices] + + +_JSON_DECODER = json.JSONDecoder() + + +def _extract_json_payload(text: str) -> dict[str, Any] | None: + """Find the first ``{...}`` block in ``text`` that parses as a JSON object. + + Uses :meth:`json.JSONDecoder.raw_decode` so that braces appearing inside + JSON *string* values (e.g. LaTeX like ``"\\frac{d vy}{dt}"``) do not + confuse the scanner — a regex-based brace matcher would mis-balance + here and return the whole completion as a malformed equation. + """ + candidate = _strip_code_fences(text) + + for i, ch in enumerate(candidate): + if ch != "{": + continue + try: + payload, _ = _JSON_DECODER.raw_decode(candidate[i:]) + except json.JSONDecodeError: + continue + if isinstance(payload, dict): + return payload + return None + + +def _strip_code_fences(text: str) -> str: + """Remove Markdown code-fence wrappers (```json``` / ```python``` / ```). + + This is *not* equation rewriting — it strips the outer fence syntax + only, so the JSON-aware extractor below can find the object payload. + """ + text = re.sub(r"```(?:json|python)?\s*", "", text) + text = text.replace("```", "") + return text + + +def _coerce_params(params_raw: Any) -> dict[str, float]: + """Best-effort coercion of a raw params payload into ``dict[str, float]``.""" + if not isinstance(params_raw, dict): + return {} + out: dict[str, float] = {} + for key, value in params_raw.items(): + try: + out[str(key)] = float(value) + except (TypeError, ValueError): + continue + return out diff --git a/physix-live/physix/training/reward_fns.py b/physix-live/physix/training/reward_fns.py new file mode 100644 index 0000000000000000000000000000000000000000..e492fa9332165d0c07451231489ad3b904d2abe0 --- /dev/null +++ b/physix-live/physix/training/reward_fns.py @@ -0,0 +1,167 @@ +"""TRL-compatible reward functions for GRPO training. + +Responsibility: expose a stateless reward function for each independent +reward signal. Internally each component delegates to a shared +:class:`Scorer` so a single completion is parsed and simulated exactly +once per training step regardless of how many reward functions query it. + +The TRL signature for a reward function is:: + + def reward_func(*, prompts, completions, **kwargs) -> list[float]: ... + +where ``prompts`` and ``completions`` are batched lists. Extra columns from +the training dataset arrive as keyword arguments — we expect the columns +listed in :class:`SystemContext` to be present. + +Reward set design (anti-hack, RCA from W&B run 5kuqns9x): + +- ``reward_match`` — raw R² on the trajectory (linear). +- ``reward_match_dense`` — sqrt(R²); denser gradient at low values. +- ``reward_correctness`` — binary cliff at R² ≥ 0.70; pushes past plateau. +- ``reward_simplicity`` — gated on R² ≥ 0.10 (no free reward for trivial + equations). +- ``reward_format`` — 1.0 only if the equation parsed *and* + simulated. No partial credit for parseable + but uncomputable garbage. + +The legacy ``reward_progress`` is intentionally absent. In single-turn +GRPO every dataset row carries ``previous_r_match=0``, which made +``progress = max(0, match - 0) = match`` for every rollout — a perfect +duplicate of ``reward_match`` that diluted advantage estimation. +""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from typing import Any + +from physix.training.scorer import Scorer, SystemContext +from physix.verifier.reward import correctness_bonus, match_dense + + +RewardFunction = Callable[..., list[float]] + + +#: Components that read directly from the :class:`RewardBreakdown` produced +#: by :class:`Scorer.score`. ``progress`` is omitted (see module docstring). +_BREAKDOWN_COMPONENTS: tuple[str, ...] = ("match", "simplicity", "format") + + +def make_reward_funcs( + scorer: Scorer | None = None, +) -> dict[str, RewardFunction]: + """Build a fresh dict of reward functions wired to a shared scorer. + + Each function is named ``reward_`` so TRL's GRPO trainer + logs them individually to W&B under + ``train/rewards/reward_/mean``. + + The scorer is shared across all functions; calling ``scorer.reset()`` + between steps avoids unbounded cache growth and ensures each + completion is parsed + simulated exactly once per step regardless of + how many reward functions query it. + + Returns a dict whose keys are: + + - ``match`` / ``simplicity`` / ``format`` — direct reads from the + :class:`RewardBreakdown`. ``simplicity`` is internally gated on + match ≥ 0.10 and ``format`` on simulation success. + - ``match_dense`` — ``sqrt(match)`` for denser low-value gradient. + - ``correctness`` — binary 1.0 above an R² threshold (``0.70``). + + All functions share the scorer cache, so they cost one parse + + simulate per completion combined, not five. + """ + shared = scorer if scorer is not None else Scorer() + + def _make_breakdown_reader(component: str) -> RewardFunction: + def _reward_fn( + prompts: Sequence[Any], + completions: Sequence[str], + **kwargs: Any, + ) -> list[float]: + del prompts # kept for TRL API conformance; unused here. + shared.reset() + contexts = _hydrate_contexts(len(completions), kwargs) + out: list[float] = [] + for i, completion in enumerate(completions): + breakdown = shared.score( + completion=completion, + context=contexts[i], + cache_key=i, + ) + out.append(getattr(breakdown, component)) + return out + + _reward_fn.__name__ = f"reward_{component}" + return _reward_fn + + def _reward_match_dense( + prompts: Sequence[Any], + completions: Sequence[str], + **kwargs: Any, + ) -> list[float]: + del prompts + shared.reset() + contexts = _hydrate_contexts(len(completions), kwargs) + out: list[float] = [] + for i, completion in enumerate(completions): + b = shared.score(completion=completion, context=contexts[i], cache_key=i) + out.append(match_dense(b.match)) + return out + + _reward_match_dense.__name__ = "reward_match_dense" + + def _reward_correctness( + prompts: Sequence[Any], + completions: Sequence[str], + **kwargs: Any, + ) -> list[float]: + del prompts + shared.reset() + contexts = _hydrate_contexts(len(completions), kwargs) + out: list[float] = [] + for i, completion in enumerate(completions): + b = shared.score(completion=completion, context=contexts[i], cache_key=i) + out.append(correctness_bonus(b.match)) + return out + + _reward_correctness.__name__ = "reward_correctness" + + funcs: dict[str, RewardFunction] = { + name: _make_breakdown_reader(name) for name in _BREAKDOWN_COMPONENTS + } + funcs["match_dense"] = _reward_match_dense + funcs["correctness"] = _reward_correctness + return funcs + + +def _hydrate_contexts(batch_size: int, kwargs: dict[str, Any]) -> list[SystemContext]: + """Project per-row kwargs into :class:`SystemContext` records. + + TRL passes dataset columns as kwargs where each value is a list of + length ``batch_size``. We zip them together into per-row dicts and hand + each off to :func:`SystemContext.from_row`. + """ + expected_keys = ( + "system_id", + "state_variables", + "parameters", + "initial_conditions", + "timestamps", + "observed", + "previous_r_match", + ) + + rows: list[dict[str, Any]] = [] + for i in range(batch_size): + row: dict[str, Any] = {} + for key in expected_keys: + value = kwargs.get(key) + if isinstance(value, list) and len(value) > i: + row[key] = value[i] + else: + row[key] = value + rows.append(row) + + return [SystemContext.from_row(row) for row in rows] diff --git a/physix-live/physix/training/scorer.py b/physix-live/physix/training/scorer.py new file mode 100644 index 0000000000000000000000000000000000000000..c506db40adbc0532af4fbbfded02004d7daf0df6 --- /dev/null +++ b/physix-live/physix/training/scorer.py @@ -0,0 +1,189 @@ +"""Single-completion scorer used by both training and evaluation. + +Responsibility: given the agent's raw completion text plus the system context +(state variables, parameters, IC, observed trajectory), compute the same +4-component :class:`RewardBreakdown` the env produces during a normal +``step()`` call. This is the bridge between TRL's "reward function over a +batch of completions" interface and our env's verifier pipeline. + +Caching: a :class:`Scorer` instance memoises by ``(dataset_index, completion)`` +so per-component reward functions can each ask the scorer for the *same* +completion without re-running parse + simulate four times. +""" + +from __future__ import annotations + +import numpy as np +from pydantic import BaseModel, ConfigDict, Field + +from physix.models import RewardBreakdown +from physix.training.prompt import parse_completion +from physix.verifier import ( + ParseError, + SimulationError, + compute_match, + compute_reward, + parse_equation, + simulate_hypothesis, +) + + +def _drop_none(mapping: object) -> dict[str, float]: + """Return ``{k: float(v)}`` for keys whose value is not ``None``. + + HuggingFace ``Dataset`` columns are schema-unified across rows, so a + row that lacks a key gets ``None`` for it. We drop those at ingest + so per-row dicts only contain the keys that actually apply to the + row's system. + """ + if not isinstance(mapping, dict): + return {} + return {str(k): float(v) for k, v in mapping.items() if v is not None} + + +class SystemContext(BaseModel): + """Per-prompt context the scorer needs to evaluate completions. + + These fields correspond 1:1 with dataset columns at training time. + """ + + model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True) + + system_id: str + state_variables: tuple[str, ...] + parameters: dict[str, float] = Field(default_factory=dict) + initial_conditions: dict[str, float] = Field(default_factory=dict) + timestamps: np.ndarray + observed: dict[str, np.ndarray] = Field(default_factory=dict) + previous_r_match: float = 0.0 + + @classmethod + def from_row(cls, row: dict[str, object]) -> "SystemContext": + """Hydrate from a HuggingFace dataset row. + + Two non-obvious transforms happen here: + + 1. **Lists -> arrays.** The dataset stores trajectories as plain + Python lists for JSON serialisability; we lift them back into + ``np.ndarray`` so the verifier's NumPy code path works. + 2. **Strip ``None`` fillers.** ``Dataset.from_list`` schema-unifies + rows across all systems: a ``free_fall`` row ends up with + ``parameters={'g': 9.81, 'mass': 3.4, 'k': None, 'L': None, ...}`` + because *other* systems define those keys. Left as-is, ``None`` + values would (a) inflate the verifier's allowed-symbol set, so + the model could "validly" reference parameters that don't + exist for this system, and (b) crash the simulator on + substitution. We drop them at ingest, restoring per-system + parameter sets. + """ + state_variables = tuple(row.get("state_variables", ())) + observed: dict[str, np.ndarray] = {} + observed_raw = row.get("observed", {}) + if isinstance(observed_raw, dict): + for key, values in observed_raw.items(): + if key not in state_variables: + continue + observed[str(key)] = np.asarray(values, dtype=float) + + return cls( + system_id=str(row.get("system_id", "")), + state_variables=state_variables, + parameters=_drop_none(row.get("parameters", {})), + initial_conditions=_drop_none(row.get("initial_conditions", {})), + timestamps=np.asarray(row.get("timestamps", []), dtype=float), + observed=observed, + previous_r_match=float(row.get("previous_r_match", row.get("previous_total", 0.0))), + ) + + +class Scorer: + """Stateless completion scorer with optional per-batch memoisation.""" + + def __init__(self) -> None: + self._cache: dict[int, RewardBreakdown] = {} + + def reset(self) -> None: + """Clear the memoisation cache (call once per training step).""" + self._cache.clear() + + def score( + self, + completion: str, + context: SystemContext, + *, + cache_key: int | None = None, + ) -> RewardBreakdown: + """Score one completion. Optionally memoise by ``cache_key``.""" + if cache_key is not None and cache_key in self._cache: + return self._cache[cache_key] + + breakdown = self._score_uncached(completion, context) + if cache_key is not None: + self._cache[cache_key] = breakdown + return breakdown + + # --------------------------------------------------------------- internals + + def _score_uncached( + self, + completion: str, + context: SystemContext, + ) -> RewardBreakdown: + action = parse_completion(completion) + parameter_names = frozenset(action.params or {}) | frozenset(context.parameters) + + try: + parsed = parse_equation( + action.equation, + state_variables=context.state_variables, + parameter_names=parameter_names, + ) + except ParseError: + return compute_reward( + parse_succeeded=False, + r_match=0.0, + operator_count=0, + previous_r_match=context.previous_r_match, + ) + + # The agent's params take precedence over the system's; agent is + # allowed to use system parameter names like ``g`` if it provides + # values, but if it omits them we fall back to ground-truth values + # (which is fine — the agent's structural correctness is what we + # primarily score). + merged_parameters = {**context.parameters, **(action.params or {})} + + try: + predicted = simulate_hypothesis( + parsed, + state_variables=context.state_variables, + parameters=merged_parameters, + initial_conditions=context.initial_conditions, + timestamps=context.timestamps, + ) + except SimulationError: + # Equation parsed but the simulator could not produce a usable + # trajectory (NaN/inf, stiff blow-up, dimension mismatch, …). + # We mark ``simulation_succeeded=False`` so ``compute_reward`` + # zeros out *every* component including ``format`` — otherwise + # the model gets paid for "looks valid but doesn't work". + return compute_reward( + parse_succeeded=True, + simulation_succeeded=False, + r_match=0.0, + operator_count=parsed.operator_count, + previous_r_match=context.previous_r_match, + ) + + r_match = compute_match( + observed=context.observed, + predicted=predicted, + state_variables=context.state_variables, + ) + return compute_reward( + parse_succeeded=True, + simulation_succeeded=True, + r_match=r_match, + operator_count=parsed.operator_count, + previous_r_match=context.previous_r_match, + ) diff --git a/physix-live/physix/training/sft.py b/physix-live/physix/training/sft.py new file mode 100644 index 0000000000000000000000000000000000000000..97323372835f3cc64d49ad6edc2517f6c57ecb87 --- /dev/null +++ b/physix-live/physix/training/sft.py @@ -0,0 +1,293 @@ +"""SFT warm-start before GRPO training. + +Trains Qwen2.5-1.5B-Instruct for 2 epochs on supervised (prompt, completion) +pairs where the completion is the ground-truth equation in the action JSON +format the env expects. This is the essential bootstrap step: without it a +cold 1.5B model outputs LaTeX / incoherent text on ~80% of turns, yielding +near-zero GRPO advantages and a flat loss curve that wastes GPU credits. + +After SFT the model: +- Emits valid JSON with ``equation``, ``params``, ``rationale`` on >90% turns. +- Writes equations in the ASCII grammar (``d2y/dt2 = ...``), not LaTeX. +- Knows the per-system equation family (gravity, drag, pendulum, spring). + +Then GRPO refines physics accuracy via the verifiable R² reward. + +Run:: + + python -m physix.training.sft \ + --model Qwen/Qwen2.5-1.5B-Instruct \ + --output-dir runs/physix-1.5b-sft \ + --epochs 2 \ + --instances-per-system 32 + +Typical runtime: 5-8 min on an A10G, 3-4 min on an A100. +""" + +from __future__ import annotations + +import argparse +import json +import logging +import os +from pathlib import Path + +import numpy as np +from datasets import Dataset + +from physix.systems import ( + SUPPORTED_SYSTEMS, + SYSTEM_REGISTRY, + get_system, +) +from physix.systems.base import PhysicalSystem, TrajectoryData +from physix.training.prompt import build_prompt +from physix.models import DEFAULT_MAX_TURNS, PhysiXObservation + + +_log = logging.getLogger(__name__) + + +# ─── Dataset ────────────────────────────────────────────────────────────────── + +def _gt_completion(system: PhysicalSystem) -> str: + """Build the ground-truth completion JSON for one system. + + We include the system's sampled parameters so the model learns that the + ``params`` field must contain the symbols it references in the equation. + The SFT target is the *exact* JSON string the env's verifier accepts; + GRPO will later teach the model to refine parameter values per trajectory. + """ + import re as _re + eq = system.ground_truth_equation() + # Extract all identifier tokens that appear in the equation, then keep + # only those that are declared as system parameters. We use a proper + # identifier regex (not split-on-whitespace) so symbols inside function + # calls like sin(theta) and fractions like -(g/L) are caught. + reserved = set(system.state_variables) | {"dt", "d", "t", "sin", "cos", + "tan", "exp", "log", "sqrt", "abs"} + eq_tokens = set(_re.findall(r'\b([A-Za-z_][A-Za-z0-9_]*)\b', eq)) + relevant_keys = eq_tokens & set(system.parameters) - reserved + relevant = {k: round(system.parameters[k], 4) for k in sorted(relevant_keys)} + return json.dumps({ + "equation": eq, + "params": relevant, + "rationale": ( + f"Ground-truth equation for {system.system_id.replace('_', ' ')}." + ), + }) + + +def build_sft_dataset( + system_ids: tuple[str, ...] = SUPPORTED_SYSTEMS, + instances_per_system: int = 32, + seed: int = 0, +) -> Dataset: + if not system_ids: + raise ValueError("system_ids must be non-empty.") + unknown = [sid for sid in system_ids if sid not in SYSTEM_REGISTRY] + if unknown: + raise ValueError( + f"Unknown system_ids in build_sft_dataset: {unknown!r}. " + f"Registered: {sorted(SYSTEM_REGISTRY)!r}." + ) + + rng = np.random.default_rng(seed) + rows: list[dict] = [] + + for system_id in system_ids: + system = get_system(system_id) + for _ in range(instances_per_system): + trajectory = system.simulate(rng) + obs = _build_obs(system, trajectory) + prompt_messages = build_prompt(obs) + completion = _gt_completion(system) + rows.append({"prompt": prompt_messages, "completion": completion}) + + _log.info( + "Built SFT dataset: %d rows across %d systems (%s)", + len(rows), + len(system_ids), + ", ".join(system_ids), + ) + return Dataset.from_list(rows) + + +def _build_obs(system: PhysicalSystem, trajectory: TrajectoryData) -> PhysiXObservation: + return PhysiXObservation( + done=False, + reward=None, + trajectory=trajectory.to_observation_samples(), + state_variables=list(system.state_variables), + hint=system.hint(system.parameters), + history=[], + mismatch_summary="", + turn=0, + turn_remaining=DEFAULT_MAX_TURNS, + system_id=system.system_id, + stats=trajectory.stats(), + reward_breakdown={}, + ) + + +# ─── Training ───────────────────────────────────────────────────────────────── + +def train_sft( + model_name: str = "Qwen/Qwen2.5-1.5B-Instruct", + output_dir: str = "runs/physix-1.5b-sft", + epochs: int = 2, + max_seq_length: int = 2048, + lora_r: int = 16, + lora_alpha: int = 32, + per_device_batch_size: int = 2, + gradient_accumulation_steps: int = 4, + learning_rate: float = 2e-5, + instances_per_system: int = 32, + seed: int = 0, + wandb_run_name: str | None = None, +) -> None: + _configure_logging() + + # Heavy imports: only available in [train] env. + import wandb + from unsloth import FastLanguageModel, PatchFastRL # noqa: F401 + from trl import SFTTrainer, SFTConfig + + # Force a fresh W&B run for SFT regardless of any inherited WANDB_RUN_ID + # / WANDB_RESUME env vars (those are intended for the GRPO stage). If we + # let wandb.init() try to resume a foreign run id it will block for ~90s + # fetching that run's history before giving up. + for stale in ("WANDB_RUN_ID", "WANDB_RESUME"): + os.environ.pop(stale, None) + + wandb.init( + project=os.environ.get("WANDB_PROJECT", "physix-live"), + name=wandb_run_name or f"physix-sft-{epochs}ep", + config={ + "stage": "sft", + "model_name": model_name, + "epochs": epochs, + "lora_r": lora_r, + "lora_alpha": lora_alpha, + "learning_rate": learning_rate, + "per_device_batch_size": per_device_batch_size, + "gradient_accumulation_steps": gradient_accumulation_steps, + "instances_per_system": instances_per_system, + "seed": seed, + }, + tags=["sft", "physix", model_name.split("/")[-1]], + ) + + _log.info("Loading model %s (4-bit, LoRA-%d)", model_name, lora_r) + model, tokenizer = FastLanguageModel.from_pretrained( + model_name=model_name, + max_seq_length=max_seq_length, + load_in_4bit=True, + dtype=None, + ) + model = FastLanguageModel.get_peft_model( + model, + r=lora_r, + lora_alpha=lora_alpha, + target_modules=["q_proj", "k_proj", "v_proj", "o_proj", + "gate_proj", "up_proj", "down_proj"], + bias="none", + use_gradient_checkpointing="unsloth", + random_state=seed, + ) + + dataset = build_sft_dataset(instances_per_system=instances_per_system, seed=seed) + + def _format_row(row: dict) -> dict: + """Combine prompt + completion into a single training string.""" + messages = row["prompt"] + [{"role": "assistant", "content": row["completion"]}] + text = tokenizer.apply_chat_template( + messages, tokenize=False, add_generation_prompt=False + ) + return {"text": text} + + formatted = dataset.map(_format_row, remove_columns=["prompt", "completion"]) + _log.info("SFT dataset ready: %d rows", len(formatted)) + + import torch + sft_config = SFTConfig( + output_dir=output_dir, + num_train_epochs=epochs, + per_device_train_batch_size=per_device_batch_size, + gradient_accumulation_steps=gradient_accumulation_steps, + learning_rate=learning_rate, + max_seq_length=max_seq_length, + dataset_text_field="text", + packing=True, + logging_steps=1, + save_strategy="epoch", + report_to=["wandb"], + seed=seed, + bf16=torch.cuda.is_bf16_supported() if torch.cuda.is_available() else False, + fp16=not torch.cuda.is_bf16_supported() if torch.cuda.is_available() else False, + ) + + trainer = SFTTrainer( + model=model, + tokenizer=tokenizer, + args=sft_config, + train_dataset=formatted, + ) + + _log.info("Starting SFT for %d epochs on %d examples", epochs, len(formatted)) + trainer.train() + + # We save as merged_16bit (full model + config + tokenizer) rather than + # "lora" (adapter weights only). GRPO's downstream + # ``FastLanguageModel.from_pretrained(sft_checkpoint)`` needs a complete + # model directory — config.json + tokenizer + weights — to load. A bare + # adapter shard makes Unsloth raise "No config file found". The merged + # checkpoint is ~3 GB (1.5B params × 2 bytes) which is fine on /tmp. + out_path = Path(output_dir) / "merged" + out_path.mkdir(parents=True, exist_ok=True) + model.save_pretrained_merged( + save_directory=str(out_path), + tokenizer=tokenizer, + save_method="merged_16bit", + ) + _log.info("SFT model (merged 16-bit) saved → %s", out_path) + wandb.finish() + + +# ─── CLI ────────────────────────────────────────────────────────────────────── + +def _configure_logging() -> None: + logging.basicConfig( + level=os.environ.get("PHYSIX_LOG_LEVEL", "INFO"), + format="[%(asctime)s] %(levelname)s %(name)s | %(message)s", + ) + + +def main() -> None: + parser = argparse.ArgumentParser(description="SFT warm-start for PhysiX RLVR.") + parser.add_argument("--model", default="Qwen/Qwen2.5-1.5B-Instruct") + parser.add_argument("--output-dir", default="runs/physix-1.5b-sft") + parser.add_argument("--epochs", type=int, default=2) + parser.add_argument("--instances-per-system", type=int, default=32) + parser.add_argument("--lora-r", type=int, default=32) + parser.add_argument("--learning-rate", type=float, default=2e-5) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--wandb-run-name", default=None, + help="Override W&B run name. Defaults to physix-sft-{epochs}ep.") + args = parser.parse_args() + + os.environ.setdefault("WANDB_PROJECT", "physix-live") + train_sft( + model_name=args.model, + output_dir=args.output_dir, + epochs=args.epochs, + lora_r=args.lora_r, + learning_rate=args.learning_rate, + instances_per_system=args.instances_per_system, + seed=args.seed, + wandb_run_name=args.wandb_run_name, + ) + + +if __name__ == "__main__": + main() diff --git a/physix-live/physix/verifier/__init__.py b/physix-live/physix/verifier/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c0f472062be238e9fa6f3e5df794ab0f5d700e39 --- /dev/null +++ b/physix-live/physix/verifier/__init__.py @@ -0,0 +1,33 @@ +"""Verifier layer: parse hypothesis, simulate, score, summarise mismatch. + +Public API: + +- :func:`parse_equation` (``parser``): convert a SymPy-grammar string into a + callable ODE right-hand-side, validated against a strict whitelist. +- :func:`simulate_hypothesis` (``simulator``): run the parsed RHS forward in + time via ``scipy.integrate.odeint``. +- :func:`compute_match` (``metrics``): R-squared between observed and + predicted trajectories. +- :func:`summarize_mismatch` (``mismatch``): generate a one-sentence English + description of where prediction diverges from observation. +- :func:`compute_reward` (``reward``): combine all components into a + :class:`RewardBreakdown`. +""" + +from physix.verifier.metrics import compute_match, residual_summary +from physix.verifier.mismatch import summarize_mismatch +from physix.verifier.parser import ParseError, ParsedEquation, parse_equation +from physix.verifier.reward import compute_reward +from physix.verifier.simulator import SimulationError, simulate_hypothesis + +__all__ = [ + "compute_match", + "residual_summary", + "summarize_mismatch", + "ParseError", + "ParsedEquation", + "parse_equation", + "compute_reward", + "SimulationError", + "simulate_hypothesis", +] diff --git a/physix-live/physix/verifier/__pycache__/__init__.cpython-311.pyc b/physix-live/physix/verifier/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb62e2278c00f788712abff322d13f52495c80ac Binary files /dev/null and b/physix-live/physix/verifier/__pycache__/__init__.cpython-311.pyc differ diff --git a/physix-live/physix/verifier/__pycache__/metrics.cpython-311.pyc b/physix-live/physix/verifier/__pycache__/metrics.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da4fa5181b41dddd62e35a5ab950a7e8fa7ae150 Binary files /dev/null and b/physix-live/physix/verifier/__pycache__/metrics.cpython-311.pyc differ diff --git a/physix-live/physix/verifier/__pycache__/mismatch.cpython-311.pyc b/physix-live/physix/verifier/__pycache__/mismatch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd45eb7bd6098e86e32fc0e769b55862fcce39c4 Binary files /dev/null and b/physix-live/physix/verifier/__pycache__/mismatch.cpython-311.pyc differ diff --git a/physix-live/physix/verifier/__pycache__/parser.cpython-311.pyc b/physix-live/physix/verifier/__pycache__/parser.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6dc75edfe0198b6dc5b9f885273a32777452908d Binary files /dev/null and b/physix-live/physix/verifier/__pycache__/parser.cpython-311.pyc differ diff --git a/physix-live/physix/verifier/__pycache__/reward.cpython-311.pyc b/physix-live/physix/verifier/__pycache__/reward.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..467f24ceac98e4c76a84583ea59c6c7d70bf2e59 Binary files /dev/null and b/physix-live/physix/verifier/__pycache__/reward.cpython-311.pyc differ diff --git a/physix-live/physix/verifier/__pycache__/simulator.cpython-311.pyc b/physix-live/physix/verifier/__pycache__/simulator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..646076057ec8a881d6178aff30fb0e29f826cdd0 Binary files /dev/null and b/physix-live/physix/verifier/__pycache__/simulator.cpython-311.pyc differ diff --git a/physix-live/physix/verifier/metrics.py b/physix-live/physix/verifier/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..c97a1f219ffee4903c08da61a272d6b8d12fd8f1 --- /dev/null +++ b/physix-live/physix/verifier/metrics.py @@ -0,0 +1,114 @@ +"""Numerical metrics over (observed, predicted) trajectory pairs. + +Responsibility: compute scalar fit quality (R-squared), per-variable +residuals, and lightweight diagnostic statistics. Does no parsing, no +simulation, no English-text generation. +""" + +from __future__ import annotations + +from collections.abc import Iterable + +import numpy as np +from pydantic import BaseModel, ConfigDict, Field + + +class ResidualSummary(BaseModel): + """Diagnostic statistics derived from per-variable residuals. + + Consumed exclusively by :mod:`physix.verifier.mismatch` to render the + English residual summary surfaced to the agent. + """ + + model_config = ConfigDict(frozen=True) + + per_variable_max_abs_residual: dict[str, float] = Field(default_factory=dict) + per_variable_t_of_max_residual: dict[str, float] = Field(default_factory=dict) + per_variable_late_residual_mean: dict[str, float] = Field(default_factory=dict) + overall_r2: float = 0.0 + + +def compute_match( + observed: dict[str, np.ndarray], + predicted: dict[str, np.ndarray], + state_variables: Iterable[str], +) -> float: + """Compute the per-step R-squared used as the primary reward signal. + + Returns the **average** of per-variable R-squared values, clipped to + ``[0, 1]``. This intentionally rewards models that get *some* variables + right even if others diverge. + """ + r2s = [ + _r_squared(observed[var], predicted[var]) + for var in state_variables + if var in observed and var in predicted + ] + if not r2s: + return 0.0 + avg = float(np.mean(r2s)) + return _clip01(avg) + + +def residual_summary( + timestamps: np.ndarray, + observed: dict[str, np.ndarray], + predicted: dict[str, np.ndarray], + state_variables: Iterable[str], +) -> ResidualSummary: + """Build a structured residual summary used downstream by mismatch.py.""" + per_max: dict[str, float] = {} + per_t_max: dict[str, float] = {} + per_late_mean: dict[str, float] = {} + r2_values: list[float] = [] + + for var in state_variables: + if var not in observed or var not in predicted: + continue + obs = observed[var] + pred = predicted[var] + residual = pred - obs + + r2_values.append(_r_squared(obs, pred)) + i_max = int(np.argmax(np.abs(residual))) + per_max[var] = float(np.abs(residual[i_max])) + per_t_max[var] = float(timestamps[i_max]) + + # Mean residual magnitude over the last 25% of the trajectory; this + # is the signal the mismatch summariser uses to detect drift / + # plateau-mismatch. + late_start = int(0.75 * len(timestamps)) + per_late_mean[var] = float(np.mean(np.abs(residual[late_start:]))) + + overall = float(np.mean(r2_values)) if r2_values else 0.0 + + return ResidualSummary( + per_variable_max_abs_residual=per_max, + per_variable_t_of_max_residual=per_t_max, + per_variable_late_residual_mean=per_late_mean, + overall_r2=_clip01(overall), + ) + + +def _r_squared(observed: np.ndarray, predicted: np.ndarray) -> float: + """Coefficient of determination with a zero floor. + + Returns 0.0 when the observed series is constant (degenerate). + Returns 0.0 when the model is worse than the observed mean. + """ + if observed.shape != predicted.shape: + return 0.0 + obs_mean = float(np.mean(observed)) + ss_res = float(np.sum((observed - predicted) ** 2)) + ss_tot = float(np.sum((observed - obs_mean) ** 2)) + if ss_tot <= 0.0: + return 0.0 + return _clip01(1.0 - ss_res / ss_tot) + + +def _clip01(value: float) -> float: + if value < 0.0: + return 0.0 + if value > 1.0: + return 1.0 + return value diff --git a/physix-live/physix/verifier/mismatch.py b/physix-live/physix/verifier/mismatch.py new file mode 100644 index 0000000000000000000000000000000000000000..55d35ad20c60a4a5569350ddf213c5df6e23185e --- /dev/null +++ b/physix-live/physix/verifier/mismatch.py @@ -0,0 +1,138 @@ +"""Generate a one-sentence English summary of where prediction disagrees +with observation. + +Responsibility: convert a :class:`ResidualSummary` plus the two trajectories +into a deterministic English string the agent can use as feedback. No LLM +involved; this is templated text driven by simple rules over the numerical +residuals. + +The output is the only place in the env where structured numerical state is +translated into natural language for the agent. We invest in this carefully +because a 1.5B model reasons better over short English sentences than over +100-row residual tables. +""" + +from __future__ import annotations + +from collections.abc import Iterable + +import numpy as np + +from physix.verifier.metrics import ResidualSummary + + +def summarize_mismatch( + observed: dict[str, np.ndarray], + predicted: dict[str, np.ndarray], + state_variables: Iterable[str], + timestamps: np.ndarray, + summary: ResidualSummary, +) -> str: + """Return a one-sentence English description of the residual. + + The sentence is built by: + + 1. Picking the variable with the **highest** late-window residual mean. + 2. Inspecting whether the residual grows late in the trajectory (drift), + early in the trajectory (initial-condition mismatch), oscillates + around zero (phase / amplitude error), or stays uniformly small + (good fit). + 3. Producing one descriptor for the dominant pattern. + + Returns ``""`` if no residuals could be computed. + """ + if summary.overall_r2 >= 0.93: + return "Predicted and observed trajectories agree closely." + + target = _pick_dominant_variable(summary, state_variables) + if target is None: + return "" + + obs = observed[target] + pred = predicted[target] + residual = pred - obs + + pattern = _classify_pattern(residual, timestamps) + return _render_sentence(target, pattern, summary, timestamps) + + +def _pick_dominant_variable( + summary: ResidualSummary, + state_variables: Iterable[str], +) -> str | None: + """Pick the variable with the largest late-window residual mean.""" + candidates: list[tuple[str, float]] = [] + for var in state_variables: + if var in summary.per_variable_late_residual_mean: + candidates.append((var, summary.per_variable_late_residual_mean[var])) + if not candidates: + return None + return max(candidates, key=lambda kv: kv[1])[0] + + +def _classify_pattern(residual: np.ndarray, timestamps: np.ndarray) -> str: + """Classify the dominant pattern of the residual into one of: + + - ``"diverges_late"``: residual magnitude grows monotonically. + - ``"early_offset"``: large residual near t=0 then shrinks. + - ``"phase_or_amplitude"``: residual oscillates around zero with non-trivial amplitude. + - ``"uniform_small"``: residual is small everywhere. + """ + n = len(residual) + if n == 0: + return "uniform_small" + + early_window = residual[: max(1, n // 4)] + late_window = residual[3 * n // 4 :] + abs_residual = np.abs(residual) + + early_mag = float(np.mean(np.abs(early_window))) + late_mag = float(np.mean(np.abs(late_window))) + overall_mag = float(np.mean(abs_residual)) or 1e-9 + + # Sign-flip count: rough proxy for oscillation around zero. + sign_flips = int(np.sum(np.diff(np.sign(residual)) != 0)) + + if late_mag > 2.0 * early_mag and late_mag > 0.05 * float(np.ptp(residual) + 1e-9): + return "diverges_late" + if early_mag > 2.0 * late_mag: + return "early_offset" + if sign_flips > n // 5 and overall_mag > 0.05 * float(np.ptp(residual) + 1e-9): + return "phase_or_amplitude" + return "uniform_small" + + +def _render_sentence( + variable: str, + pattern: str, + summary: ResidualSummary, + timestamps: np.ndarray, +) -> str: + """Render the chosen pattern into a single English sentence.""" + t_max = summary.per_variable_t_of_max_residual.get(variable, 0.0) + max_abs = summary.per_variable_max_abs_residual.get(variable, 0.0) + + if pattern == "diverges_late": + return ( + f"Predicted {variable!s} diverges from observed past t={t_max:.1f}s " + f"(peak residual {max_abs:.2f}); the late-time behaviour is " + "structurally wrong (consider a missing damping, drag, or " + "saturation term)." + ) + if pattern == "early_offset": + return ( + f"Predicted {variable!s} is offset near t=0 (peak residual " + f"{max_abs:.2f} at t={t_max:.1f}s); the dynamics align later, " + "suggesting an initial-condition or constant-term mismatch." + ) + if pattern == "phase_or_amplitude": + return ( + f"Predicted {variable!s} oscillates around the observed but is " + f"out of phase or amplitude (peak residual {max_abs:.2f}); " + "consider tuning the natural frequency or adding light damping." + ) + return ( + f"Predicted {variable!s} matches observed broadly but residual is " + f"non-trivial (peak {max_abs:.2f} at t={t_max:.1f}s); fine-tune the " + "parameters." + ) diff --git a/physix-live/physix/verifier/parser.py b/physix-live/physix/verifier/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..ce7c9c4a99cddd848b62876ff644b3d4c090ad22 --- /dev/null +++ b/physix-live/physix/verifier/parser.py @@ -0,0 +1,396 @@ +"""Parser for agent-emitted equations of motion. + +RHS is parsed via Python's ``ast`` module, then walked by a whitelist visitor +that only permits Constant / Name / UnaryOp (+/-) / BinOp (+ - * / **) / +Call (bare allowed-function name, no kwargs). Anything else — Attribute, +Subscript, Lambda, IfExp, keyword args, etc. — raises ParseError by +construction. We never call sympify on raw text, so there is no eval stage +that can crash the trainer with an AttributeError. + +Pre-transforms before AST parse: +- ``^`` → ``**`` (physics power notation) +- ``dx/dt`` / bare ``dx`` → ``vx`` when the system pairs x with vx +""" + +from __future__ import annotations + +import ast +import re + +import sympy as sp +from pydantic import BaseModel, ConfigDict + + +class ParseError(ValueError): + """Raised when the agent's text payload violates the equation grammar.""" + + +ALLOWED_FUNCTIONS: dict[str, sp.Function] = { + "sin": sp.sin, + "cos": sp.cos, + "tan": sp.tan, + "exp": sp.exp, + "log": sp.log, + "sqrt": sp.sqrt, + "abs": sp.Abs, + "Abs": sp.Abs, +} + + +def _build_grammar_hint() -> str: + funcs = sorted({name.lower() for name in ALLOWED_FUNCTIONS}) + return ( + "The 'equation' field is an infix ODE in plain ASCII. " + "LHS form: 'dN/dtN' where N is 1 or 2 (omit N for first " + "order, e.g. 'dy/dt' or 'd2y/dt2'). " + "RHS uses operators + - * / ** (or ^ for power), parentheses, " + "the state variables listed under STATE_VARIABLES, and any " + "names you declare in 'params'. " + f"Allowed functions: {' '.join(funcs)}. " + "Velocity convention: when STATE_VARIABLES lists both 'x' and 'vx' " + "(or 'y'/'vy', etc.), use the 'vx' name on the RHS to refer to the " + "first time-derivative of x. The aliases 'dx/dt' and bare 'dx' are " + "also accepted for that case. The system is autonomous: time 't' is " + "not a valid RHS symbol. " + "No LaTeX, no \\frac, no array indexing, no library prefixes " + "(write 'sqrt(x)', not 'np.sqrt(x)'), no keyword arguments. " + "Working examples appear in the HISTORY block of each subsequent turn." + ) + + +GRAMMAR_HINT: str = _build_grammar_hint() + + +_LHS_PATTERN = re.compile( + r""" + ^\s* + d(?P\d*) + (?P[A-Za-z_][A-Za-z0-9_]*) + / + d t + (?P\d*) + \s*$ + """, + re.VERBOSE, +) + +_BIN_OP_TO_SYMPY: dict[type, "callable"] = { + ast.Add: lambda a, b: a + b, + ast.Sub: lambda a, b: a - b, + ast.Mult: lambda a, b: a * b, + ast.Div: lambda a, b: a / b, + ast.Pow: lambda a, b: a**b, +} + + +class Equation(BaseModel): + model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True) + + var: str + order: int + rhs: sp.Expr + + +class ParsedEquation(BaseModel): + model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True) + + equations: tuple[Equation, ...] + free_symbols: frozenset[str] + operator_count: int + + +def parse_equation( + text: str, + state_variables: tuple[str, ...], + parameter_names: frozenset[str], +) -> ParsedEquation: + """Parse and validate the agent's equation payload. + + Only ParseError ever escapes — callers convert it to r_format=0. + """ + if not text or not text.strip(): + raise ParseError("Empty equation payload.") + + raw_equations = _split_equations(text) + if not raw_equations: + raise ParseError("No equations found in payload.") + + allowed_symbols = frozenset(state_variables) | parameter_names + + parsed: list[Equation] = [] + free_symbol_names: set[str] = set() + operator_count = 0 + + for raw in raw_equations: + eq = _parse_one(raw, allowed_symbols, state_variables) + parsed.append(eq) + free_symbol_names.update(s.name for s in eq.rhs.free_symbols) + operator_count += _count_operators(eq.rhs) + + return ParsedEquation( + equations=tuple(parsed), + free_symbols=frozenset(free_symbol_names), + operator_count=operator_count, + ) + + +def _split_equations(text: str) -> list[str]: + parts = re.split(r"[;\n]+", text) + return [p.strip() for p in parts if p.strip()] + + +def _parse_one( + raw: str, + allowed_symbols: frozenset[str], + state_variables: tuple[str, ...], +) -> Equation: + if "=" not in raw: + raise ParseError(f"Equation has no '=' sign: {raw!r}") + lhs_text, rhs_text = raw.split("=", 1) + var, order = _parse_lhs(lhs_text) + rhs_expr = _parse_rhs(rhs_text, allowed_symbols, state_variables) + return Equation(var=var, order=order, rhs=rhs_expr) + + +def _parse_lhs(lhs: str) -> tuple[str, int]: + match = _LHS_PATTERN.match(lhs) + if not match: + raise ParseError( + f"Cannot parse LHS {lhs!r}. Expected 'dN/dtN' where N is " + "1 or 2 (or empty for first order)." + ) + order_top = match.group("order") + order_bot = match.group("order2") + var = match.group("var") + if order_top != order_bot: + raise ParseError( + f"LHS order mismatch in {lhs!r}: top order {order_top!r} vs " + f"bottom order {order_bot!r}." + ) + if order_top == "": + order = 1 + elif order_top in {"1", "2"}: + order = int(order_top) + else: + raise ParseError(f"Only orders 1 and 2 are supported. Got {order_top!r}.") + return var, order + + +def _parse_rhs( + rhs: str, + allowed_symbols: frozenset[str], + state_variables: tuple[str, ...], +) -> sp.Expr: + rhs = rhs.strip() + if not rhs: + raise ParseError("Empty RHS.") + rhs = rhs.replace("^", "**") + rhs = _apply_velocity_alias(rhs, state_variables) + try: + tree = ast.parse(rhs, mode="eval") + except SyntaxError as exc: + raise ParseError( + f"Syntax error in RHS {rhs!r}: {exc.msg}. " + "Expected an infix expression like '-k*x + c*vx'." + ) from exc + return _ast_to_sympy(tree.body, allowed_symbols, state_variables) + + +def _ast_to_sympy( + node: ast.AST, + allowed_symbols: frozenset[str], + state_variables: tuple[str, ...], +) -> sp.Expr: + if isinstance(node, ast.Constant): + if isinstance(node.value, bool) or not isinstance(node.value, (int, float)): + raise ParseError( + f"Only numeric literals allowed on RHS; got " + f"{node.value!r} ({type(node.value).__name__})." + ) + return sp.Number(node.value) + + if isinstance(node, ast.Name): + return _name_to_sympy(node.id, allowed_symbols, state_variables) + + if isinstance(node, ast.UnaryOp): + operand = _ast_to_sympy(node.operand, allowed_symbols, state_variables) + if isinstance(node.op, ast.UAdd): + return +operand + if isinstance(node.op, ast.USub): + return -operand + raise ParseError( + f"Unsupported unary operator {type(node.op).__name__}. " + "Allowed: + (positive), - (negation)." + ) + + if isinstance(node, ast.BinOp): + op_fn = _BIN_OP_TO_SYMPY.get(type(node.op)) + if op_fn is None: + raise ParseError( + f"Unsupported binary operator {type(node.op).__name__}. " + "Allowed: + - * / ** (also '^' as a power synonym)." + ) + left = _ast_to_sympy(node.left, allowed_symbols, state_variables) + right = _ast_to_sympy(node.right, allowed_symbols, state_variables) + return op_fn(left, right) + + if isinstance(node, ast.Call): + return _call_to_sympy(node, allowed_symbols, state_variables) + + if isinstance(node, ast.Attribute): + raise ParseError( + "Attribute access is not allowed in equation RHS " + f"(saw '.{node.attr}'). Use bare function names like " + "'sqrt(x)' or 'sin(theta)', not 'np.sqrt(x)'." + ) + + if isinstance(node, ast.Subscript): + raise ParseError( + "Array indexing is not allowed in equation RHS. " + "Use named scalars declared in 'params'." + ) + + if isinstance(node, ast.Compare): + raise ParseError( + "Comparisons (==, <, >, etc.) are not allowed in equation RHS." + ) + + if isinstance(node, ast.BoolOp): + raise ParseError( + "Boolean operators ('and', 'or') are not allowed in equation RHS." + ) + + if isinstance(node, ast.IfExp): + raise ParseError( + "Conditional expressions ('a if cond else b') are not allowed in " + "equation RHS." + ) + + if isinstance(node, ast.Lambda): + raise ParseError("Lambda expressions are not allowed in equation RHS.") + + if isinstance(node, (ast.Tuple, ast.List, ast.Set, ast.Dict)): + raise ParseError( + f"Collection literal ({type(node).__name__}) is not allowed in " + "equation RHS." + ) + + raise ParseError( + f"Unsupported expression construct {type(node).__name__}. " + "The grammar accepts: numeric literals, allowed identifiers, " + f"+ - * / **, parentheses, and {sorted(ALLOWED_FUNCTIONS)}." + ) + + +def _name_to_sympy( + name: str, + allowed_symbols: frozenset[str], + state_variables: tuple[str, ...], +) -> sp.Symbol: + if name in ALLOWED_FUNCTIONS: + raise ParseError( + f"{name!r} is a function and must be called with parentheses, " + f"e.g. {name}(x)." + ) + if name not in allowed_symbols: + hint = _explain_unknown_symbol(name, state_variables) + suffix = f" {hint}" if hint else "" + raise ParseError( + f"Unknown symbol {name!r}; allowed {sorted(allowed_symbols)!r}." + f"{suffix}" + ) + return sp.Symbol(name) + + +def _call_to_sympy( + node: ast.Call, + allowed_symbols: frozenset[str], + state_variables: tuple[str, ...], +) -> sp.Expr: + if node.keywords: + raise ParseError( + "Keyword arguments are not allowed in function calls " + "(e.g. 'sin(theta=0.1)'). Pass positional arguments only." + ) + for arg in node.args: + if isinstance(arg, ast.Starred): + raise ParseError("Star-arg / unpacking ('*args') is not allowed.") + + if isinstance(node.func, ast.Attribute): + raise ParseError( + "Attribute access is not allowed in equation RHS " + f"(saw '.{node.func.attr}'). Use bare function names like " + "'sqrt(x)' or 'sin(theta)', not 'np.sqrt(x)'." + ) + + if not isinstance(node.func, ast.Name): + raise ParseError( + "Only direct calls to named functions are allowed. " + f"Use one of {sorted(ALLOWED_FUNCTIONS)}, not a computed-name call." + ) + + func_name = node.func.id + if func_name not in ALLOWED_FUNCTIONS: + raise ParseError( + f"Unknown function {func_name!r}; " + f"allowed: {sorted(ALLOWED_FUNCTIONS)}." + ) + + args = [_ast_to_sympy(a, allowed_symbols, state_variables) for a in node.args] + return ALLOWED_FUNCTIONS[func_name](*args) + + +def _apply_velocity_alias(rhs: str, state_variables: tuple[str, ...]) -> str: + aliases = _velocity_aliases(state_variables) + if not aliases: + return rhs + out = rhs + for var, velocity in aliases: + slash_pattern = rf"\bd{re.escape(var)}\s*/\s*dt\b" + out = re.sub(slash_pattern, velocity, out) + bare_pattern = rf"\bd{re.escape(var)}\b" + out = re.sub(bare_pattern, velocity, out) + return out + + +def _velocity_aliases(state_variables: tuple[str, ...]) -> list[tuple[str, str]]: + state_set = set(state_variables) + out: list[tuple[str, str]] = [] + for var in state_variables: + if not var or var.startswith(("d", "v")): + continue + velocity = f"v{var}" + if velocity in state_set: + out.append((var, velocity)) + return out + + +def _explain_unknown_symbol(name: str, state_variables: tuple[str, ...]) -> str: + state_set = set(state_variables) + if name == "t": + return ( + "'t' is not allowed — the equation must be autonomous " + "(express forces via state variables only, no explicit time)." + ) + if name.startswith("d") and len(name) > 1: + base = name[1:] + velocity = f"v{base}" + if velocity in state_set: + return ( + f"Did you mean '{velocity}'? " + f"Use '{velocity}' for the velocity of '{base}'." + ) + if base in state_set: + return ( + f"'{name}' looks like a derivative; this system has no " + f"separate velocity name, write '{base}' on the RHS." + ) + return "" + + +def _count_operators(expr: sp.Expr) -> int: + count = 0 + for node in sp.preorder_traversal(expr): + if not isinstance(node, (sp.Symbol, sp.Number)): + count += 1 + return count diff --git a/physix-live/physix/verifier/reward.py b/physix-live/physix/verifier/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..c6badb1f608b48244f6614af494b5e3999a01bf5 --- /dev/null +++ b/physix-live/physix/verifier/reward.py @@ -0,0 +1,169 @@ +"""Compose the multi-component reward (anti-hack design). + +Responsibility: + +- Take pre-computed ``r_match`` (from :mod:`physix.verifier.metrics`), + ``operator_count`` (from :mod:`physix.verifier.parser`), the previous turn's + match (for env-driven progress; unused in single-turn GRPO), and flags + for whether parsing and simulation succeeded. +- Return a :class:`RewardBreakdown` with all components plus the legacy + weighted total. + +Anti-hack invariants (RCA from W&B run 5kuqns9x): + +1. **`format` requires simulation success, not just parse success.** A + syntactically valid equation that crashes the simulator is a failure, + not a half-success. Otherwise the model learns to emit nonsense that + is "almost runnable" and farm format reward. +2. **`simplicity` is gated on `r_match >= MATCH_GATE`.** An empty/trivial + equation (e.g. ``dx/dt = 0``) parses, simulates, and earns + ``simplicity=1`` for being short — but produces a trajectory wildly + off the truth. We must not pay reward for "elegant nonsense". The + gate forces the model to be at least somewhat physically right + before it is allowed to bank simplicity. +3. **`correctness_bonus` is a binary cliff at high R².** Provides a + strong terminal signal once the model is genuinely close to the + true equation — pushes past the plateau of "decent but not right". +4. **`match_dense = sqrt(r_match)`** gives non-trivial gradient at low + R² values where raw ``r_match`` is near zero and gradient-starved. + +The legacy 4-tuple (match/progress/simplicity/format) remains in the +breakdown for backward compatibility with the demo/UI/eval code; the +GRPO trainer subscribes only to the components it cares about via +``make_reward_funcs`` in ``physix.training.reward_fns``. + +This module owns no NumPy/SciPy dependencies. It only knows about scalars. +""" + +from __future__ import annotations + +import math + +from physix.models import REWARD_WEIGHTS, RewardBreakdown + + +#: Operator-count cap used to normalise ``r_simplicity``. An equation with +#: this many operators or more scores 0.0 on simplicity; an equation with one +#: operator scores ~1.0. +SIMPLICITY_OPERATOR_CAP: int = 12 + +#: Minimum ``r_match`` required to earn any simplicity reward. Below this +#: threshold the equation is judged as "wrong physics" regardless of how +#: short it is, so simplicity collapses to 0. Eliminates the "output +#: ``dx/dt = 0`` for free reward" exploit. +MATCH_GATE_FOR_SIMPLICITY: float = 0.10 + +#: ``r_match`` threshold above which the binary correctness_bonus fires. +#: Calibrated against typical R² distributions from the verifier — 0.70 +#: requires the agent to capture the dominant dynamics, not just the +#: initial condition or a constant approximation. +CORRECTNESS_BONUS_THRESHOLD: float = 0.70 + + +def compute_reward( + *, + parse_succeeded: bool, + r_match: float, + operator_count: int, + previous_r_match: float, + simulation_succeeded: bool = True, +) -> RewardBreakdown: + """Compose the reward components for one turn. + + Failure modes (return all-zero except where noted): + + - Parse failure: everything 0. The agent emitted unparseable output. + - Simulation failure: everything 0. The equation parsed but produced + a non-runnable system (NaN/inf, integration blowup, etc.). + - Trivial-but-runnable output (``r_match < MATCH_GATE_FOR_SIMPLICITY``): + ``format=1`` (we acknowledge it parsed and ran), but ``simplicity=0``. + """ + if not parse_succeeded or not simulation_succeeded: + # Hard zero. No partial credit for parseable-but-broken or + # parseable-but-uncomputable output. (Empirically, leaving any + # partial credit here produces immediate reward hacking.) + return RewardBreakdown( + match=0.0, + progress=0.0, + simplicity=0.0, + format=0.0, + total=0.0, + ) + + # Past this point: the equation parsed AND simulated. ``r_match`` is + # a legitimate signal of physical correctness. + r_format = 1.0 + r_simplicity = ( + _simplicity_score(operator_count) + if r_match >= MATCH_GATE_FOR_SIMPLICITY + else 0.0 + ) + r_progress = _progress_score(r_match=r_match, previous_r_match=previous_r_match) + + total = _weighted_total( + match=r_match, + progress=r_progress, + simplicity=r_simplicity, + format=r_format, + ) + + return RewardBreakdown( + match=r_match, + progress=r_progress, + simplicity=r_simplicity, + format=r_format, + total=total, + ) + + +def correctness_bonus(r_match: float) -> float: + """Binary cliff: 1.0 iff ``r_match >= CORRECTNESS_BONUS_THRESHOLD``.""" + return 1.0 if r_match >= CORRECTNESS_BONUS_THRESHOLD else 0.0 + + +def match_dense(r_match: float) -> float: + """Square-root-shaped match reward. + + ``sqrt(R²)`` magnifies small but non-zero matches — the model gets a + meaningful gradient even when raw ``r_match`` is 0.05 or 0.10 + (near-zero linear value but ``sqrt(0.10) ≈ 0.32``). Saturates at 1.0. + """ + if r_match <= 0.0: + return 0.0 + if r_match >= 1.0: + return 1.0 + return float(math.sqrt(r_match)) + + +def _simplicity_score(operator_count: int) -> float: + """Map raw operator count to a [0, 1] score where smaller is better.""" + if operator_count <= 0: + return 1.0 + if operator_count >= SIMPLICITY_OPERATOR_CAP: + return 0.0 + return 1.0 - (operator_count / SIMPLICITY_OPERATOR_CAP) + + +def _progress_score(*, r_match: float, previous_r_match: float) -> float: + """Score for improving the physics fit over the previous turn (env only).""" + delta = r_match - previous_r_match + if delta <= 0.0: + return 0.0 + if delta >= 1.0: + return 1.0 + return float(delta) + + +def _weighted_total( + *, + match: float, + progress: float, + simplicity: float, + format: float, +) -> float: + return float( + REWARD_WEIGHTS["match"] * match + + REWARD_WEIGHTS["progress"] * progress + + REWARD_WEIGHTS["simplicity"] * simplicity + + REWARD_WEIGHTS["format"] * format + ) diff --git a/physix-live/physix/verifier/simulator.py b/physix-live/physix/verifier/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..59e882910c54cb74a568ee1b8ad69111b77924e7 --- /dev/null +++ b/physix-live/physix/verifier/simulator.py @@ -0,0 +1,224 @@ +"""Forward-simulate the agent's parsed hypothesis. + +Responsibility: + +- Given a :class:`ParsedEquation`, the system's state-variable layout, the + agent's parameter dictionary, and a set of initial conditions and + timestamps, run ``scipy.integrate.odeint`` to produce a predicted + trajectory in the same shape as the system's observed data. + +What this module does not do: parse text (see :mod:`physix.verifier.parser`), +score the trajectory (see :mod:`physix.verifier.metrics`), or compose rewards +(see :mod:`physix.verifier.reward`). +""" + +from __future__ import annotations + +from collections.abc import Iterable +from typing import Callable + +import numpy as np +import sympy as sp +from scipy.integrate import odeint + +from physix.verifier.parser import ParsedEquation + + +class SimulationError(RuntimeError): + """Raised when the proposed system cannot be integrated numerically. + + Common causes: NaN/Inf produced by ``odeint``, mass-matrix singularity, + or stiff dynamics that exhaust the integrator's step budget. + """ + + +def simulate_hypothesis( + parsed: ParsedEquation, + state_variables: Iterable[str], + parameters: dict[str, float], + initial_conditions: dict[str, float], + timestamps: np.ndarray, +) -> dict[str, np.ndarray]: + """Integrate the agent's hypothesis forward in time. + + Args: + parsed: Parsed equations from :func:`physix.verifier.parser.parse_equation`. + state_variables: Ordering of state variables in the underlying + physical system. Used to derive the integration state vector. + parameters: Numerical parameter substitutions supplied by the agent. + initial_conditions: Initial state values keyed by variable name. + timestamps: 1-D array of times at which to record state. + + Returns: + A dict mapping each state variable to its predicted trajectory + (1-D array of the same length as ``timestamps``). + """ + state_vars = tuple(state_variables) + int_layout = _build_integration_layout(parsed, state_vars) + try: + rhs_callable = _compile_rhs(parsed, int_layout, parameters) + except Exception as exc: # noqa: BLE001 — surfaced as SimulationError below + raise SimulationError(f"failed to compile RHS: {exc}") from exc + + initial_state = _build_initial_state(int_layout, initial_conditions) + + try: + result = odeint( + rhs_callable, + initial_state, + timestamps, + full_output=False, + mxstep=2000, + rtol=1e-6, + atol=1e-9, + ) + except Exception as exc: # noqa: BLE001 + # ``odeint`` propagates whatever the user-supplied RHS callable + # raises. The model can emit equations that lambdify into Python + # code which then trips ``TypeError`` (e.g. ``np.sqrt`` on a + # SymPy ``Add``), ``ZeroDivisionError``, ``OverflowError``, etc. + # Any of those should be surfaced to the env as a clean + # ``SimulationError`` (= ``r_match=0`` for the turn) rather than + # crashing the route with a 500. + raise SimulationError(f"odeint failed: {exc}") from exc + + if not np.all(np.isfinite(result)): + raise SimulationError("Predicted trajectory contains NaN or Inf values.") + + return _project_back_to_state_vars(result, int_layout, state_vars) + + +_IntegrationLayout = tuple[tuple[str, ...], dict[str, int]] + + +def _build_integration_layout( + parsed: ParsedEquation, + state_vars: tuple[str, ...], +) -> _IntegrationLayout: + """Return ``(integration_vars, index)`` for the integration state. + + For a system with second-order ODEs we need to integrate both ``var`` and + ``dvar/dt``. We prefix-derive the names: e.g. ``y -> [y, vy]``, with the + convention that ``v`` is the first time derivative of ```` + (matching the conventions used in :mod:`physix.systems.tier1`). + """ + integration_vars: list[str] = [] + + eq_by_var = {eq.var: eq for eq in parsed.equations} + + for var in state_vars: + # Skip variables that are themselves first derivatives of another + # state variable (e.g. ``vy`` paired with ``y``); those will be added + # as part of the higher-order companion. + if _is_velocity_of(var, state_vars): + continue + + eq = eq_by_var.get(var) + if eq is not None and eq.order == 2: + integration_vars.append(var) + integration_vars.append(_velocity_name(var)) + continue + if eq is not None and eq.order == 1: + integration_vars.append(var) + continue + # No matching equation — accept anyway, treating as zero-derivative. + integration_vars.append(var) + + # Now also append any equations whose var was not in state_vars (e.g. + # the agent named a derivative directly). We log these but do not crash; + # ``rhs_callable`` will simply not see them. + declared = set(integration_vars) + for eq in parsed.equations: + if eq.var in declared: + continue + if eq.order == 2: + integration_vars.append(eq.var) + integration_vars.append(_velocity_name(eq.var)) + else: + integration_vars.append(eq.var) + + index = {name: i for i, name in enumerate(integration_vars)} + return tuple(integration_vars), index + + +def _is_velocity_of(var: str, state_vars: tuple[str, ...]) -> bool: + """True if ``var`` looks like the first derivative of another state var.""" + if var.startswith("v"): + return var[1:] in state_vars + if var.startswith("d"): + return var[1:] in state_vars + return False + + +def _velocity_name(var: str) -> str: + """Convention for naming a first time derivative.""" + if var.startswith("theta"): + return "d" + var + return "v" + var + + +def _compile_rhs( + parsed: ParsedEquation, + layout: _IntegrationLayout, + parameters: dict[str, float], +) -> Callable[[np.ndarray, float], np.ndarray]: + """Build a Python callable f(state, t) -> dstate/dt for ``odeint``.""" + integration_vars, index = layout + eq_by_var = {eq.var: eq for eq in parsed.equations} + + # Lambdify each equation's RHS once. Symbols are bound to integration + # variables (state) and to scalar parameters (substituted). + state_symbols = sp.symbols(" ".join(integration_vars)) + if not isinstance(state_symbols, tuple): + state_symbols = (state_symbols,) + + rhs_lambdas: dict[str, Callable[..., float]] = {} + for var, eq in eq_by_var.items(): + rhs = eq.rhs.subs({sp.Symbol(k): v for k, v in parameters.items()}) + rhs_lambdas[var] = sp.lambdify(state_symbols, rhs, modules="numpy") + + def _rhs(state: np.ndarray, t: float) -> np.ndarray: + derivs = np.zeros_like(state) + for var, eq in eq_by_var.items(): + if eq.order == 1: + idx = index[var] + derivs[idx] = float(rhs_lambdas[var](*state)) + else: # order == 2 + pos_idx = index[var] + vel_name = _velocity_name(var) + vel_idx = index[vel_name] + derivs[pos_idx] = state[vel_idx] + derivs[vel_idx] = float(rhs_lambdas[var](*state)) + return derivs + + return _rhs + + +def _build_initial_state( + layout: _IntegrationLayout, + initial_conditions: dict[str, float], +) -> np.ndarray: + """Project the IC dict into the integration variable order.""" + integration_vars, _ = layout + state = np.zeros(len(integration_vars), dtype=float) + for i, var in enumerate(integration_vars): + state[i] = float(initial_conditions.get(var, 0.0)) + return state + + +def _project_back_to_state_vars( + result: np.ndarray, + layout: _IntegrationLayout, + state_vars: tuple[str, ...], +) -> dict[str, np.ndarray]: + """Slice the integration output into per-system-variable trajectories.""" + _, index = layout + out: dict[str, np.ndarray] = {} + for var in state_vars: + if var in index: + out[var] = result[:, index[var]] + else: + # The agent never modelled this variable; predict the first + # entry constant. This is rare and kept defensive. + out[var] = np.full(result.shape[0], float(result[0, 0])) + return out diff --git a/physix-live/pyproject.toml b/physix-live/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..899113cedadbb7d0b8b890de9654f042210d43cf --- /dev/null +++ b/physix-live/pyproject.toml @@ -0,0 +1,48 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "physix-live" +version = "0.1.0" +description = "OpenEnv RL environment for iterative equation discovery from trajectory data" +authors = [{ name = "PhysiX-Live Team" }] +requires-python = ">=3.10" +dependencies = [ + "openenv-core[core]>=0.2.2", + "numpy>=1.24", + "scipy>=1.10", + "sympy>=1.12", + "fastapi>=0.110", + "uvicorn>=0.29", + "pydantic>=2.5", + "requests>=2.31", +] + +[project.optional-dependencies] +dev = ["pytest>=7.4", "ruff>=0.4"] +# Training stack pinned to versions verified to work together. trl is +# HARD-pinned: see physix-train/Dockerfile for the rationale (Unsloth's +# patch_trl_openenv hook crashes on trl >=0.26). +train = [ + "torch>=2.4", + "transformers>=4.56.1", + "accelerate>=1.4", + "trl>=0.18.2,!=0.19.0,<=0.24.0", + "unsloth>=2025.4", + "wandb>=0.16", + "datasets>=3.0", + "huggingface_hub>=0.24,<1.0", +] +demo = ["ollama>=0.4"] + +[project.scripts] +physix-server = "physix.server.app:main" +physix-sft = "physix.training.sft:main" +physix-grpo = "physix.training.loop:main" + +[tool.hatch.build.targets.wheel] +packages = ["physix"] + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/physix-live/tests/__init__.py b/physix-live/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/physix-live/tests/__pycache__/__init__.cpython-311.pyc b/physix-live/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab4abbba66224c485a538ced17d67b66c9497523 Binary files /dev/null and b/physix-live/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/physix-live/tests/__pycache__/test_client_ws.cpython-311-pytest-9.0.3.pyc b/physix-live/tests/__pycache__/test_client_ws.cpython-311-pytest-9.0.3.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53f682fd661bc89c8567d0d581cae6725df7ee65 Binary files /dev/null and b/physix-live/tests/__pycache__/test_client_ws.cpython-311-pytest-9.0.3.pyc differ diff --git a/physix-live/tests/__pycache__/test_dataset.cpython-311-pytest-9.0.3.pyc b/physix-live/tests/__pycache__/test_dataset.cpython-311-pytest-9.0.3.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac99e643e93594c27965f497d2d64f468951ae15 Binary files /dev/null and b/physix-live/tests/__pycache__/test_dataset.cpython-311-pytest-9.0.3.pyc differ diff --git a/physix-live/tests/__pycache__/test_environment.cpython-311-pytest-9.0.3.pyc b/physix-live/tests/__pycache__/test_environment.cpython-311-pytest-9.0.3.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44ec4d3a1606d2e586a595fb88b8f7c0c00f7783 Binary files /dev/null and b/physix-live/tests/__pycache__/test_environment.cpython-311-pytest-9.0.3.pyc differ diff --git a/physix-live/tests/__pycache__/test_interactive_api.cpython-311-pytest-9.0.3.pyc b/physix-live/tests/__pycache__/test_interactive_api.cpython-311-pytest-9.0.3.pyc new file mode 100644 index 0000000000000000000000000000000000000000..909593e0bcbd70138263025e55409ab95b0aefaa Binary files /dev/null and b/physix-live/tests/__pycache__/test_interactive_api.cpython-311-pytest-9.0.3.pyc differ diff --git a/physix-live/tests/__pycache__/test_prompt.cpython-311-pytest-9.0.3.pyc b/physix-live/tests/__pycache__/test_prompt.cpython-311-pytest-9.0.3.pyc new file mode 100644 index 0000000000000000000000000000000000000000..958e5e5c508370f79ad0b8cc7163003a4d9384d3 Binary files /dev/null and b/physix-live/tests/__pycache__/test_prompt.cpython-311-pytest-9.0.3.pyc differ diff --git a/physix-live/tests/__pycache__/test_scorer.cpython-311-pytest-9.0.3.pyc b/physix-live/tests/__pycache__/test_scorer.cpython-311-pytest-9.0.3.pyc new file mode 100644 index 0000000000000000000000000000000000000000..534400679f6fd878107a9638a91e40386f45a589 Binary files /dev/null and b/physix-live/tests/__pycache__/test_scorer.cpython-311-pytest-9.0.3.pyc differ diff --git a/physix-live/tests/test_client_ws.py b/physix-live/tests/test_client_ws.py new file mode 100644 index 0000000000000000000000000000000000000000..e5295548590937d96f6a80b6e5e0775df5f0f354 --- /dev/null +++ b/physix-live/tests/test_client_ws.py @@ -0,0 +1,88 @@ +"""WebSocket smoke test: spin up the FastAPI server in-process and drive it +through :class:`physix.PhysiXEnv` over a real WebSocket connection. + +This catches regressions in the wire protocol (action/observation +serialisation, session lifecycle) that the in-process +``test_environment.py`` cannot. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import socket +import threading +import time +from collections.abc import Iterator + +import pytest +import uvicorn + +from physix.client import PhysiXEnv +from physix.models import PhysiXAction +from physix.server.app import app + + +# --------------------------------------------------------------------------- +# Server fixture +# --------------------------------------------------------------------------- + + +def _free_port() -> int: + """Return an OS-assigned free TCP port.""" + with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: + sock.bind(("127.0.0.1", 0)) + return int(sock.getsockname()[1]) + + +@pytest.fixture(scope="module") +def server_url() -> Iterator[str]: + """Run uvicorn in a daemon thread for the duration of the module.""" + port = _free_port() + config = uvicorn.Config(app, host="127.0.0.1", port=port, log_level="warning") + server = uvicorn.Server(config) + + thread = threading.Thread(target=server.run, daemon=True) + thread.start() + + deadline = time.time() + 10.0 + while not server.started and time.time() < deadline: + time.sleep(0.05) + if not server.started: + pytest.fail("uvicorn server failed to start within timeout") + + try: + yield f"http://127.0.0.1:{port}" + finally: + server.should_exit = True + thread.join(timeout=5.0) + + +# --------------------------------------------------------------------------- +# Test +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def _drive_episode(base_url: str) -> None: + """One reset + step against the live server, asserting reward shape.""" + async with PhysiXEnv(base_url=base_url) as env: + result = await env.reset(system_id="free_fall", seed=11) + + assert result.done is False + assert result.observation.system_id == "free_fall" + assert result.observation.turn == 0 + assert len(result.observation.trajectory) > 0 + + result = await env.step( + PhysiXAction(equation="d2y/dt2 = -9.81", params={}, rationale="free fall") + ) + + breakdown = result.observation.reward_breakdown + assert breakdown["format"] == 1.0 + assert breakdown["match"] >= 0.9 + assert result.done is True + + +def test_websocket_round_trip(server_url: str) -> None: + asyncio.run(_drive_episode(server_url)) diff --git a/physix-live/tests/test_dataset.py b/physix-live/tests/test_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..579b63521d248556366b2a5e497ffa75013983c1 --- /dev/null +++ b/physix-live/tests/test_dataset.py @@ -0,0 +1,92 @@ +"""Unit tests for :mod:`physix.training.dataset`.""" + +from __future__ import annotations + +import pytest + +from physix.systems import SUPPORTED_SYSTEMS +from physix.training.dataset import ( + DatasetSpec, + EvalDatasetSpec, + build_eval_dataset, + build_training_dataset, +) + + +_EXPECTED_COLUMNS = { + "prompt", + "system_id", + "state_variables", + "parameters", + "initial_conditions", + "timestamps", + "observed", + "previous_r_match", +} + + +def test_training_dataset_has_expected_schema() -> None: + ds = build_training_dataset(DatasetSpec(instances_per_system=2)) + + assert _EXPECTED_COLUMNS.issubset(set(ds.column_names)) + # Default curriculum is the 3 demo systems × 2 instances = 6 rows. + assert len(ds) == len(SUPPORTED_SYSTEMS) * 2 + + +def test_training_dataset_default_curriculum_is_demo_systems() -> None: + """Default DatasetSpec must train on exactly the same systems the + live demo exposes. Mismatches would mean GRPO improves systems we + never benchmark — the failure mode that produced flat headline + metrics in the v1 training run. + """ + ds = build_training_dataset(DatasetSpec(instances_per_system=1)) + assert set(ds["system_id"]) == set(SUPPORTED_SYSTEMS) + + +def test_training_dataset_explicit_system_ids_override_default() -> None: + ds = build_training_dataset( + DatasetSpec(system_ids=("free_fall", "simple_pendulum"), instances_per_system=1) + ) + assert set(ds["system_id"]) == {"free_fall", "simple_pendulum"} + + +def test_training_dataset_rejects_unknown_system_ids() -> None: + with pytest.raises(ValueError, match="Unknown system_ids"): + build_training_dataset(DatasetSpec(system_ids=("not_a_real_system",))) + + +def test_training_dataset_rejects_empty_system_ids() -> None: + with pytest.raises(ValueError, match="non-empty"): + build_training_dataset(DatasetSpec(system_ids=())) + + +def test_training_dataset_prompts_are_chat_lists() -> None: + ds = build_training_dataset(DatasetSpec(instances_per_system=1)) + prompt = ds[0]["prompt"] + + assert isinstance(prompt, list) + assert prompt[0]["role"] == "system" + assert prompt[1]["role"] == "user" + assert "TRAJECTORY" in prompt[1]["content"] + + +def test_eval_dataset_marks_held_out_rows() -> None: + ds = build_eval_dataset(EvalDatasetSpec(instances_per_system=1)) + + held_out_rows = [r for r in ds if r["is_held_out"]] + train_rows = [r for r in ds if not r["is_held_out"]] + + assert len(held_out_rows) >= 2 # 2 Tier 3 systems + assert len(train_rows) >= 6 # 6 Tier 1+2 systems + held_out_ids = {row["system_id"] for row in held_out_rows} + assert held_out_ids == {"projectile_drag", "charged_b_field"} + + +def test_dataset_observed_arrays_match_state_variables() -> None: + ds = build_training_dataset(DatasetSpec(instances_per_system=1)) + + for row in ds: + observed = row["observed"] + for var in row["state_variables"]: + assert var in observed + assert len(observed[var]) > 0 diff --git a/physix-live/tests/test_environment.py b/physix-live/tests/test_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..eccf6a64130779c09e7b2bd6b5a9c58bb27a5da5 --- /dev/null +++ b/physix-live/tests/test_environment.py @@ -0,0 +1,180 @@ +"""End-to-end smoke tests for :class:`PhysiXEnvironment`. + +These tests exercise the full pipeline (parse + simulate + score + record) +without spinning up a FastAPI server. They serve as the first sanity check +that the parser, simulator, metrics, and reward composer interoperate. +""" + +from __future__ import annotations + +import pytest + +from physix.models import CONVERGENCE_THRESHOLD, PhysiXAction +from physix.server.environment import PhysiXEnvironment +from physix.systems import SystemTier + + +# --------------------------------------------------------------------------- +# Fixtures +# --------------------------------------------------------------------------- + + +@pytest.fixture +def env() -> PhysiXEnvironment: + """Deterministic env restricted to Tier 1 systems for fast tests.""" + return PhysiXEnvironment(seed=42, train_tiers=(SystemTier.TIER_1,)) + + +# --------------------------------------------------------------------------- +# Tests +# --------------------------------------------------------------------------- + + +def test_reset_returns_well_formed_observation(env: PhysiXEnvironment) -> None: + obs = env.reset(system_id="free_fall") + + assert obs.system_id == "free_fall" + assert obs.turn == 0 + assert obs.turn_remaining > 0 + assert obs.history == [] + assert obs.mismatch_summary == "" + assert "y" in obs.state_variables and "vy" in obs.state_variables + assert len(obs.trajectory) == 100 + assert obs.hint # non-empty + assert obs.done is False + + +def test_step_with_ground_truth_rewards_high(env: PhysiXEnvironment) -> None: + """The exact ground-truth equation should yield r_match close to 1.""" + env.reset(system_id="free_fall") + + obs = env.step(PhysiXAction(equation="d2y/dt2 = -9.81", params={})) + breakdown = obs.reward_breakdown + + assert breakdown["format"] == 1.0 + assert breakdown["match"] >= 0.95 + assert obs.reward >= CONVERGENCE_THRESHOLD * 0.5 # weighted total floor + + +def test_step_with_unparseable_equation_short_circuits( + env: PhysiXEnvironment, +) -> None: + """A junk payload should set r_format=0 and other components to 0.""" + env.reset(system_id="free_fall") + + obs = env.step(PhysiXAction(equation="not a real equation")) + breakdown = obs.reward_breakdown + + assert breakdown["format"] == 0.0 + assert breakdown["match"] == 0.0 + assert breakdown["progress"] == 0.0 + assert breakdown["simplicity"] == 0.0 + assert "Parse error" in obs.mismatch_summary + + +def test_episode_terminates_on_convergence(env: PhysiXEnvironment) -> None: + """High-quality match should set done=True via the convergence threshold.""" + env.reset(system_id="free_fall") + + obs = env.step(PhysiXAction(equation="d2y/dt2 = -9.81")) + + assert obs.done is True + + +def test_history_accumulates_across_turns(env: PhysiXEnvironment) -> None: + """Each step should append exactly one history entry.""" + env.reset(system_id="free_fall_drag") + + obs1 = env.step(PhysiXAction(equation="d2y/dt2 = -9.81")) + assert len(obs1.history) == 1 + assert obs1.history[0]["equation"] == "d2y/dt2 = -9.81" + + if not obs1.done: + obs2 = env.step( + PhysiXAction(equation="d2y/dt2 = -9.81 + 0.05 * vy**2"), + ) + assert len(obs2.history) == 2 + assert obs2.history[1]["equation"] == "d2y/dt2 = -9.81 + 0.05 * vy**2" + + +def test_progress_reward_rewards_improvement(env: PhysiXEnvironment) -> None: + """A second-turn improvement should yield positive r_progress.""" + env.reset(system_id="free_fall_drag") + + # Turn 1: pure gravity (decent fit but missing drag). + obs1 = env.step(PhysiXAction(equation="d2y/dt2 = -9.81")) + if obs1.done: + pytest.skip("episode converged on turn 1") + + # Turn 2: add drag (closer fit). + obs2 = env.step( + PhysiXAction(equation="d2y/dt2 = -9.81 + 0.05 * vy**2"), + ) + + assert obs2.reward_breakdown["match"] >= obs1.reward_breakdown["match"] + if obs2.reward_breakdown["match"] > obs1.reward_breakdown["total"]: + assert obs2.reward_breakdown["progress"] > 0.0 + + +def test_max_turns_terminates_episode() -> None: + """When budget is exhausted with no convergence, ``done`` flips true.""" + env = PhysiXEnvironment(seed=0, max_turns=3, train_tiers=(SystemTier.TIER_1,)) + env.reset(system_id="simple_pendulum") + + last_obs = None + for _ in range(3): + # Deliberately wrong-but-parseable equation. + last_obs = env.step(PhysiXAction(equation="d2theta/dt2 = 0")) + + assert last_obs is not None + assert last_obs.done is True + assert last_obs.turn_remaining == 0 + + +def test_state_property_exposes_episode_id(env: PhysiXEnvironment) -> None: + obs = env.reset(system_id="free_fall") + assert env.state.episode_id is not None + assert env.state.episode_id # non-empty string + assert env.state.system_id == "free_fall" + assert obs.system_id == env.state.system_id + + +@pytest.mark.parametrize( + "system_id, equation", + [ + # Pendulum-like system with a sqrt of an Add — historically + # produced a TypeError ("loop of ufunc does not support argument + # 0 of type Add which has no callable sqrt method") that escaped + # the simulator and 500-ed the route. + ("simple_pendulum", "d2theta/dt2 = -sqrt(dtheta**2 + theta**2) * sin(theta)"), + # sqrt of a guaranteed-negative quantity → numpy emits NaN. + ("simple_pendulum", "d2theta/dt2 = -sqrt(-theta**2 - 1)"), + # Division by zero from constant numerics in the RHS. + ("free_fall", "d2y/dt2 = -9.81 / (y - y)"), + # Pathological growth that overflows odeint. + ("free_fall", "d2y/dt2 = exp(exp(exp(y)))"), + # log of zero (-inf) propagating through the RHS. + ("free_fall", "d2y/dt2 = log(0 * y)"), + ], +) +def test_step_swallows_simulator_failures_as_format_zero_match_zero( + system_id: str, equation: str +) -> None: + """``step`` must never propagate a TypeError / overflow / NaN out of + the simulator into the route layer. A model-emitted equation that + parses but blows up numerically should score ``r_match=0`` cleanly, + surface a ``Simulation error: ...`` mismatch, and let the episode + continue. Without the broadened exception catch in + :func:`simulate_hypothesis`, several of these would 500 the server. + """ + env = PhysiXEnvironment(seed=0, train_tiers=(SystemTier.TIER_1,)) + env.reset(system_id=system_id) + + obs = env.step(PhysiXAction(equation=equation)) + + assert obs.reward_breakdown["match"] == 0.0 + # The equation parses, so format should be 1; any "format=0" here + # indicates parse rejection (also acceptable for these inputs). + assert obs.reward_breakdown["format"] in (0.0, 1.0) + # Either path must produce a non-empty diagnostic string. + assert obs.mismatch_summary diff --git a/physix-live/tests/test_interactive_api.py b/physix-live/tests/test_interactive_api.py new file mode 100644 index 0000000000000000000000000000000000000000..b12b400268e20ca3b1d0e843168272a96cdae3d5 --- /dev/null +++ b/physix-live/tests/test_interactive_api.py @@ -0,0 +1,329 @@ +"""End-to-end tests for the ``/interactive/*`` router.""" + +from __future__ import annotations + +import json +from collections.abc import Iterable + +import pytest +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from fastapi.testclient import TestClient +from openenv.core.env_server import create_fastapi_app + +from physix.models import PhysiXAction, PhysiXObservation +from physix.server.app import build_app +from physix.server.environment import PhysiXEnvironment +from physix.server.interactive import ( + LlmModelInfo, + LlmModelsResponse, + LlmStepRequest, + build_interactive_router, +) + + +@pytest.fixture +def client() -> TestClient: + return TestClient(build_app()) + + +def _build_app_with_stubbed_llm( + completions: Iterable[str], + *, + models_response: LlmModelsResponse | None = None, +) -> FastAPI: + """Build a clone of the production app whose LLM policy returns + pre-canned completion strings in order. + + Each call to the policy pops the next completion off the deque, so a + test that wants three turns supplies three strings. Optionally + overrides the model lister so the ``/interactive/models`` route can + be exercised without touching the real Ollama daemon. + """ + queue = list(completions) + + def _stub_policy(_payload: LlmStepRequest): + def _policy(_prompt: list[dict[str, str]]) -> str: + if not queue: + raise AssertionError("Stubbed LLM ran out of canned completions.") + return queue.pop(0) + + return _policy + + def _stub_lister() -> LlmModelsResponse: + return models_response or LlmModelsResponse(models=[]) + + app = create_fastapi_app( + env=PhysiXEnvironment, + action_cls=PhysiXAction, + observation_cls=PhysiXObservation, + ) + app.add_middleware( + CORSMiddleware, + allow_origins=["http://localhost:5173"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + ) + app.include_router( + build_interactive_router( + policy_factory=_stub_policy, + models_lister=_stub_lister, + ) + ) + return app + + +# --- Catalogue --- + + +def test_systems_endpoint_returns_supported_systems_in_order( + client: TestClient, +) -> None: + from physix.systems.registry import SUPPORTED_SYSTEMS + + response = client.get("/interactive/systems") + assert response.status_code == 200 + + catalogue = response.json() + returned_ids = [row["system_id"] for row in catalogue] + assert returned_ids == list(SUPPORTED_SYSTEMS) + + system_ids = set(returned_ids) + assert "projectile_drag" not in system_ids + assert "charged_b_field" not in system_ids + # Sanity check: the systems we pruned for plateauing on 7B must not + # leak through either, since the whole point of the curriculum is to + # hide them from the demo dropdown. + assert "free_fall_drag" not in system_ids + assert "damped_pendulum" not in system_ids + + +# --- Local model catalogue --- + + +def test_models_endpoint_returns_injected_list() -> None: + """Frontend reads installed model tags from the server, not a hardcoded + list. The route must surface whatever the lister reports.""" + canned = LlmModelsResponse( + models=[ + LlmModelInfo(name="qwen2.5:7b", size_bytes=4_700_000_000, parameter_size="7.6B"), + LlmModelInfo(name="qwen2.5:1.5b-instruct", size_bytes=986_000_000), + ] + ) + app = _build_app_with_stubbed_llm([], models_response=canned) + with TestClient(app) as client: + response = client.get("/interactive/models") + + assert response.status_code == 200, response.text + body = response.json() + assert body["error"] is None + assert [m["name"] for m in body["models"]] == [ + "qwen2.5:7b", + "qwen2.5:1.5b-instruct", + ] + assert body["models"][0]["parameter_size"] == "7.6B" + + +def test_models_endpoint_returns_empty_with_error_when_daemon_unavailable() -> None: + """When Ollama is unreachable the route degrades to an empty list and + surfaces a human-readable hint, instead of 5xx-ing the page.""" + canned = LlmModelsResponse( + models=[], + error="Could not reach the local Ollama daemon (test). Is 'ollama serve' running?", + ) + app = _build_app_with_stubbed_llm([], models_response=canned) + with TestClient(app) as client: + response = client.get("/interactive/models") + + assert response.status_code == 200 + body = response.json() + assert body["models"] == [] + assert "Ollama" in body["error"] + + +# --- Session lifecycle --- + + +def test_session_lifecycle_create_summary_delete(client: TestClient) -> None: + """Create → reset observation → summary → delete → 404. The actual + advancing of turn counter / format scoring / predicted overlay + lives in the ``/llm-step`` tests below; this is the lifecycle + skeleton (the only flow the UI actually exercises now that the + manual ``/step`` route is gone).""" + create = client.post( + "/interactive/sessions", + json={"system_id": "free_fall", "seed": 42, "max_turns": 4}, + ) + assert create.status_code == 200, create.text + body = create.json() + + session_id = body["session_id"] + assert isinstance(session_id, str) and session_id + assert body["system"]["system_id"] == "free_fall" + assert "tier" not in body["system"] # tier is dropped from the public schema + assert body["max_turns"] == 4 + assert body["observation"]["turn"] == 0 + assert body["observation"]["done"] is False + assert len(body["observation"]["trajectory"]) == 100 + + summary = client.get(f"/interactive/sessions/{session_id}").json() + assert summary["turn"] == 0 + assert summary["max_turns"] == 4 + assert summary["done"] is False + + end = client.delete(f"/interactive/sessions/{session_id}") + assert end.status_code == 204 + assert client.get(f"/interactive/sessions/{session_id}").status_code == 404 + + +def test_unknown_system_id_returns_400(client: TestClient) -> None: + response = client.post( + "/interactive/sessions", + json={"system_id": "no_such_system"}, + ) + assert response.status_code == 400 + + +def test_unknown_session_id_returns_404() -> None: + """Session-scoped routes return 404 for unknown ids, not 500.""" + app = _build_app_with_stubbed_llm([]) + with TestClient(app) as client: + response = client.post( + "/interactive/sessions/does-not-exist/llm-step", + json={"model": "stub"}, + ) + assert response.status_code == 404 + + +# --- LLM-step endpoint (with stubbed policy) --- + + +def test_llm_step_drives_a_turn_using_injected_policy() -> None: + """The endpoint must call the policy, parse, step, and surface the raw.""" + app = _build_app_with_stubbed_llm( + [json.dumps({"equation": "d2y/dt2 = -9.81", "rationale": "gravity"})] + ) + with TestClient(app) as client: + create = client.post( + "/interactive/sessions", + json={"system_id": "free_fall", "seed": 0, "max_turns": 4}, + ).json() + session_id = create["session_id"] + + response = client.post( + f"/interactive/sessions/{session_id}/llm-step", + json={"model": "stub:1.5b", "temperature": 0.1, "max_tokens": 64}, + ) + + assert response.status_code == 200, response.text + body = response.json() + assert body["model"] == "stub:1.5b" + assert body["action"]["equation"] == "d2y/dt2 = -9.81" + assert body["action"]["rationale"] == "gravity" + assert body["observation"]["turn"] == 1 + assert body["observation"]["reward_breakdown"]["match"] >= 0.9 + assert body["predicted_trajectory"] + assert body["latency_s"] >= 0.0 + assert "d2y/dt2" in body["raw_completion"] + + +def test_llm_step_runs_full_episode_with_three_canned_turns() -> None: + """Multi-turn drive: each call pops the next completion, history grows.""" + completions = [ + json.dumps({"equation": "d2y/dt2 = -9.81", "rationale": "pure gravity"}), + json.dumps({ + "equation": "d2y/dt2 = -9.81 + 0.1 * vy", + "rationale": "linear drag", + }), + json.dumps({ + "equation": "d2y/dt2 = -9.81 + 0.05 * vy**2", + "rationale": "quadratic drag", + }), + ] + app = _build_app_with_stubbed_llm(completions) + with TestClient(app) as client: + session_id = client.post( + "/interactive/sessions", + json={"system_id": "free_fall_drag", "seed": 42, "max_turns": 8}, + ).json()["session_id"] + + bodies = [] + for _ in range(3): + response = client.post( + f"/interactive/sessions/{session_id}/llm-step", + json={"model": "stub"}, + ) + assert response.status_code == 200, response.text + bodies.append(response.json()) + + assert [b["action"]["equation"] for b in bodies] == [ + "d2y/dt2 = -9.81", + "d2y/dt2 = -9.81 + 0.1 * vy", + "d2y/dt2 = -9.81 + 0.05 * vy**2", + ] + assert [b["observation"]["turn"] for b in bodies] == [1, 2, 3] + # History accumulates across turns. + assert len(bodies[-1]["observation"]["history"]) == 3 + + +def test_llm_step_handles_unparseable_completion_as_format_zero() -> None: + """If the model emits junk, the env scores it format=0, no 500.""" + app = _build_app_with_stubbed_llm(["I refuse to answer."]) + with TestClient(app) as client: + session_id = client.post( + "/interactive/sessions", + json={"system_id": "simple_pendulum", "seed": 0, "max_turns": 4}, + ).json()["session_id"] + response = client.post( + f"/interactive/sessions/{session_id}/llm-step", + json={"model": "stub"}, + ) + + assert response.status_code == 200, response.text + body = response.json() + assert body["observation"]["reward_breakdown"]["format"] == 0.0 + assert body["predicted_trajectory"] == [] + assert body["raw_completion"] == "I refuse to answer." + + +def test_llm_step_after_budget_exhaustion_returns_409() -> None: + """Once the env has consumed its budget, llm-step is rejected too.""" + canned = [ + json.dumps({"equation": "d2theta/dt2 = 0"}), + json.dumps({"equation": "d2theta/dt2 = 0"}), + ] + app = _build_app_with_stubbed_llm(canned) + with TestClient(app) as client: + session_id = client.post( + "/interactive/sessions", + json={"system_id": "simple_pendulum", "seed": 1, "max_turns": 2}, + ).json()["session_id"] + for _ in range(2): + assert client.post( + f"/interactive/sessions/{session_id}/llm-step", + json={"model": "stub"}, + ).status_code == 200 + overflow = client.post( + f"/interactive/sessions/{session_id}/llm-step", + json={"model": "stub"}, + ) + + assert overflow.status_code == 409 + + +# --- CORS --- + + +def test_cors_preflight_for_dev_origin(client: TestClient) -> None: + """OPTIONS preflight from the Vite dev server is allowed.""" + response = client.options( + "/interactive/sessions", + headers={ + "Origin": "http://localhost:5173", + "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "content-type", + }, + ) + assert response.status_code in (200, 204), response.text + assert response.headers["access-control-allow-origin"] == "http://localhost:5173" diff --git a/physix-live/tests/test_parser.py b/physix-live/tests/test_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..ea892670f5cbf37919cc3d7dcd81da4a9f7f12f3 --- /dev/null +++ b/physix-live/tests/test_parser.py @@ -0,0 +1,329 @@ +"""Tests for :mod:`physix.verifier.parser`. + +The parser is the contract between LLM output and the simulator. Most +tests here exist because of a real failure mode caught during live +episodes — concretely, the velocity-alias rules and unknown-symbol +hints close grammar gaps that were silently scoring competent agent +outputs as ``r_format=0``. +""" + +from __future__ import annotations + +import pytest +import sympy as sp + +from physix.verifier.parser import ( + GRAMMAR_HINT, + ParseError, + parse_equation, +) + + +def _parse( + text: str, + state_variables: tuple[str, ...] = ("y", "vy"), + parameter_names: frozenset[str] = frozenset(), +): + return parse_equation(text, state_variables, parameter_names) + + +def test_basic_equation_round_trips(): + parsed = _parse("d2y/dt2 = -9.81") + assert len(parsed.equations) == 1 + eq = parsed.equations[0] + assert eq.var == "y" + assert eq.order == 2 + assert sp.simplify(eq.rhs - sp.Float(-9.81)) == 0 + + +def test_dx_dt_alias_substitutes_for_vx_when_velocity_state_exists(): + """``dx/dt`` is a valid synonym for ``vx`` in damped-spring style systems. + + Regression: 7B produced the textbook-correct equation + ``d2x/dt2 = -k/m * x - c/m * dx/dt`` on turn 1 and we silently + rejected it because ``dx`` and ``dt`` were not whitelisted. + """ + parsed = parse_equation( + "d2x/dt2 = -k/m * x - c/m * dx/dt", + state_variables=("x", "vx"), + parameter_names=frozenset({"k", "c", "m"}), + ) + eq = parsed.equations[0] + assert "vx" in {s.name for s in eq.rhs.free_symbols} + assert "dx" not in {s.name for s in eq.rhs.free_symbols} + assert "dt" not in {s.name for s in eq.rhs.free_symbols} + + +def test_bare_dx_alias_substitutes_for_vx(): + """A bare ``dx`` (without ``/dt``) is also accepted as the velocity.""" + parsed = parse_equation( + "d2x/dt2 = -k*x - c*dx", + state_variables=("x", "vx"), + parameter_names=frozenset({"k", "c"}), + ) + eq = parsed.equations[0] + free = {s.name for s in eq.rhs.free_symbols} + assert "vx" in free + assert "dx" not in free + + +def test_dy_dt_alias_substitutes_for_vy(): + """The same alias rule applies to any ````/``v`` pairing.""" + parsed = parse_equation( + "d2y/dt2 = -9.81 - 0.1 * dy/dt", + state_variables=("y", "vy"), + parameter_names=frozenset(), + ) + eq = parsed.equations[0] + free = {s.name for s in eq.rhs.free_symbols} + assert free == {"vy"} + + +def test_alias_does_not_fire_when_velocity_state_is_named_dvar(): + """For systems like damped pendulum where the state itself is ``dtheta``, + we must *not* substitute ``dtheta`` away — it is the canonical state name. + """ + parsed = parse_equation( + "d2theta/dt2 = -9.81 * sin(theta) - b * dtheta", + state_variables=("theta", "dtheta"), + parameter_names=frozenset({"b"}), + ) + eq = parsed.equations[0] + free = {s.name for s in eq.rhs.free_symbols} + assert "dtheta" in free + assert "vtheta" not in free + + +def test_alias_only_replaces_word_boundary_matches(): + """``dx`` substring inside a longer identifier must be left alone. + + Param names like ``mu_dx`` or ``kdx`` should not be silently + rewritten to ``mu_vx``/``kvx``. + """ + parsed = parse_equation( + "d2x/dt2 = -k * x + mu_dx * vx", + state_variables=("x", "vx"), + parameter_names=frozenset({"k", "mu_dx"}), + ) + eq = parsed.equations[0] + free = {s.name for s in eq.rhs.free_symbols} + assert "mu_dx" in free + + +def test_unknown_dx_in_system_without_paired_velocity_includes_hint(): + """Without a ``vx`` state, ``dx`` cannot be aliased and must reject — + but the error should suggest the actual state name ``x``.""" + with pytest.raises(ParseError) as excinfo: + parse_equation( + "dx/dt = -k * dx", + state_variables=("x",), + parameter_names=frozenset({"k"}), + ) + assert "dx" in str(excinfo.value) + assert "no separate velocity name" in str(excinfo.value) + + +def test_unknown_t_emits_autonomy_hint(): + """``t`` is the most common forbidden symbol; the error must explain + why so the model stops re-emitting time-explicit RHSs across turns.""" + with pytest.raises(ParseError) as excinfo: + parse_equation( + "d2theta/dt2 = -k * theta + c * t", + state_variables=("theta", "dtheta"), + parameter_names=frozenset({"k", "c"}), + ) + msg = str(excinfo.value) + assert "'t'" in msg + assert "autonomous" in msg + + +def test_grammar_hint_documents_velocity_convention(): + """The system prompt embeds GRAMMAR_HINT verbatim. Whoever opens + this file looking for *why* dx/dt is now legal will find the + explanation; whoever weakens the convention by accident will + trip this test. + """ + assert "vx" in GRAMMAR_HINT + assert "dx/dt" in GRAMMAR_HINT + assert "autonomous" in GRAMMAR_HINT + + +def test_multiple_equations_split_on_semicolons_keep_alias_behaviour(): + """The alias rule must apply per-equation when payloads are stacked.""" + parsed = parse_equation( + "dx/dt = vx; d2x/dt2 = -k * x - c * dx/dt", + state_variables=("x", "vx"), + parameter_names=frozenset({"k", "c"}), + ) + assert len(parsed.equations) == 2 + second_rhs = parsed.equations[1].rhs + free = {s.name for s in second_rhs.free_symbols} + assert "vx" in free + assert "dx" not in free + + +def test_dotted_attribute_access_is_rejected_with_clear_error(): + """Regression test for the GRPO crash on completion:: + + d2theta/dt2 = ... * np.sqrt(L**2 - theta**2) / L + + Pre-v2 the parser used ``sympy.sympify`` which turned ``np`` into + ``Symbol('np')`` and then evaluated ``.sqrt(...)`` on it during + ``eval``, raising ``AttributeError: 'Symbol' object has no + attribute 'sqrt'`` *inside* sympy and tearing down the entire RL + step. v2 parses with ``ast.parse`` and a whitelist visitor that + rejects ``ast.Attribute`` (and call-with-attribute func) + structurally — there is no longer an "eval" stage that can crash. + """ + with pytest.raises(ParseError) as excinfo: + parse_equation( + "d2theta/dt2 = -theta + np.sqrt(L**2 - theta**2) / L", + state_variables=("theta", "dtheta"), + parameter_names=frozenset({"L"}), + ) + msg = str(excinfo.value) + assert "Attribute access is not allowed" in msg + # Hint always nudges toward the bare-function form. + assert "sqrt(x)" in msg or "sqrt(" in msg + + +@pytest.mark.parametrize( + "rhs", + [ + "math.sin(theta)", + "numpy.cos(theta) + 1", + "np.exp(-theta**2)", + "scipy.special.expit(theta)", + "theta.diff()", + ], +) +def test_dotted_attribute_access_variants_all_rejected(rhs): + """Defence in depth: every common ``library.fn`` shape — both the + 'attribute as function' (``np.sqrt(x)``) and 'attribute as value' + (``theta.something``) shapes — must reject with the same + user-facing wording.""" + with pytest.raises(ParseError) as excinfo: + parse_equation( + f"d2theta/dt2 = {rhs}", + state_variables=("theta", "dtheta"), + parameter_names=frozenset(), + ) + assert "Attribute access is not allowed" in str(excinfo.value) + + +def test_decimal_literals_are_not_misread_as_attribute_access(): + """Numbers like ``1.05`` must parse as constants — they were a real + coefficient in the failing pendulum equation and ``ast.parse`` + correctly tokenises them as ``ast.Constant(1.05)``, not as + Attribute access. + """ + parsed = parse_equation( + "d2theta/dt2 = -1.05 * theta", + state_variables=("theta", "dtheta"), + parameter_names=frozenset(), + ) + assert len(parsed.equations) == 1 + + +def test_keyword_arguments_in_call_are_rejected_with_specific_hint(): + """Pre-v2, ``sin(theta=0.1)`` reached sympy's eval and raised + ``TypeError`` from inside ``parse_expr``. v2's call validator + catches it at the AST level and gives the model a one-line fix. + """ + with pytest.raises(ParseError, match="Keyword arguments"): + parse_equation( + "d2y/dt2 = sin(theta=0.1)", + state_variables=("y", "vy"), + parameter_names=frozenset(), + ) + + +@pytest.mark.parametrize( + "rhs, expected_keyword", + [ + ("vy[0]", "Array indexing"), + ("y if vy > 0 else -y", "Conditional"), + ("lambda x: x", "Lambda"), + ("y == vy", "Comparisons"), + ("y and vy", "Boolean"), + ("(y, vy)", "Collection"), + # Lambda nested in a call hits the call-with-non-Name-func branch, + # not the bare Lambda branch — keep coverage for that path too. + ("(lambda x: x)(y)", "computed-name call"), + ], +) +def test_disallowed_constructs_each_have_targeted_error(rhs, expected_keyword): + """The whitelist visitor must reject each non-arithmetic shape with + a hint that names the construct — the error string is what the + LLM sees on the next turn, so vague messages waste turns. This + locks in coverage so adding a new shape requires adding a test + *and* a branch. + """ + with pytest.raises(ParseError) as excinfo: + parse_equation( + f"d2y/dt2 = {rhs}", + state_variables=("y", "vy"), + parameter_names=frozenset(), + ) + assert expected_keyword in str(excinfo.value) + + +def test_caret_is_accepted_as_power_synonym(): + """Physics notation universally writes ``x^2`` for the square. v2 + rewrites ``^`` → ``**`` before AST parse so the agent doesn't have + to remember Python's XOR/power split. (Pre-v2 the grammar hint + actively *disallowed* ``^`` — the model frequently emitted it + anyway and got format=0 for purely cosmetic reasons.) + """ + parsed = parse_equation( + "d2y/dt2 = -k * y^2", + state_variables=("y", "vy"), + parameter_names=frozenset({"k"}), + ) + eq = parsed.equations[0] + # k * y**2 = k * y * y → operator count of 2 (Mul + Pow + Pow's UnaryMinus + # outer Mul). What we really care about: the rhs equals the explicit form. + expected = parse_equation( + "d2y/dt2 = -k * y**2", + state_variables=("y", "vy"), + parameter_names=frozenset({"k"}), + ).equations[0] + assert sp.simplify(eq.rhs - expected.rhs) == 0 + + +def test_only_parse_error_ever_escapes_the_parser(): + """Contract test: whatever the agent writes, the *only* exception + type that ever leaves this module is :class:`ParseError`. The + scorer relies on this to convert grammar failures into + ``r_format = 0`` instead of crashing the entire GRPO group (which + is what zeroed loss + zeroed reward in the v1 training run). + + We sweep a grab-bag of historically problematic shapes and + confirm every one becomes ``ParseError``, never bare + ``AttributeError`` / ``TypeError`` / ``SyntaxError``. + """ + pathological = [ + "np.sqrt(y)", + "sin(theta=0.1)", + "(lambda x: x)(y)", + "y if vy else -y", + "y == vy", + "y[0]", + "y; import os", # legal Python, illegal here — first arm parses, second is rejected by split-then-validate + "1.05.foo", # decimal followed by attribute + "y ** vy ** y ** vy ** y", # legal but deep; just confirms no crash + ] + for raw in pathological: + try: + parse_equation( + f"d2y/dt2 = {raw}", + state_variables=("y", "vy"), + parameter_names=frozenset(), + ) + except ParseError: + continue # expected for most + except BaseException as exc: # noqa: BLE001 — that's the whole point + raise AssertionError( + f"Non-ParseError escaped parser for input {raw!r}: " + f"{type(exc).__name__}: {exc}" + ) from exc diff --git a/physix-live/tests/test_prompt.py b/physix-live/tests/test_prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..5329fc772e2b81d82414b99f322a77c83f6d4295 --- /dev/null +++ b/physix-live/tests/test_prompt.py @@ -0,0 +1,300 @@ +"""Unit tests for :mod:`physix.training.prompt`.""" + +from __future__ import annotations + +from physix.models import PhysiXObservation +from physix.training.prompt import ( + SYSTEM_MESSAGE, + build_prompt, + parse_completion, + render_observation_for_prompt, +) + + +def _sample_observation() -> PhysiXObservation: + return PhysiXObservation( + done=False, + reward=None, + trajectory=[ + {"t": 0.0, "y": 50.0, "vy": 0.0}, + {"t": 0.5, "y": 48.7, "vy": -4.9}, + {"t": 1.0, "y": 45.1, "vy": -9.7}, + ], + state_variables=["y", "vy"], + hint="Object dropped from 50 m, mass 2 kg.", + history=[ + { + "turn": 1, + "equation": "d2y/dt2 = -9.81", + "params": {}, + "reward_total": 0.42, + "reward_components": {"match": 0.42, "progress": 0.0, "simplicity": 0.95, "format": 1.0}, + "mismatch_summary": "predicted y diverges past t=2.0s.", + } + ], + mismatch_summary="predicted y diverges past t=2.0s.", + turn=1, + turn_remaining=7, + system_id="free_fall_drag", + stats={"y_min": 0.0, "y_max": 50.0, "duration": 6.0}, + reward_breakdown={"match": 0.42, "total": 0.40}, + ) + + +# --------------------------------------------------------------------------- +# render_observation_for_prompt +# --------------------------------------------------------------------------- + + +def test_render_includes_metadata_block() -> None: + text = render_observation_for_prompt(_sample_observation()) + + assert "SYSTEM_ID: free_fall_drag" in text + assert "STATE_VARIABLES: y, vy" in text + assert "HINT: Object dropped from 50 m" in text + assert "STATS:" in text + + +def test_render_includes_trajectory_samples() -> None: + text = render_observation_for_prompt(_sample_observation()) + assert "TRAJECTORY" in text + assert "y=50" in text or "y=50.000" in text + assert "vy=" in text + + +def test_render_includes_history_when_present() -> None: + text = render_observation_for_prompt(_sample_observation()) + assert "HISTORY" in text + assert "turn=1" in text + assert "d2y/dt2 = -9.81" in text + + +def test_history_uses_equation_field_name_not_shorthand() -> None: + """Regression: HISTORY originally used ``eqn=`` as a display + shorthand, which mid-strength chat models then mimicked when + emitting their own JSON (``{"eqn": "..."}``). The parser only reads + ``equation``, so every post-first turn silently scored + ``r_format=0`` even when the model's actual equation was perfect. + The prompt must use the same field name the parser expects.""" + text = render_observation_for_prompt(_sample_observation()) + assert "equation=`d2y/dt2 = -9.81`" in text + assert "eqn=" not in text + + +def test_history_block_surfaces_dense_reward_components() -> None: + """The model needs to see *which* reward component scored what so it + can attribute its own progress turn-over-turn — e.g. push on grammar + when ``format=0``, or try a structurally different equation when + ``match`` plateaus while ``progress=0``. Showing only ``reward=`` (the + weighted total) hides that signal. + """ + obs = _sample_observation() + obs.history = [ + { + "turn": 1, + "equation": "d2y/dt2 = -9.81", + "params": {}, + "reward_total": 0.42, + "reward_components": { + "match": 0.42, + "progress": 0.0, + "simplicity": 0.95, + "format": 1.0, + }, + "mismatch_summary": "predicted y diverges past t=2.0s.", + } + ] + text = render_observation_for_prompt(obs) + + assert "match=0.42" in text + assert "progress=0.00" in text + assert "simplicity=0.95" in text + assert "format=1.00" in text + + +def test_history_block_tolerates_missing_reward_components() -> None: + """Older history rows or partial breakdowns shouldn't crash render — + missing components default to 0.00 so the column layout stays + stable and the model can still parse the block in-context.""" + obs = _sample_observation() + obs.history = [ + { + "turn": 1, + "equation": "d2y/dt2 = -9.81", + "params": {}, + "reward_total": 0.4, + "mismatch_summary": "", + } + ] + text = render_observation_for_prompt(obs) + + for name in ("match", "progress", "simplicity", "format"): + assert f"{name}=0.00" in text + + +def test_system_message_locks_in_canonical_field_name() -> None: + """The system prompt must explicitly forbid synonyms so the model + doesn't drift to ``eqn``/``ode``/``formula`` on later turns.""" + assert '"equation"' in SYSTEM_MESSAGE + assert "never" in SYSTEM_MESSAGE.lower() + + +def test_render_omits_history_block_when_empty() -> None: + obs = _sample_observation() + obs.history = [] + text = render_observation_for_prompt(obs) + assert "HISTORY" not in text + + +# --------------------------------------------------------------------------- +# build_prompt +# --------------------------------------------------------------------------- + + +def test_build_prompt_returns_chat_pair() -> None: + prompt = build_prompt(_sample_observation()) + + assert len(prompt) == 2 + assert prompt[0] == {"role": "system", "content": SYSTEM_MESSAGE} + assert prompt[1]["role"] == "user" + assert "TRAJECTORY" in prompt[1]["content"] + + +# --------------------------------------------------------------------------- +# parse_completion +# --------------------------------------------------------------------------- + + +def test_parse_completion_extracts_clean_json() -> None: + completion = '{"equation": "d2y/dt2 = -9.81", "params": {"g": 9.81}, "rationale": "free fall"}' + action = parse_completion(completion) + + assert action.equation == "d2y/dt2 = -9.81" + assert action.params == {"g": 9.81} + assert action.rationale == "free fall" + + +def test_parse_completion_handles_code_fences() -> None: + completion = ''' + Here is my hypothesis: + ```json + { + "equation": "d2y/dt2 = -g + k * vy**2", + "params": {"g": 9.81, "k": 0.05}, + "rationale": "added drag" + } + ``` + ''' + action = parse_completion(completion) + + assert action.equation == "d2y/dt2 = -g + k * vy**2" + assert action.params == {"g": 9.81, "k": 0.05} + + +def test_parse_completion_with_no_json_yields_empty_equation() -> None: + """When the completion contains no extractable JSON object, the action + must have an *empty* equation (so the verifier reports a clean + ``Empty equation payload`` error and the env scores ``r_format=0``). + + The raw text is preserved in ``rationale`` so logs/UI can still show + what the model said, but it is never fed to the equation parser as + if it were an equation. + """ + completion = "I think the equation is d2y/dt2 = -g but I'm not sure." + action = parse_completion(completion) + + assert action.equation == "" + assert action.params == {} + assert action.rationale == completion.strip() + + +def test_parse_completion_coerces_string_params() -> None: + completion = '{"equation": "d2y/dt2 = -g", "params": {"g": "9.81", "bad": "not_a_number"}}' + action = parse_completion(completion) + + assert action.params == {"g": 9.81} # bad value silently dropped + + +def test_parse_completion_handles_latex_braces_inside_json_string() -> None: + """Regression: a regex-based brace matcher mis-balances when the JSON + *string* value contains literal ``{`` / ``}`` (e.g. LaTeX ``\\frac{...}``). + The JSON-aware extractor (``json.JSONDecoder.raw_decode``) handles it + correctly. The equation field is preserved verbatim — rewriting it + upstream would silently corrupt the agent's output and is the env's + job to score, not ours.""" + completion = ( + '```json\n' + '{ "equation": "\\\\frac{d vy}{dt} = -9.81", ' + '"params": { "g": 9.81 }, ' + '"rationale": "free fall" }\n' + '```' + ) + action = parse_completion(completion) + + assert action.equation == "\\frac{d vy}{dt} = -9.81" + assert action.params == {"g": 9.81} + assert action.rationale == "free fall" + + +def test_parse_completion_picks_first_object_when_text_has_multiple() -> None: + completion = ( + "Some thoughts here.\n" + '{"equation": "dy/dt = vy", "params": {}}\n' + "And then another:\n" + '{"equation": "dvy/dt = -g", "params": {"g": 9.81}}' + ) + action = parse_completion(completion) + + assert action.equation == "dy/dt = vy" + + +def test_parse_completion_accepts_eqn_synonym() -> None: + """Regression: qwen2.5:7b emits ``{"eqn": "..."}`` after the first + turn (mimicking the historical HISTORY block shorthand). The parser + must accept this rather than silently scoring r_format=0.""" + completion = '{"eqn": "d2y/dt2 = -9.81", "rationale": "free fall"}' + action = parse_completion(completion) + + assert action.equation == "d2y/dt2 = -9.81" + assert action.rationale == "free fall" + + +def test_parse_completion_accepts_other_equation_synonyms() -> None: + for key in ("ode", "formula", "expression", "expr"): + completion = '{"%s": "dy/dt = vy"}' % key + action = parse_completion(completion) + assert action.equation == "dy/dt = vy", f"failed for key={key!r}" + + +def test_parse_completion_accepts_capitalised_keys() -> None: + """Some models emit ``"Equation"`` / ``"EQN"``; we lowercase keys + once before lookup so the alias table stays simple.""" + completion = '{"Equation": "dy/dt = vy", "Rationale": "kinematic"}' + action = parse_completion(completion) + + assert action.equation == "dy/dt = vy" + assert action.rationale == "kinematic" + + +def test_parse_completion_accepts_parameters_synonym() -> None: + completion = '{"equation": "d2y/dt2 = -g", "parameters": {"g": 9.81}}' + action = parse_completion(completion) + + assert action.params == {"g": 9.81} + + +def test_parse_completion_canonical_key_wins_over_synonym() -> None: + """If both ``equation`` and a synonym are present, ``equation`` + wins. This is just hygiene — we don't want the synonym fallback to + silently override a model that *did* emit the canonical key.""" + completion = '{"equation": "dy/dt = vy", "eqn": "d2y/dt2 = -9.81"}' + action = parse_completion(completion) + + assert action.equation == "dy/dt = vy" + + +def test_parse_completion_accepts_reasoning_synonym() -> None: + completion = '{"equation": "dy/dt = vy", "reasoning": "kinematic"}' + action = parse_completion(completion) + + assert action.rationale == "kinematic" diff --git a/physix-live/tests/test_registry.py b/physix-live/tests/test_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..8ecf701d287b79bc6d1e5eb42439ea7ce022aefd --- /dev/null +++ b/physix-live/tests/test_registry.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +from physix.systems.registry import ( + SUPPORTED_SYSTEMS, + SYSTEM_REGISTRY, + get_system, + list_supported_systems, +) + + +def test_supported_systems_is_non_empty() -> None: + assert len(SUPPORTED_SYSTEMS) > 0 + + +def test_supported_systems_only_references_registered_systems() -> None: + for system_id in SUPPORTED_SYSTEMS: + assert system_id in SYSTEM_REGISTRY + + +def test_list_supported_systems_preserves_declared_order() -> None: + assert list_supported_systems() == list(SUPPORTED_SYSTEMS) + + +def test_every_supported_system_instantiates_cleanly() -> None: + for system_id in SUPPORTED_SYSTEMS: + system = get_system(system_id) + assert system.system_id == system_id + assert system.state_variables, f"{system_id} declares no state variables" diff --git a/physix-live/tests/test_scorer.py b/physix-live/tests/test_scorer.py new file mode 100644 index 0000000000000000000000000000000000000000..1be1ce7aca935e9ec8933047e47ca73496a26611 --- /dev/null +++ b/physix-live/tests/test_scorer.py @@ -0,0 +1,68 @@ +"""Unit tests for :mod:`physix.training.scorer`.""" + +from __future__ import annotations + +import numpy as np +import pytest + +from physix.systems import get_system +from physix.training.scorer import Scorer, SystemContext + + +def _build_context_for(system_id: str, seed: int = 5) -> SystemContext: + system = get_system(system_id) + rng = np.random.default_rng(seed) + traj = system.simulate(rng) + return SystemContext( + system_id=system_id, + state_variables=system.state_variables, + parameters=system.parameters, + initial_conditions=system.initial_conditions, + timestamps=traj.timestamps, + observed=traj.states, + previous_total=0.0, + ) + + +def test_scorer_returns_high_match_for_ground_truth() -> None: + scorer = Scorer() + ctx = _build_context_for("free_fall") + breakdown = scorer.score('{"equation": "d2y/dt2 = -9.81"}', ctx) + + assert breakdown.format == 1.0 + assert breakdown.match >= 0.9 + + +def test_scorer_returns_zero_format_on_garbage() -> None: + scorer = Scorer() + ctx = _build_context_for("free_fall") + breakdown = scorer.score("this is not an equation", ctx) + + assert breakdown.format == 0.0 + assert breakdown.match == 0.0 + + +def test_scorer_caches_by_key() -> None: + scorer = Scorer() + ctx = _build_context_for("simple_pendulum") + completion = '{"equation": "d2theta/dt2 = -9.81 * sin(theta)"}' + + first = scorer.score(completion, ctx, cache_key=42) + second = scorer.score(completion, ctx, cache_key=42) + assert first is second + + +def test_scorer_progress_shrinks_when_previous_total_is_high() -> None: + scorer = Scorer() + ctx_low = _build_context_for("free_fall_drag", seed=3) + completion = '{"equation": "d2y/dt2 = -9.81 + 0.05 * vy**2"}' + + no_prev = scorer.score(completion, ctx_low) + if no_prev.match < 0.5: + pytest.skip("rng selection produced an awkward instance") + + ctx_high = ctx_low.model_copy(update={"previous_total": no_prev.match * 0.9}) + with_prev = scorer.score(completion, ctx_high) + + # progress = max(0, match - prev_total). Higher prev_total => smaller progress. + assert with_prev.progress <= no_prev.progress + 1e-9 diff --git a/physix-live/tests/test_sft_dataset.py b/physix-live/tests/test_sft_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..34c3c46abfc17c5f78b00ec72b3d5e63b5bd1156 --- /dev/null +++ b/physix-live/tests/test_sft_dataset.py @@ -0,0 +1,60 @@ +"""Tests for the SFT dataset builder. + +Why a dedicated file: :func:`physix.training.sft.build_sft_dataset` is +imported through a module that *also* imports heavy ML packages +(``unsloth``, ``trl``, ``wandb``) lazily inside :func:`train_sft`. Keeping +the dataset-only tests here documents the boundary — these tests +exercise the pure-Python data path and must not require GPU deps. + +The whole point of changes captured by these tests: SFT must warm the +model on *the same systems GRPO will refine*. Any divergence between +SFT and GRPO curricula wastes the warm-start budget on shapes that +never see a reinforcement signal. +""" + +from __future__ import annotations + +import json + +import pytest + +from physix.systems import SUPPORTED_SYSTEMS +from physix.training.sft import build_sft_dataset + + +def test_build_sft_dataset_default_curriculum_size() -> None: + ds = build_sft_dataset(instances_per_system=1) + assert len(ds) == len(SUPPORTED_SYSTEMS) + + +def test_build_sft_dataset_default_scales_with_instances_per_system() -> None: + instances = 4 + ds = build_sft_dataset(instances_per_system=instances) + assert len(ds) == len(SUPPORTED_SYSTEMS) * instances + + +def test_build_sft_dataset_completions_are_valid_json_action() -> None: + ds = build_sft_dataset(instances_per_system=1) + for row in ds: + action = json.loads(row["completion"]) + assert "equation" in action + assert "params" in action + assert "rationale" in action + + +def test_build_sft_dataset_explicit_system_ids_override_default() -> None: + ds = build_sft_dataset( + system_ids=("free_fall",), + instances_per_system=3, + ) + assert len(ds) == 3 + + +def test_build_sft_dataset_rejects_unknown_system_ids() -> None: + with pytest.raises(ValueError, match="Unknown system_ids"): + build_sft_dataset(system_ids=("definitely_not_a_system",)) + + +def test_build_sft_dataset_rejects_empty_system_ids() -> None: + with pytest.raises(ValueError, match="non-empty"): + build_sft_dataset(system_ids=())