xwm.core¶
Types, base modules, EMA targets, rollouts and the ambient key source. Everything else in the library is built on these.
Core abstractions: types, base modules, EMA targets, latent rollouts.
Modules:
| Name | Description |
|---|---|
ema |
Exponential-moving-average targets. |
module |
Base classes shared by every xwm model. |
random |
A default PRNG key, so |
rollout |
Latent rollouts. |
types |
Shared type aliases and structural protocols for xwm. |
Classes:
| Name | Description |
|---|---|
Module |
An |
WorldModel |
A trainable world model. |
KeySource |
A counter-based key generator: |
Encoder |
Maps one sample to a token sequence |
LatentDynamics |
One step of action-conditioned latent dynamics: |
Objective |
Batch-level training objective, returning |
Predictor |
Predicts target-position embeddings from context tokens. |
Functions:
| Name | Description |
|---|---|
ema_init |
Create the initial target as a detached copy of |
ema_update |
|
stop_gradient |
Detach every array leaf of |
batched_apply |
Apply |
vmap_apply |
vmap |
default_key |
Draw the next key from the ambient source. |
key_source |
The ambient key source, created on first use. |
resolve_key |
Return |
seed |
Use |
set_seed |
Replace the ambient source with a fresh one for |
split |
|
rollout_cost |
Accumulate |
teacher_forced_rollout |
One-step predictions from ground-truth latents (teacher forcing). |
Module
¶
Bases: Module
An equinox.Module with a couple of conveniences.
Everything in xwm subclasses this, so n_params and
eval_mode are available on individual layers and on whole world
models alike.
Note that inference is deliberately not the name of the method here:
Equinox treats an inference attribute as the flag it toggles, so a
method by that name would shadow it and break
equinox.nn.inference_mode.
Methods:
| Name | Description |
|---|---|
eval_mode |
A copy with dropout and drop-path disabled. |
train_mode |
A copy with dropout and drop-path re-enabled. |
Attributes:
| Name | Type | Description |
|---|---|---|
n_params |
int
|
Number of trainable (inexact-array) scalars in this subtree. |
eval_mode
¶
A copy with dropout and drop-path disabled.
Modules are immutable, so this returns the eval-mode model rather
than mutating in place: model = model.eval_mode().
WorldModel
¶
Bases: Module
A trainable world model.
Subclasses implement loss, the single contract the trainer relies
on. Models whose objective needs a slowly-moving teacher (I-JEPA, V-JEPA,
BYOL-style asymmetry) set uses_target to True; the trainer then
maintains an EMA copy of the model and passes it in as target. Models
that do not need one (LeJEPA, VICReg) leave it False and receive
None.
Methods:
| Name | Description |
|---|---|
loss |
Scalar loss for a batched input, plus scalars to log. |
trainable |
Boolean tree marking which leaves the optimizer may update. |
prepare_batch |
Host-side hook, run before the jitted step. |
loss
¶
loss(batch: Batch, *, key: PRNGKey, target: WorldModel | None = None) -> tuple[Array, Metrics]
Scalar loss for a batched input, plus scalars to log.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
Batch
|
modality-specific dict (see |
required |
key
|
PRNGKey
|
RNG for masking, dropout and any stochastic objective. |
required |
target
|
WorldModel | None
|
EMA copy of |
None
|
Source code in xwm/core/module.py
trainable
¶
Boolean tree marking which leaves the optimizer may update.
Defaults to every inexact array. Override to freeze part of the model -- an action-conditioned stage trained on top of a fixed video encoder is the canonical case, and freezing it here means the optimizer never allocates state for those parameters at all.
Source code in xwm/core/module.py
prepare_batch
¶
Host-side hook, run before the jitted step.
Where mask sampling and any other combinatorial, non-jittable batch
preparation belongs. It may read the model's static configuration but
must not depend on its parameters -- it runs outside jit and outside
the gradient.
Source code in xwm/core/module.py
KeySource
¶
A counter-based key generator: fold_in(root, n) for n = 0, 1, 2, ...
Counter-based rather than split-chained so the n-th draw is a pure function
of (seed, n). That makes the sequence inspectable and replayable, and
avoids a long chain of splits whose state depends on every prior call.
Methods:
| Name | Description |
|---|---|
next_key |
Return the next key and advance the counter. |
Attributes:
| Name | Type | Description |
|---|---|---|
counter |
int
|
How many keys have been drawn. Useful in tests and logs. |
Source code in xwm/core/random.py
next_key
¶
Encoder
¶
Bases: Protocol
Maps one sample to a token sequence (N, D).
LatentDynamics
¶
Bases: Protocol
One step of action-conditioned latent dynamics: (z, a) -> z'.
Objective
¶
Bases: Protocol
Batch-level training objective, returning (scalar_loss, metrics).
Predictor
¶
Bases: Protocol
Predicts target-position embeddings from context tokens.
context is (K_ctx, D) with flat grid positions context_idx;
the return value is (K_tgt, D) aligned with target_idx.
ema_init
¶
Create the initial target as a detached copy of model.
ema_update
¶
target <- m * target + (1 - m) * model over inexact arrays.
Non-array leaves (ints, bools, static config) are taken from model so
the target never drifts out of structural sync with the student.
Source code in xwm/core/ema.py
stop_gradient
¶
batched_apply
¶
Apply fn over the leading axis of x in chunks, then concatenate.
fn maps a batch to a batch (already vmapped or jitted). Use this instead
of one enormous call whenever the leading axis is a dataset rather than a
minibatch: encoding 16k frames at once asks the allocator for tens of
gigabytes, and the failure mode is an out-of-memory abort at the end of a
long run rather than anything diagnosable.
The trailing chunk may be smaller than batch_size, which costs one extra
compilation under jit; padding instead would silently change the result.
Source code in xwm/core/module.py
vmap_apply
¶
vmap fn over a batch, splitting key per sample.
fn is a sample-level callable fn(*args, key=...). Leading axes of
args are mapped; when key is None the key argument is
omitted entirely (so deterministic modules need no RNG plumbing).
Source code in xwm/core/module.py
default_key
¶
resolve_key
¶
Return key, or the next ambient key when it is None.
The one-line helper every constructor calls, so the fallback lives in one place instead of being reimplemented per module.
Source code in xwm/core/random.py
seed
¶
Use value as the ambient seed for the duration of the block.
set_seed
¶
set_seed(seed: int) -> KeySource
Replace the ambient source with a fresh one for seed.
Process-wide (within the current context). For a scoped change that restores
the previous source, use seed.
Source code in xwm/core/random.py
split
¶
n keys, split from key or drawn from the ambient source.
rollout_cost
¶
rollout_cost(dynamics: LatentDynamics, z0: Array, actions: Array, cost_fn: Callable[[Array, Array, int], Array], *, key: PRNGKey | None = None, cost_on: str = 'next') -> Array
Accumulate cost_fn(z, a, t) along a rollout.
Fused with the rollout so planners never materialise the whole trajectory, which matters when sampling thousands of candidate action sequences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cost_on
|
str
|
which latent the cost sees.
|
'next'
|
Source code in xwm/core/rollout.py
teacher_forced_rollout
¶
teacher_forced_rollout(dynamics: LatentDynamics, latents: Array, actions: Array, *, key: PRNGKey | None = None) -> Array
One-step predictions from ground-truth latents (teacher forcing).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
latents
|
Array
|
|
required |
actions
|
Array
|
|
required |
Returns:
| Type | Description |
|---|---|
Array
|
|
Source code in xwm/core/rollout.py
rollout¶
Note
xwm.core.rollout is both a submodule and the function it exports. The function
is documented here under its canonical path; xwm.core.rollout(...) is the way
to call it.
Roll dynamics forward over an action sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dynamics
|
LatentDynamics
|
one-step latent model |
required |
z0
|
Array
|
initial latent, any shape (typically |
required |
actions
|
Array
|
|
required |
key
|
PRNGKey | None
|
optional RNG for stochastic dynamics. |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
|
Array
|
not included, so |