--- library_name: pytorch pipeline_tag: text-to-video tags: - text-to-video - video-generation - world-model - latent-video - text-conditioned - flow-matching - transformer - pytorch - torch-xla - google-tpu - spatiotemporal - egocentric-video - research --- # WorldDiT — Clustered Latent Video World Models WorldDiT is a collection of compact Transformer-based video world models trained on clustered egocentric video data. Instead of training one large model on the entire dataset, the training pipeline divides the dataset into four semantic groups. Each group receives its own WorldDiT model, trained independently on a dedicated TPU chip. The models operate in a learned spatiotemporal latent space produced by a separate Variational Autoencoder (VAE). Text embeddings condition video generation, while temporal context and hand-related features are incorporated into the automatically generated training prompts. The implementation uses PyTorch, PyTorch/XLA, and Google Cloud TPUs. ## Overview The training pipeline consists of four main stages: 1. **Semantic clustering:** Video segments are grouped into four clusters using cosine similarity between text embeddings. 2. **Group preparation:** A larger and more diverse set of clips is selected for each cluster. New prompts are generated using task descriptions, temporal context, environment information, and hand features. 3. **Independent model training:** Four separate WorldDiT models are trained, with one training process assigned to each TPU chip. 4. **Video reconstruction:** The trained EMA models generate latent video sequences, which are decoded into RGB videos using the pretrained VAE. Each group is trained as an independent model rather than as a shard of one distributed model. ## Architecture ### Model configuration Each group uses the same WorldDiT architecture: | Parameter | Value | |---|---:| | Hidden size | 512 | | Transformer depth | 10 | | Attention heads | 8 | | Head dimension | 64 | | Approximate parameters | 50M | | Latent channels | 128 | | Temporal latent positions | 13 | | Spatial latent resolution | 8 × 8 | | Tokens per sequence | 832 | | Text embedding dimension | 768 | | Text sequence length in v2 | 64 | The model is instantiated as: ```python model = WorldDiT( d=512, depth=10, heads=8 ) ``` The parameter count is also printed by the training script when each group starts. ### Video latent representation WorldDiT does not directly predict RGB pixels. Each training example is a VAE-encoded video sequence with the shape: ```text (128, 13, 8, 8) ``` The dimensions represent: - 128 latent channels. - 13 temporal positions. - An 8 × 8 spatial latent grid. The resulting sequence contains 832 spatiotemporal tokens. The pretrained VAE decoder reconstructs the generated latent representation into RGB video. In the current implementation, the decoded output has the shape: ```text (3, 97, 256, 256) ``` This corresponds to 97 RGB frames at 256 × 256 resolution. ## Semantic clustering The initial clustering stage divides the dataset into four groups. The clustering script uses precomputed text embeddings and attention masks: ```text ~/wm_data/ txt_emb.npy txt_mask.npy txt_idx.npy texts.json meta.json ``` For each text entry, token embeddings are averaged using the attention mask and normalized to unit length. The embedding of each video segment is selected through `txt_idx.npy`. Clustering uses cosine similarity and k-means++ initialization: | Parameter | Value | |---|---:| | Number of groups | 4 | | Initialization | k-means++ | | Restarts | 5 | | Iterations per restart | 50 | | Distance | Cosine distance | The initial clustering stage selects 10 representative clips per group and writes: ```text ~/wm_groups/groups.json ``` The v2 preparation stage reuses the same clustering procedure but increases the selection to 38 clips per group. This produces four groups with up to 38 selected video segments each. ## V2 dataset preparation The v2 pipeline creates more detailed and diverse text conditions for each selected video segment. It uses several sources of information: - Original task descriptions. - Environment descriptions. - Current action or keystep. - Previous and next actions from the same video. - Hand visibility and movement features. - Whether a hand is gripping an object or has an open palm. - Approximate hand movement speed. - The position of the segment within the full video. ### Hand features The preparation script loads: ```text ~/wm_data/hand_feats.npy ``` The array is reshaped into: ```text (-1, 4, 2, 10) ``` The hand features are used to construct textual descriptions of the observed hands. The generated descriptions distinguish between: - Both hands visible. - One hand visible. - Hands mostly outside the frame. - Gripping an object. - Open palm. - Quick hand movement. - Slow deliberate motion. - Hands nearly still. ### Temporal context The preparation stage reads: ```text ~/ego-raw/spans.csv ``` It uses the `clip_id`, `start_s`, `end_s`, and `keystep` fields to recover the previous and next actions surrounding each selected segment. This adds temporal context to the generated prompt. For example, a prompt can describe the current action while also mentioning what happened immediately before it and what action follows. ### Prompt generation The v2 pipeline uses multiple prompt templates combining task, environment, current action, previous and next actions, hand state, and movement speed. The resulting prompts are encoded with the external `text_emb.py` module. The encoder is configured with: ```python text_emb.L = 64 ``` For each group, the preparation stage writes: ```text ~/wm_groups/v2/ groups_v2.json emb_g0.npy emb_g1.npy emb_g2.npy emb_g3.npy msk_g0.npy msk_g1.npy msk_g2.npy msk_g3.npy ``` Each group's embeddings and masks correspond to that group's selected prompts. The generated group metadata contains: - Group identifier. - Original cluster size. - Most common tasks. - Selected clip indices. - Generated text prompts. ## Flow-matching objective WorldDiT is trained using a flow-matching objective. Given a clean latent sequence \(x_0\), Gaussian noise \(\epsilon\), and a time variable \(t\), the training script constructs: \[ x_t=(1-t)x_0+t\epsilon \] The target velocity is: \[ v=\epsilon-x_0 \] The model predicts: \[ \hat v_\theta(x_t,t,c) \] where \(c\) represents the text embeddings and attention mask. The training loss is: \[ \mathcal{L}= \mathbb{E}\left[ \left\| \hat v_\theta(x_t,t,c)-(\epsilon-x_0) \right\|_2^2 \right] \] The time variable is sampled independently for each temporal position in a video sequence. With a probability of 50%, all temporal positions in a training example share the same time value. ### Optimization The training process uses: - AdamW optimizer. - BF16 autocasting on XLA. - Gradient clipping. - Learning-rate warmup. - Exponential moving average of model parameters. The EMA parameters are updated with a decay of 0.99. ## Repository and file layout The scripts expect the following files under the user's home directory: ```text ~/ wm.py vae.py text_emb.py wm_data/ latents.npy txt_emb.npy txt_mask.npy txt_idx.npy texts.json meta.json hand_feats.npy wm_run/ lat_stats.npz vae_run/ last.pt ego-raw/ spans.csv wm_groups/ cluster.py train_group.py groups.json v2/ groups_v2.json emb_g0.npy emb_g1.npy emb_g2.npy emb_g3.npy msk_g0.npy msk_g1.npy msk_g2.npy msk_g3.npy run_v2.sh stdout_g0.txt stdout_g1.txt stdout_g2.txt stdout_g3.txt done.txt g0/ wm.pt log.txt gen10.mp4 g1/ wm.pt log.txt gen10.mp4 g2/ wm.pt log.txt gen10.mp4 g3/ wm.pt log.txt gen10.mp4 train_group2.py ``` The v2 preparation script generates `train_group2.py` and `run_v2.sh`. The exact contents of the generated training script depend on the source `train_group.py` and the transformations performed by the preparation script. ## Dataset format The training pipeline expects precomputed NumPy arrays. | File | Expected shape | Description | |---|---|---| | `latents.npy` | `(N, 128, 13, 8, 8)` | VAE-encoded video segments | | `txt_emb.npy` | `(M, L, 768)` | Original text embeddings | | `txt_mask.npy` | `(M, L)` | Text attention masks | | `txt_idx.npy` | `(N,)` | Mapping from video segments to text entries | | `hand_feats.npy` | Compatible with `(-1, 4, 2, 10)` | Hand-related features | | `texts.json` | List of strings | Text descriptions | | `meta.json` | Segment metadata | Clip ID and segment start/end times | The latent normalization statistics are stored in: ```text ~/wm_run/lat_stats.npz ``` The archive must contain: ```python mean std ``` The trainer normalizes latents using: ```python normalized_latents = (latents - mean) / std ``` Before VAE decoding, the original scale is restored: ```python decoded_latents = generated_latents * std + mean ``` The selected clip indices in the group metadata must be valid indices into `latents.npy`, `txt_idx.npy`, `meta.json`, and the corresponding hand feature data. ## Training environment The implementation uses: - Python. - PyTorch. - PyTorch/XLA. - NumPy. - PyAV. - The project's `wm.py`, `vae.py`, and `text_emb.py` modules. - Google Cloud TPU runtime. The PyTorch and PyTorch/XLA versions must be compatible with the installed TPU runtime. The group training script uses: ```python import torch_xla.core.xla_model as xm dev = xm.xla_device() ``` It uses one TPU device per process. The v2 launcher starts four separate processes, assigning one visible TPU chip to each group. This is not a single GSPMD-sharded model. ## Training ### Step 1. Prepare the initial groups Run the initial clustering script: ```bash python ~/wm_groups/cluster.py ``` This creates: ```text ~/wm_groups/groups.json ``` The v2 preparation script reads the original clustering implementation and reuses its clustering calculations. ### Step 2. Prepare the v2 groups Run the v2 preparation code. This stage: 1. Loads the original clustering implementation. 2. Repeats clustering with four groups and up to 38 selected clips per group. 3. Loads hand features and temporal action spans. 4. Creates richer prompts for selected clips. 5. Encodes prompts using `text_emb.py` with a sequence length of 64. 6. Saves group metadata, embeddings, and masks. 7. Generates `train_group2.py`. 8. Generates `run_v2.sh`. The preparation script should finish by printing: ```text BUILD_OK ``` After this step, verify that the generated files exist: ```bash ls -lh ~/wm_groups/v2/groups_v2.json ls -lh ~/wm_groups/v2/emb_g*.npy ls -lh ~/wm_groups/v2/msk_g*.npy ls -lh ~/wm_groups/train_group2.py ls -lh ~/wm_groups/v2/run_v2.sh ``` ### Step 3. Start all four TPU training processes Run: ```bash bash ~/wm_groups/v2/run_v2.sh ``` The generated launcher executes: ```bash for g in 0 1 2 3; do TPU_CHIPS_PER_PROCESS_BOUNDS=1,1,1 \ TPU_PROCESS_BOUNDS=1,1,1 \ TPU_VISIBLE_CHIPS=$g \ TPU_PROCESS_PORT=$((8476+g)) \ CLOUD_TPU_TASK_ID=0 \ PJRT_DEVICE=TPU \ GROUP=$g \ MAX_MIN=12 \ RESUME=1 \ nohup ~/xla_env/bin/python \ ~/wm_groups/train_group2.py \ > ~/wm_groups/v2/stdout_g$g.txt 2>&1 & done wait echo DONE > ~/wm_groups/v2/done.txt ``` Each process receives its own `GROUP` value: | Process | Group | TPU chip | |---|---:|---:| | Process 0 | 0 | 0 | | Process 1 | 1 | 1 | | Process 2 | 2 | 2 | | Process 3 | 3 | 3 | All four groups train concurrently. The launcher uses the `~/xla_env/bin/python` environment. ### Important: checkpoint initialization The launcher sets: ```bash RESUME=1 ``` This means the training script must find the checkpoint specified in its `RESUME` branch. There are two checkpoint-path variants in the current scripts: - The original group trainer loads `OUT/wm.pt`. - The v2 preparation code rewrites the generated trainer to initialize from `~/wm_groups/g{G}/wm.pt`. - Another trainer variant may use `~/wm_groups/v2/g{G}/wm_prev.pt`. These are different paths and must not be treated as interchangeable. Before launching, inspect the actual generated trainer: ```bash grep -n -E 'RESUME|torch.load|OUT =' ~/wm_groups/train_group2.py ``` Make sure the checkpoint path in the `RESUME` branch exists for all four groups. The intended v2 initialization in the preparation script uses the previous group checkpoints under: ```text ~/wm_groups/g0/wm.pt ~/wm_groups/g1/wm.pt ~/wm_groups/g2/wm.pt ~/wm_groups/g3/wm.pt ``` If training should start from randomly initialized weights, remove `RESUME=1` from the generated launcher or unset the resume branch in the training script. ## Training configuration Each group uses the following defaults: | Parameter | Value | |---|---:| | Model | WorldDiT | | Hidden size | 512 | | Depth | 10 | | Attention heads | 8 | | Batch size | 20 | | Learning rate | 4e-4 | | Optimizer | AdamW | | Betas | (0.9, 0.95) | | Weight decay | 0 | | Gradient clipping | 1.0 | | LR warmup | 150 steps | | EMA decay | 0.99 | | Default maximum runtime | 8 minutes | | Runtime in v2 launcher | 12 minutes | | Default early-stop target | 0.05 | | Loss logging interval | 50 steps | The learning-rate scheduler uses linear warmup: \[ lr_s=lr_{\mathrm{base}}\cdot \min\left(1,\frac{s+1}{150}\right) \] The training loop stops when the runtime limit is reached or when the configured early-stop condition is met. The early-stop condition is checked after at least 600 steps: \[ \text{average recent loss}<\text{TARGET} \] The trainer calculates the average using the most recent six logged loss measurements. The runtime and learning-rate settings can be changed using environment variables: ```bash MAX_MIN=12 LR=4e-4 TARGET=0.05 ``` ## Checkpoints Each group writes its checkpoint to: ```text ~/wm_groups/v2/g0/wm.pt ~/wm_groups/v2/g1/wm.pt ~/wm_groups/v2/g2/wm.pt ~/wm_groups/v2/g3/wm.pt ``` The checkpoint contains: - `ema`: EMA model state dictionary. - `clips`: Selected clip indices. - `step`: Final training step. - `cfg`: Model configuration. The model configuration is: ```python { "d": 512, "depth": 10, "heads": 8 } ``` The checkpoint stores EMA weights rather than the complete optimizer and scheduler state. AdamW optimizer state is not saved, and resuming does not restore the original optimizer or learning-rate scheduler state. ## Video generation and validation After the training loop, each group runs a generation test using its EMA model. The generation process: 1. Creates a Gaussian noise latent sequence. 2. Uses the corresponding text embeddings and masks. 3. Runs 40 flow-matching sampling steps. 4. Compares generated latents with the selected original latents. 5. Decodes generated latents through the pretrained VAE. 6. Saves a video montage. The sampling update is: \[ x \leftarrow x-\frac{\hat v_\theta(x,t,c)}{40} \] The initial noise uses a fixed seed of 0. The trainer logs a latent-space MSE for each selected prompt. The VAE checkpoint is loaded from: ```text ~/vae_run/last.pt ``` The checkpoint must contain the VAE state dictionary under the `model` key. The decoder is obtained through: ```python vae = VAE() vae.load_state_dict( torch.load( "~/vae_run/last.pt", map_location="cpu" )["model"] ) decoder = vae.dec ``` The final video montage is written to: ```text ~/wm_groups/v2/g0/gen10.mp4 ~/wm_groups/v2/g1/gen10.mp4 ~/wm_groups/v2/g2/gen10.mp4 ~/wm_groups/v2/g3/gen10.mp4 ``` Each montage contains 10 generated video sequences arranged in a 5-column, 2-row grid. The montage resolution is 1280 × 512, encoded using H.264 at 24 FPS. These are group-level preview montages, not individual MP4 files for every prompt. ## Monitoring Each group has its own training log: ```text ~/wm_groups/v2/g0/log.txt ~/wm_groups/v2/g1/log.txt ~/wm_groups/v2/g2/log.txt ~/wm_groups/v2/g3/log.txt ``` Standard output and errors from the four processes are stored in: ```text ~/wm_groups/v2/stdout_g0.txt ~/wm_groups/v2/stdout_g1.txt ~/wm_groups/v2/stdout_g2.txt ~/wm_groups/v2/stdout_g3.txt ``` The launcher creates: ```text ~/wm_groups/v2/done.txt ``` when all four processes finish. To inspect the output: ```bash tail -f ~/wm_groups/v2/stdout_g0.txt ``` To inspect the training log: ```bash tail -f ~/wm_groups/v2/g0/log.txt ``` To check all groups: ```bash for g in 0 1 2 3; do echo "===== GROUP $g =====" tail -n 10 ~/wm_groups/v2/g$g/log.txt done ``` ## Inference status The current implementation includes a generation and validation stage at the end of each training run. It does not currently provide a separate standalone inference script for loading a Hugging Face checkpoint and generating an arbitrary video from a new prompt. The generated videos are produced using the prompts and embeddings prepared for the corresponding group. A separate inference pipeline would need to load the selected group's EMA checkpoint, recreate the text embeddings, initialize latent noise, run flow-matching sampling, and decode the result with the compatible VAE. ## Current scope and limitations WorldDiT is a text-conditioned latent video generation system trained using clustered egocentric video segments. The v2 preparation stage uses hand-related features and temporal action context to build richer text prompts. However, the current implementation does not provide: - Explicit robot action conditioning. - Direct robot control. - A physics-based simulator. - An interactive environment that reacts to agent actions. - A standalone arbitrary-prompt inference interface. - A standardized benchmark evaluation. The models are trained independently for their respective data groups. ## Project summary | Property | Description | |---|---| | Project | LiberalMind | | Model family | WorldDiT | | Training approach | Four independent group-specific models | | Model size | Approximately 50M parameters per group | | Number of groups | 4 | | Selected clips | Up to 38 per group in v2 | | Training hardware | Google Cloud TPU | | TPU allocation | One TPU chip per group process | | Framework | PyTorch / PyTorch-XLA | | Video representation | VAE latent space | | Latent shape | 128 × 13 × 8 × 8 | | Text conditioning | 768-dimensional embeddings | | Training objective | Flow matching | | Optimization | AdamW with EMA | | Video decoding | Separate pretrained VAE | **WorldDiT is a research implementation of clustered, text-conditioned latent video world models.**