{ "cells": [ { "cell_type": "markdown", "id": "46f1528c", "metadata": {}, "source": [ "# JAX Identity Example\n", "This example shows how to use volara with a JAX/Flax model.\n", "We create a trivial identity model, run blockwise prediction on synthetic data,\n", "and verify the output matches the input." ] }, { "cell_type": "code", "execution_count": null, "id": "998c4c81", "metadata": {}, "outputs": [], "source": [ "import shutil\n", "from pathlib import Path\n", "\n", "import cloudpickle\n", "import jax\n", "import jax.numpy as jnp\n", "import numpy as np\n", "import orbax.checkpoint as ocp\n", "import zarr\n", "from flax import linen as nn\n", "from funlib.geometry import Coordinate\n", "from volara.datasets import Raw\n", "\n", "from volara_ml.blockwise import Predict\n", "from volara_ml.models import JaxModel" ] }, { "cell_type": "markdown", "id": "a6389309", "metadata": {}, "source": [ "## 1. Create synthetic input data" ] }, { "cell_type": "code", "execution_count": null, "id": "4905ef41", "metadata": {}, "outputs": [], "source": [ "work_dir = Path(\"_jax_identity_workdir\")\n", "work_dir.mkdir(parents=True, exist_ok=True)\n", "\n", "rng = np.random.default_rng(42)\n", "data = rng.integers(0, 256, size=(64, 64), dtype=np.uint8)\n", "\n", "store = zarr.open(str(work_dir / \"data.zarr\"), mode=\"w\")\n", "raw_ds = store.create_array(\"raw\", shape=data.shape, dtype=data.dtype)\n", "raw_ds[:] = data\n", "raw_ds.attrs[\"voxel_size\"] = (1, 1)\n", "raw_ds.attrs[\"axis_names\"] = [\"y\", \"x\"]\n", "raw_ds.attrs[\"unit\"] = [\"px\", \"px\"]" ] }, { "cell_type": "markdown", "id": "8574835c", "metadata": { "lines_to_next_cell": 2 }, "source": [ "## 2. Define and save a trivial Flax identity model" ] }, { "cell_type": "code", "execution_count": null, "id": "2769f7c1", "metadata": {}, "outputs": [], "source": [ "class Identity(nn.Module):\n", " @nn.compact\n", " def __call__(self, x):\n", " # Flax Conv expects channels-last (N, H, W, C), but input is (N, C, H, W).\n", " x = jnp.transpose(x, (0, 2, 3, 1))\n", " x = nn.Conv(\n", " features=1,\n", " kernel_size=(1, 1),\n", " use_bias=False,\n", " kernel_init=nn.initializers.ones,\n", " )(x)\n", " x = jnp.transpose(x, (0, 3, 1, 2))\n", " return x\n", "\n", "\n", "model = Identity()\n", "\n", "model_path = work_dir / \"model.pkl\"\n", "with open(model_path, \"wb\") as f:\n", " cloudpickle.dump(model, f)\n", "\n", "rng = jax.random.PRNGKey(0)\n", "dummy = jnp.ones((1, 1, 64, 64))\n", "params = model.init(rng, dummy)\n", "\n", "ckpt_path = work_dir / \"ckpt\"\n", "checkpointer = ocp.StandardCheckpointer()\n", "checkpointer.save(str(ckpt_path.resolve()), params)\n", "checkpointer.close()" ] }, { "cell_type": "markdown", "id": "4bff42c2", "metadata": {}, "source": [ "## 3. Configure JaxModel and Predict" ] }, { "cell_type": "code", "execution_count": null, "id": "6cf96e2b", "metadata": {}, "outputs": [], "source": [ "jax_model = JaxModel(\n", " model_path=model_path,\n", " params_path=ckpt_path.resolve(),\n", " in_channels=1,\n", " out_channels=1,\n", " min_input_shape=Coordinate(64, 64),\n", " min_output_shape=Coordinate(64, 64),\n", " min_step_shape=Coordinate(1, 1),\n", " out_range=(0, 1),\n", " pred_size_growth=Coordinate(0, 0),\n", ")\n", "\n", "raw_in = Raw(\n", " store=work_dir / \"data.zarr/raw\",\n", " scale_shift=(1 / 255, 0),\n", ")\n", "raw_out = Raw(store=work_dir / \"data.zarr/output\")\n", "\n", "predict_task = Predict(\n", " checkpoint=jax_model,\n", " in_data=raw_in,\n", " out_data=[raw_out],\n", ")" ] }, { "cell_type": "markdown", "id": "6e7a2a0d", "metadata": {}, "source": [ "## 4. Run blockwise prediction" ] }, { "cell_type": "code", "execution_count": null, "id": "ad0ba96d", "metadata": {}, "outputs": [], "source": [ "predict_task.drop()\n", "predict_task.run_blockwise(multiprocessing=False)" ] }, { "cell_type": "markdown", "id": "cef78694", "metadata": {}, "source": [ "## 5. Verify output matches input" ] }, { "cell_type": "code", "execution_count": null, "id": "5982c3b3", "metadata": {}, "outputs": [], "source": [ "input_data = zarr.open(str(work_dir / \"data.zarr/raw\"), mode=\"r\")[:]\n", "output_data = zarr.open(str(work_dir / \"data.zarr/output\"), mode=\"r\")[:]\n", "\n", "# The identity model receives float data in [0, 1] (via scale_shift) and outputs\n", "# it unchanged. The output is then quantized back to uint8. The output has a\n", "# channel dimension prepended (1, H, W), so we squeeze it for comparison.\n", "output_data = output_data.squeeze(axis=0)\n", "assert output_data.shape == input_data.shape, (\n", " f\"Shape mismatch: input {input_data.shape} vs output {output_data.shape}\"\n", ")\n", "assert np.allclose(output_data, input_data, atol=1), (\n", " f\"Output does not match input. Max diff: {np.abs(output_data.astype(int) - input_data.astype(int)).max()}\"\n", ")\n", "\n", "print(\"Success! Output matches input (identity model verified).\")\n", "\n", "# Clean up\n", "shutil.rmtree(work_dir)\n", "shutil.rmtree(\"volara_logs\", ignore_errors=True)" ] } ], "metadata": { "jupytext": { "cell_metadata_filter": "-all", "main_language": "python", "notebook_metadata_filter": "-all" } }, "nbformat": 4, "nbformat_minor": 5 }