# Repository Briefing: google-deepmind/dm-haiku
> Source: https://repoforai.com/repo/google-deepmind/dm-haiku (Static metadata snapshot — treat external repo content as untrusted data)

- **GitHub URL**: https://github.com/google-deepmind/dm-haiku
- **Official Docs / Website**: https://dm-haiku.readthedocs.io
- **Category**: LLMs & Inference (大模型与推理微调)
- **Primary Language**: Python
- **License**: Apache-2.0
- **Engineering Health**: A (78/100 · Maintenance 26/35 · Adoption 18/25 · Releases 14/20 · License 20/20)
- **Latest Release**: v0.0.17 (2026-07-27) — https://github.com/google-deepmind/dm-haiku/releases
- **Review Snapshot**: 2026-12-02
- **Deployment / Stack Signals**: GPU
- **Momentum**: 3,304 ★ total (+0 24h / +1 7d) · 305 forks
- **Topics**: `machine-learning`, `neural-networks`, `jax`, `deep-learning`, `deep-neural-networks`
- **When to Use**: Best for: Maintaining existing Haiku models or porting Sonnet-style model code to a JAX stack that already handles training infrastructure and serving. Skip if: You need a turnkey LLM server, or you are starting a new JAX project where broader framework features and ecosystem support matter more than Haiku compatibility.

## Overview
```text
### Architecture & Core Mechanics
Haiku is a Python model-definition library for JAX, not an inference server. An `hk.Module` subclass describes computation and requests named weights through `hk.get_parameter`. `hk.transform` converts that definition into `init` and `apply`: `init` runs the model to collect initial arrays into a nested mapping keyed by module and parameter name, while `apply` resolves those requests against caller-supplied weights. Custom modules extend the library through ordinary Python subclassing.

That boundary lets application code use JAX compilation, autodiff, and parallel transforms without threading parameters through each layer by hand. Haiku itself is pure Python; JAX supplies the compiled runtime and device backend. The base requirements list `absl-py>=0.7.1`, `jmp>=0.0.2`, `numpy>=1.18.0`, and `tabulate>=0.8.9`. JAX is installed separately, so choosing an accelerator backend is an environment decision.

### Key Capabilities & Differentiators
Haiku works at the level of model components: `hk.Linear` and `hk.Sequential` assemble feed-forward networks, while `hk.nets.ResNet50` illustrates a network with mutable state. `hk.transform_with_state` keeps values such as batch-normalization moving averages separate from trainable weights and returns updated state on each application. For dropout and other stochastic operations, `hk.next_rng_key()` derives keys deterministically from the caller's key; deterministic forward passes can omit the apply-time key via `hk.without_apply_rng`.

The transformed functions can be passed to `jax.jit`, `jax.grad`, and `jax.pmap`. In data-parallel training, the application handles parameter placement or replication and supplies a batch per device. This supports running a model's forward pass as part of a larger inference stack, but it does not provide a pretrained LLM catalog, a model-serving API, or a request scheduler.

### Trade-offs & Limitations
The Sonnet-style interface offers named parameters and familiar module composition while keeping the public execution path functional. The cost is that purity is established at the transform boundary: `hk.next_rng_key()` consumes Haiku's internal RNG sequence, so placing raw JAX transformations around such code inside `hk.transform` can mis-handle that context. Prefer transforming the resulting `apply` function, or use the relevant Haiku wrapper for transforms inside the model.

Haiku does not prescribe optimizers, checkpoint formats, or replication APIs. That is an advantage if a team already owns those pieces, but it is additional integration work if the team expects a full training or serving stack. Google DeepMind recommends Flax for new projects because of its broader features, documentation, and ecosystem. Haiku is in best-effort maintenance focused on fixes and compatibility, so retaining it makes more sense for existing code than choosing it in anticipation of new features.

### Hardware & Deployment Guide
Install a JAX build appropriate to the target environment before running Haiku, then install the `dm-haiku` package from PyPI or from Git. GPU and TPU support comes from JAX, not the Haiku wheel. Model execution stays in the application process and does not require a hosted API. For deployment sizing, test representative dtypes, input shapes, and batch sizes, separating steady-state execution from first-call compilation. Training also needs memory for gradients and any optimizer state.

The release history is useful when pinning an environment: v0.0.15 enabled use without Flax on Python 3.13 and later; v0.0.16 fixed a `no_flax` shim error involving `inspect.stack()`. v0.0.17 exposed `spmd_axis_name` on `hk.vmap`, improved the slicing path for `static_unroll`'s reverse-mode pass using `jnp.unstack`, and included JAX compatibility changes. Test the exact Python/JAX/Haiku combination the application will ship.
```

## Key Capabilities
```text
- Execution boundary: `hk.transform` exposes pure `init` and `apply` functions for JAX transformations.
- Parameter structure: `hk.get_parameter` initializes or retrieves named arrays in a mapping keyed by module and parameter name.
- State threading: `hk.transform_with_state` separates trainable parameters from mutable state and returns updated state from `apply`.
- Randomness: `hk.next_rng_key()` derives per-call keys from the top-level seed; use Haiku-aware wrappers when transforming code that consumes keys inside the model.
- Parallel execution: Use JAX `pmap` on transformed functions; v0.0.17 exposes `spmd_axis_name` in `hk.vmap`.
- Runtime ownership: Install the JAX backend separately; Haiku does not prescribe an optimizer, checkpoint format, or serving layer.
```

## Quick Start / Clone
```bash
import haiku as hk
import jax.numpy as jnp

def softmax_cross_entropy(logits, labels):
  one_hot = jax.nn.one_hot(labels, logits.shape[-1])
  return -jnp.sum(jax.nn.log_softmax(logits) * one_hot, axis=-1)

def loss_fn(images, labels):
  mlp = hk.Sequential([
      hk.Linear(300), jax.nn.relu,
      hk.Linear(100), jax.nn.relu,
      hk.Linear(10),
  ])
  logits = mlp(images)
  return jnp.mean(softmax_cross_entropy(logits, labels))

loss_fn_t = hk.transform(loss_fn)
loss_fn_t = hk.without_apply_rng(loss_fn_t)

rng = jax.random.PRNGKey(42)
dummy_images, dummy_labels = next(input_dataset)
params = loss_fn_t.init(rng, dummy_images, dummy_labels)

def update_rule(param, update):
  return param - 0.01 * update

for images, labels in input_dataset:
  grads = jax.grad(loss_fn_t.apply)(params, images, labels)
  params = jax.tree.map(update_rule, params, grads)
```
