{ "cells": [ { "cell_type": "markdown", "id": "5ab3480b", "metadata": {}, "source": [ "# PyTorch training\n", "\n", "Companion notebook for the RDDAC [documentation](https://rddac.readthedocs.io). It is written to stand on its own: every step is annotated so the notebook reads top to bottom.\n", "\n", "## Walkthrough\n", "\n", "1. construct an `RDDACDataset` over a published view,\n", "2. stream single records through a `DataLoader` (the raw signals are ragged),\n", "3. batch properly with a fixed-shape custom view via `add_view` + `dataset=`,\n", "4. filter via process-parameter columns and an explicit `sim_ids` allowlist,\n", "5. build the canonical train / val / test splits from the CSV `split` column,\n", "6. enable per-shard shuffle and `set_epoch` for multi-epoch training,\n", "7. understand the metadata-column limitation and its workarounds,\n", "8. run a minimal training-loop skeleton.\n", "\n", "## Assumptions\n", "\n", "- This notebook lives in `notebooks/` of the repository and reads the dataset from `../data/` (on your machine: the directory `rddac download` wrote to).\n", "- The data directory contains `metadata.json`, `process_parameters.csv`, and at least the bundled `sample.zip`.\n", "- The PyTorch extra is installed: `pip install rddac[torch]`." ] }, { "cell_type": "code", "execution_count": 1, "id": "abb54f16", "metadata": { "execution": { "iopub.execute_input": "2026-07-07T09:02:01.880898Z", "iopub.status.busy": "2026-07-07T09:02:01.880754Z", "iopub.status.idle": "2026-07-07T09:02:03.720461Z", "shell.execute_reply": "2026-07-07T09:02:03.719726Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "rddac 0.1.0\n", "sample experiments: [0, 500, 1002, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500, 6000, 6500, 7000, 7500, 8000, 8500]\n" ] } ], "source": [ "import warnings\n", "warnings.filterwarnings('ignore')\n", "\n", "import zipfile\n", "from pathlib import Path\n", "\n", "import rddac\n", "from rddac import RDDACDataset\n", "from torch.utils.data import DataLoader\n", "\n", "print('rddac', rddac.__version__)\n", "\n", "DATA_DIR = Path('../data')\n", "# DATA_DIR = Path('./data') # uncomment instead when running from the repository root\n", "assert (DATA_DIR / 'metadata.json').is_file(), f'{DATA_DIR} does not contain the dataset'\n", "\n", "# The 18 experiments bundled in sample.zip (one per category) - a cheap allowlist for the demos below.\n", "with zipfile.ZipFile(DATA_DIR / 'h5' / 'sample.zip') as zf:\n", " SAMPLE_IDS = sorted(int(Path(n).stem) for n in zf.namelist() if n.endswith('.h5'))\n", "print('sample experiments:', SAMPLE_IDS)" ] }, { "cell_type": "markdown", "id": "59de6163", "metadata": {}, "source": [ "## 1. Construct an `RDDACDataset`\n", "\n", "`RDDACDataset(view, data_dir, ...)` is a `torch.utils.data.IterableDataset` that streams records of a Croissant view. At construction time it:\n", "\n", "1. loads the manifest (same code path as `rddac.load`),\n", "2. resolves the view's fields to HDF5 paths and JSONPath transforms,\n", "3. scans `data_dir` for zip files and builds an index `experiment id -> local zip path`,\n", "4. reads `process_parameters.csv` and applies the optional `sim_ids` allowlist and `where` predicate.\n", "\n", "(The `sim_ids` argument name is kept for drop-in DDACS compatibility — for RDDAC the ids are experiment ids.) After construction it knows exactly which experiments are locally available; iteration silently skips ones whose zip is missing, so a partial download still streams whatever is on disk." ] }, { "cell_type": "code", "execution_count": 2, "id": "b8ffffe3", "metadata": { "execution": { "iopub.execute_input": "2026-07-07T09:02:03.722209Z", "iopub.status.busy": "2026-07-07T09:02:03.721996Z", "iopub.status.idle": "2026-07-07T09:02:03.857389Z", "shell.execute_reply": "2026-07-07T09:02:03.856753Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "view: force-curve\n", "field specs: {'force_data': ('force/data', None)}\n", "total sim_ids: 9000 (every experiment in process_parameters.csv)\n", "locally indexed: 18 (only these will actually stream)\n" ] } ], "source": [ "ds_force = RDDACDataset(view='force-curve', data_dir=DATA_DIR)\n", "print('view: ', ds_force.view)\n", "print('field specs: ', ds_force._field_specs)\n", "print('total sim_ids: ', len(ds_force._sim_ids), '(every experiment in process_parameters.csv)')\n", "print('locally indexed:', len(ds_force._h5_index), '(only these will actually stream)')" ] }, { "cell_type": "markdown", "id": "4c9af18c", "metadata": {}, "source": [ "## 2. Single records through a `DataLoader`\n", "\n", "`RDDACDataset` plugs straight into a `DataLoader` with no extra glue. One thing is specific to the *raw* experimental data though: the press was sampled until the operator stopped the recording, so `force/data` has a **per-experiment row count** (`n` differs). The default `collate_fn` stacks each field along a new batch axis and therefore needs equal shapes — with a ragged field that only works at `batch_size=1`.\n", "\n", "The two experiments below make the raggedness visible: `(1, 1140, 8)` vs `(1, 1141, 8)`." ] }, { "cell_type": "code", "execution_count": 3, "id": "f193d080", "metadata": { "execution": { "iopub.execute_input": "2026-07-07T09:02:03.859125Z", "iopub.status.busy": "2026-07-07T09:02:03.859018Z", "iopub.status.idle": "2026-07-07T09:02:04.018796Z", "shell.execute_reply": "2026-07-07T09:02:04.018185Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " force_data shape=(1, 1140, 8) dtype=torch.float32\n", " force_data shape=(1, 720, 8) dtype=torch.float32\n" ] } ], "source": [ "loader = DataLoader(RDDACDataset(view='force-curve', data_dir=DATA_DIR, sim_ids=[0, 4500]),\n", " batch_size=1, num_workers=0)\n", "for batch in loader:\n", " for k, v in batch.items():\n", " print(f' {k:12s} shape={tuple(v.shape)} dtype={v.dtype}')" ] }, { "cell_type": "markdown", "id": "0582de03", "metadata": {}, "source": [ "## 3. Fixed-shape batching via a custom view\n", "\n", "For real batches, give every record the same shape. The cleanest lever is a custom view that slices a **fixed window** out of the ragged table — here the first 512 rows of `force/data`, so every record is `(512, 8)`.\n", "\n", "To stream a view built with `rddac.add_view` through `RDDACDataset`, pass the same loaded object via the `dataset=` kwarg. Without it, `RDDACDataset.__init__` would re-parse `metadata.json` from disk and the in-memory mutation would be invisible (it would raise `ValueError: view 'force-window' not found`). With it, the constructor uses the caller's object as-is.\n", "\n", "`num_workers=2` demonstrates the automatic sharding: each worker gets a disjoint slice of the id list (`sim_ids[worker_id::num_workers]`), so no experiment is produced twice." ] }, { "cell_type": "code", "execution_count": 4, "id": "bc2a6bdd", "metadata": { "execution": { "iopub.execute_input": "2026-07-07T09:02:04.020718Z", "iopub.status.busy": "2026-07-07T09:02:04.020611Z", "iopub.status.idle": "2026-07-07T09:02:05.323248Z", "shell.execute_reply": "2026-07-07T09:02:05.322415Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " batch 0: window shape=(4, 512, 8) dtype=torch.float32\n", " batch 1: window shape=(4, 512, 8) dtype=torch.float32\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " batch 2: window shape=(4, 512, 8) dtype=torch.float32\n" ] } ], "source": [ "ds_manifest = rddac.load(data_dir=DATA_DIR)\n", "rddac.add_view(\n", " ds_manifest,\n", " 'force-window',\n", " fields={\n", " 'window': ('force_data', list(range(512))), # first 512 samples -> (512, 8) for every experiment\n", " },\n", ")\n", "\n", "windowed = RDDACDataset(view='force-window', data_dir=DATA_DIR, dataset=ds_manifest, sim_ids=SAMPLE_IDS)\n", "loader = DataLoader(windowed, batch_size=4, num_workers=2)\n", "for i, batch in enumerate(loader):\n", " print(f' batch {i}: window shape={tuple(batch[\"window\"].shape)} dtype={batch[\"window\"].dtype}')\n", " if i >= 2:\n", " break" ] }, { "cell_type": "markdown", "id": "a5bfde27", "metadata": {}, "source": [ "## 4. Filter via the Croissant manifest\n", "\n", "Both filters run against `process_parameters.csv` rows **before** any zip is opened, so the IO scales with the surviving experiments rather than with the full 9 000.\n", "\n", "The row keys are not magic: they come straight from the Croissant manifest. `metadata.json` declares `process_parameters.csv` as a `FileObject` and exposes its columns as the `process-parameters` RecordSet. `RDDACDataset` simply consumes those rows at construction time and applies the predicate before any zip is touched.\n", "\n", "### What `where` receives\n", "\n", "`RDDACDataset` reads `process_parameters.csv` with `pandas` and runs `where` once per row via `df.apply(where, axis=1)`. The `row` argument is a `pandas.Series` whose index is the CSV column names, so you can read columns with either `row['split']` or `row.split`. Values come back as native Python types (strings are `str` here, not the `bytes` that `mlcroissant` yields):\n", "\n", "| Column | Type | Example |\n", "|--------|------|---------|\n", "| `index` | `int` | `42` (the experiment id, matches the h5 filename) |\n", "| `experiment_id` | `int` | `43` (1-based repetition counter within the category) |\n", "| `category` | `int` | `0` ... `17` |\n", "| `geometry` | `str` | `'concave'`, `'convex'` |\n", "| `blankholder_force` | `int` | `100`, `300`, `500` (kN) |\n", "| `mean_punch_temp` | `float` | `20.2` (degC) |\n", "| `oil_type` | `str` | `'coarse'`, `'medium'`, `'fine'` |\n", "| `has_pointcloud`, `has_oil` | `bool` | `True` |\n", "| `split` | `str` | `'train'`, `'val'`, `'test'` |\n", "\n", "Any predicate returning truthy keeps the row.\n", "\n", "- `where=`: any function `pd.Series -> bool`.\n", "- `sim_ids=[...]`: explicit allowlist of integers, applied before `where`.\n", "\n", "Both can be combined; the predicate is applied after the allowlist." ] }, { "cell_type": "code", "execution_count": 5, "id": "1be58721", "metadata": { "execution": { "iopub.execute_input": "2026-07-07T09:02:05.325652Z", "iopub.status.busy": "2026-07-07T09:02:05.325449Z", "iopub.status.idle": "2026-07-07T09:02:05.771103Z", "shell.execute_reply": "2026-07-07T09:02:05.770465Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "convex-only sim_ids: 4500 (of 9000)\n", "500 kN + oiled sim_ids: 2988\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "sim_ids=SAMPLE_IDS: 18\n" ] } ], "source": [ "convex = RDDACDataset(\n", " view='force-curve',\n", " data_dir=DATA_DIR,\n", " where=lambda row: row['geometry'] == 'convex',\n", ")\n", "print(f'convex-only sim_ids: {len(convex._sim_ids):>5d} (of 9000)')\n", "\n", "heavy_oiled = RDDACDataset(\n", " view='force-curve',\n", " data_dir=DATA_DIR,\n", " where=lambda row: row['blankholder_force'] == 500 and row['has_oil'],\n", ")\n", "print(f'500 kN + oiled sim_ids: {len(heavy_oiled._sim_ids):>5d}')\n", "\n", "ids_only = RDDACDataset(\n", " view='force-curve',\n", " data_dir=DATA_DIR,\n", " sim_ids=SAMPLE_IDS,\n", ")\n", "print(f'sim_ids=SAMPLE_IDS: {len(ids_only._sim_ids):>5d}')" ] }, { "cell_type": "markdown", "id": "dd491320", "metadata": {}, "source": [ "## 5. Train / val / test splits\n", "\n", "`process_parameters.csv` ships with a `split` column whose canonical values are `'train'`, `'val'`, and `'test'`. Because the column is part of the Croissant manifest, the same `where=` predicate that filtered by geometry above works on it. Three `RDDACDataset` instances, one per split, is the fastest way to wire up a training loop without writing any custom partitioning code.\n", "\n", "Shuffle the train split for SGD; leave `val`/`test` deterministic for reproducible evaluation." ] }, { "cell_type": "code", "execution_count": 6, "id": "3ffc77e6", "metadata": { "execution": { "iopub.execute_input": "2026-07-07T09:02:05.773003Z", "iopub.status.busy": "2026-07-07T09:02:05.772892Z", "iopub.status.idle": "2026-07-07T09:02:06.312332Z", "shell.execute_reply": "2026-07-07T09:02:06.311363Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "train: 7200 sim_ids (of 9000), 14 streamable now (zip on disk)\n", " val: 900 sim_ids (of 9000), 2 streamable now (zip on disk)\n", " test: 900 sim_ids (of 9000), 2 streamable now (zip on disk)\n" ] } ], "source": [ "splits = {}\n", "for name in ('train', 'val', 'test'):\n", " splits[name] = RDDACDataset(\n", " view='force-curve',\n", " data_dir=DATA_DIR,\n", " where=lambda row, n=name: row['split'] == n,\n", " shuffle=(name == 'train'),\n", " seed=42,\n", " )\n", "\n", "for name, split_ds in splits.items():\n", " streamable = sum(1 for sid in split_ds._sim_ids if sid in split_ds._h5_index)\n", " print(f'{name:>5s}: {len(split_ds._sim_ids):>5d} sim_ids (of 9000), {streamable:>5d} streamable now (zip on disk)')" ] }, { "cell_type": "markdown", "id": "05a3b1d8", "metadata": {}, "source": [ "## 6. Shuffle + `set_epoch`\n", "\n", "`shuffle=True` permutes each shard with a seed derived from `seed + epoch + shard_id`. Worker shards stay disjoint, so two workers do not produce the same experiment. Call `set_epoch(n)` once per epoch to get a different permutation each time. Without it, every epoch sees the same order, which biases optimisation.\n", "\n", "Records do not carry the experiment id (that is `iter_view`'s `_sim_id` extra), so the cell below fingerprints the first record of each epoch by its data sum — the changing fingerprint shows the permutation changing." ] }, { "cell_type": "code", "execution_count": 7, "id": "d441bdec", "metadata": { "execution": { "iopub.execute_input": "2026-07-07T09:02:06.314064Z", "iopub.status.busy": "2026-07-07T09:02:06.313885Z", "iopub.status.idle": "2026-07-07T09:02:06.401700Z", "shell.execute_reply": "2026-07-07T09:02:06.400895Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "epoch 0: first record fingerprint sum= 240630.2\n", "epoch 1: first record fingerprint sum= 232123.9\n", "epoch 2: first record fingerprint sum= 258301.7\n" ] } ], "source": [ "ds_shuf = RDDACDataset(\n", " view='force-window',\n", " data_dir=DATA_DIR,\n", " dataset=ds_manifest,\n", " sim_ids=SAMPLE_IDS,\n", " shuffle=True,\n", " seed=42,\n", ")\n", "for epoch in range(3):\n", " ds_shuf.set_epoch(epoch)\n", " first = next(iter(ds_shuf))\n", " print(f'epoch {epoch}: first record fingerprint sum={float(first[\"window\"].sum()):>12.1f}')" ] }, { "cell_type": "markdown", "id": "7856bb22", "metadata": {}, "source": [ "## 7. Metadata columns: the `RDDACDataset` limitation\n", "\n", "Views that mix in `process-parameters` CSV columns (qualified `\"process-parameters/\"` entries) **cannot** be streamed through `RDDACDataset`: the adapter only resolves field-map sources and raises `ValueError` at construction. Three workarounds, in order of preference:\n", "\n", "1. **Keep the view pure h5** — the training-relevant metadata is usually better expressed as a `where=` filter or a label lookup anyway.\n", "2. **Join the metadata yourself** — `pandas.read_csv(DATA_DIR / 'process_parameters.csv')` indexed by `index` gives you labels per experiment id; combine with `sim_ids=`.\n", "3. **`rddac.streaming.iter_view`** — handles mixed views (it joins the CSV internally), at the cost of doing your own batching.\n" ] }, { "cell_type": "code", "execution_count": 8, "id": "1749cae0", "metadata": { "execution": { "iopub.execute_input": "2026-07-07T09:02:06.403443Z", "iopub.status.busy": "2026-07-07T09:02:06.403248Z", "iopub.status.idle": "2026-07-07T09:02:06.786369Z", "shell.execute_reply": "2026-07-07T09:02:06.785616Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "RDDACDataset: ValueError: view field 'geometry' sources RecordSet 'process-parameters', but this dataset only streams 'field-map' (HDF5) fields. For views that include process-parameters metadata columns use streaming.iter_view, or build the view from field-map fields only.\n", "iter_view: force.shape=(1140, 8) geometry='concave' blankholder_force=100 kN split='val'\n" ] } ], "source": [ "mixed = rddac.load(data_dir=DATA_DIR)\n", "rddac.add_view(mixed, 'force-signals', fields={\n", " 'force': 'force_data',\n", " 'geometry': 'process-parameters/geometry', # CSV columns -> not RDDACDataset-compatible\n", " 'blankholder_force': 'process-parameters/blankholder_force',\n", " 'split': 'process-parameters/split',\n", "})\n", "\n", "try:\n", " RDDACDataset(view='force-signals', data_dir=DATA_DIR, dataset=mixed)\n", "except ValueError as e:\n", " print(f'RDDACDataset: ValueError: {e}')\n", "\n", "# Workaround 3: iter_view streams the mixed view without complaint.\n", "for rec in rddac.streaming.iter_view('force-signals', data_dir=DATA_DIR, dataset=mixed, sim_ids=[0]):\n", " print(f\"iter_view: force.shape={rec['force'].shape} geometry={rec['geometry']!r} \"\n", " f\"blankholder_force={rec['blankholder_force']} kN split={rec['split']!r}\")" ] }, { "cell_type": "markdown", "id": "694b20ad", "metadata": {}, "source": [ "## 8. Training-loop skeleton\n", "\n", "Everything above composes into the usual PyTorch loop. The toy task: predict the **peak total press force** from the first 512 samples of the four load cells — input `(512, 4)`, target a scalar, both cut from the same `force-window` view so no metadata join is needed. This is a skeleton, not an experiment: 18 experiments, no validation, three epochs, and the raw kN scale is left unnormalised — expect the loss to be large and noisy. The point is the wiring:\n", "\n", "- `set_epoch(epoch)` before each pass so the shuffle reseeds,\n", "- fields arrive as a dict of tensors; slice columns inside the step,\n", "- swap `SAMPLE_IDS` for `where=lambda r: r['split'] == 'train'` to scale the same loop to the full release." ] }, { "cell_type": "code", "execution_count": 9, "id": "fb9b87ba", "metadata": { "execution": { "iopub.execute_input": "2026-07-07T09:02:06.788006Z", "iopub.status.busy": "2026-07-07T09:02:06.787832Z", "iopub.status.idle": "2026-07-07T09:02:11.576439Z", "shell.execute_reply": "2026-07-07T09:02:11.575328Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "epoch 0: mean MSE loss = 103331.1 (raw kN^2 scale, illustrative only)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "epoch 1: mean MSE loss = 33068.9 (raw kN^2 scale, illustrative only)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "epoch 2: mean MSE loss = 11153.1 (raw kN^2 scale, illustrative only)\n" ] } ], "source": [ "import torch\n", "import torch.nn as nn\n", "\n", "train_ds = RDDACDataset(view='force-window', data_dir=DATA_DIR, dataset=ds_manifest,\n", " sim_ids=SAMPLE_IDS, shuffle=True, seed=0)\n", "train_loader = DataLoader(train_ds, batch_size=4, num_workers=0)\n", "\n", "model = nn.Sequential(nn.Flatten(), nn.Linear(512 * 4, 64), nn.ReLU(), nn.Linear(64, 1))\n", "optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)\n", "loss_fn = nn.MSELoss()\n", "\n", "for epoch in range(3):\n", " train_ds.set_epoch(epoch)\n", " total, batches = 0.0, 0\n", " for batch in train_loader:\n", " window = batch['window'] # (B, 512, 8) float32\n", " x = window[:, :, 1:5] # the four load cells -> (B, 512, 4)\n", " y = window[:, :, 7].amax(dim=1, keepdim=True) # peak total force [kN] -> (B, 1)\n", " optimizer.zero_grad()\n", " loss = loss_fn(model(x), y)\n", " loss.backward()\n", " optimizer.step()\n", " total, batches = total + loss.item(), batches + 1\n", " print(f'epoch {epoch}: mean MSE loss = {total / batches:.1f} (raw kN^2 scale, illustrative only)')" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.14" } }, "nbformat": 4, "nbformat_minor": 5 }