Spaces:
Sleeping

blanchon commited on
Commit
19583ce
·
1 Parent(s): d033720

fix first-frame anchor + atomic crash; load models once; vendor trimmed o2laf

Browse files

- app: first-frame latents were sliced on the channel axis ([:, :1]), so the
anchor was 1 of 48 channels broadcast -> garbage frame 0 and the chosen
first frame ignored. Use the full [1, C, 1, h, w] latent.
- app: atomic actions passed an [H,W,3] image where [T,H,W,3] is expected.
- app: load both pipelines at startup (ZeroGPU moves them to the GPU per call)
instead of ~35 s of loading inside every GPU call; IDM reuses the pipeline's
encoder (from_pipeline) instead of loading a second copy; share one VAE.
- app: drop the LRU cache, torch/dynamo unpatch hack, debug-dataset upload and
prefetch thread.
- O2LaF/: inference-only fork of showlab/O2LaF: action encoder uses SDPA with a
dense mask (no torch.compile), LoRA merged at load, batched CFG; training,
data, CLIs and unused encoders removed.

O2LaF/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Show Lab
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
O2LaF/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # o2laf (inference-only fork for the demo Space)
2
+
3
+ Trimmed copy of [showlab/O2LaF](https://github.com/showlab/O2LaF) (MIT; files adapted from
4
+ NVIDIA AnyFlow keep their Apache-2.0 headers). This fork keeps only what the demo uses:
5
+ the `wan_dit` action encoder, the world models, sampling and the attention visualiser.
6
+
7
+ Changes from upstream:
8
+
9
+ - Training, data loading, export, CLIs and the V-JEPA 2 / ST-transformer encoders are removed.
10
+ - The action encoder runs its mask through SDPA with a dense boolean mask instead of
11
+ `torch.compile(flex_attention)`, so there is no compilation step.
12
+ - The action encoder's LoRA is merged into its weights at load time.
13
+ - With `unconditional_mode='full'`, classifier-free guidance runs both branches as one batch-2 forward.
O2LaF/o2laf/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """O²LaF: latent action learning and action-conditioned world models on Wan 2.2."""
2
+
3
+ __version__ = '0.1.0'
4
+
5
+ __all__ = ['ActionAttentionExtractor', 'ActionGuidance', 'AttentionRenderConfig', 'LatentActionPipeline']
6
+
7
+
8
+ def __getattr__(name):
9
+ # Lazy, so that importing a training module does not load the inference stack.
10
+ if name == 'LatentActionPipeline':
11
+ from o2laf.inference.pipeline import LatentActionPipeline
12
+
13
+ return LatentActionPipeline
14
+ if name == 'ActionGuidance':
15
+ from o2laf.inference.sampling import ActionGuidance
16
+
17
+ return ActionGuidance
18
+ if name in ('ActionAttentionExtractor', 'AttentionRenderConfig'):
19
+ from o2laf.inference import attention
20
+
21
+ return getattr(attention, name)
22
+ raise AttributeError(f'module {__name__!r} has no attribute {name!r}')
O2LaF/o2laf/action_encoders/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Action encoders: models that infer latent actions from video.
2
+
3
+ This inference-only copy keeps :mod:`~o2laf.action_encoders.wan_dit`, which reads
4
+ Wan VAE latents with the Wan DiT trunk (the encoder every released model uses).
5
+ """
6
+
7
+ from o2laf.action_encoders import wan_dit # noqa: F401 (registration)
8
+ from o2laf.action_encoders.base import build_action_encoder_spec
9
+ from o2laf.utils.registry import ACTION_ENCODER_REGISTRY
10
+
11
+
12
+ def build_action_encoder(name):
13
+ """Return the action encoder class registered under ``name``."""
14
+ return ACTION_ENCODER_REGISTRY.get(name)
15
+
16
+
17
+ __all__ = ['build_action_encoder', 'build_action_encoder_spec']
O2LaF/o2laf/action_encoders/base.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The contract between the trainers and one action encoder.
2
+
3
+ Every action encoder reads the same thing -- the RGB video the dataset produces
4
+ -- and differs only in how it turns that video into tokens its trunk
5
+ understands. The Wan DiT encoder VAE-encodes it to latents; V-JEPA2 crops it
6
+ square and resizes; the ST-Transformer resizes. The VAE is a preprocessing step
7
+ like the others, not a different kind of input, so there is one ``encode`` and
8
+ no branching on what an encoder "reads".
9
+
10
+ A spec also declares the rest of what a trainer needs to know about its encoder:
11
+ how many codes it emits per latent transition, how to build it, and what
12
+ identifies the action space it defines in a checkpoint.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from abc import ABC, abstractmethod
18
+
19
+ _ACTION_ENCODER_SPECS = {}
20
+
21
+ # Optimizer parameter-group names, shared by the trainer that creates the groups
22
+ # and the encoders that re-rate them. They are defined once because the two
23
+ # sides are in different modules: when these were string literals on both sides,
24
+ # renaming the trainer's groups silently disabled an encoder's learning rate.
25
+ GROUP_WORLD_MODEL_LORA = 'world_model_lora'
26
+ GROUP_ACTION_EMBEDDER = 'action_embedder'
27
+ GROUP_ACTION_ENCODER_LORA = 'action_encoder_lora'
28
+ GROUP_READOUT = 'readout'
29
+ GROUP_WORLD_MODEL_OTHER = 'world_model_other'
30
+ GROUP_ACTION_ENCODER_OTHER = 'action_encoder_other'
31
+
32
+ PARAM_GROUP_NAMES = (
33
+ GROUP_WORLD_MODEL_LORA,
34
+ GROUP_ACTION_EMBEDDER,
35
+ GROUP_ACTION_ENCODER_LORA,
36
+ GROUP_READOUT,
37
+ GROUP_WORLD_MODEL_OTHER,
38
+ GROUP_ACTION_ENCODER_OTHER,
39
+ )
40
+
41
+
42
+ def unwrap_peft(module):
43
+ """Return the inner module under an optional PEFT wrapper."""
44
+ return module.get_base_model() if hasattr(module, 'get_base_model') else module
45
+
46
+
47
+ def register_action_encoder_spec(name):
48
+ """Register a spec class under the name used by ``idm_cfg.backend``."""
49
+
50
+ def decorator(spec_class):
51
+ if name in _ACTION_ENCODER_SPECS:
52
+ raise KeyError(f'Action encoder spec {name!r} is already registered.')
53
+ spec_class.name = name
54
+ _ACTION_ENCODER_SPECS[name] = spec_class
55
+ return spec_class
56
+
57
+ return decorator
58
+
59
+
60
+ def build_action_encoder_spec(name):
61
+ """Construct a registered action encoder spec."""
62
+ if name not in _ACTION_ENCODER_SPECS:
63
+ available = ', '.join(sorted(_ACTION_ENCODER_SPECS)) or '<empty>'
64
+ raise KeyError(f'Unknown action encoder {name!r}. Available: {available}.')
65
+ return _ACTION_ENCODER_SPECS[name]()
66
+
67
+
68
+ class ActionEncoderSpec(ABC):
69
+ """Build, run and describe one action encoder."""
70
+
71
+ name = None
72
+ # Codes emitted per latent transition. Fixed by the architecture, not a
73
+ # free choice: a config may state it, but only to agree with it.
74
+ codes_per_transition = None
75
+ action_ratio_cfg_key = None
76
+ legacy_contract_state_keys = ()
77
+ # Whether ``encode`` reads the clip's pixels (True) or the VAE latents the
78
+ # caller already holds (False). Callers decode a clip only when it is True.
79
+ reads_pixels = True
80
+ # RGB frames one encoder pass consumes, for encoders that run in windows
81
+ # over a longer clip. ``None`` means the encoder takes the whole clip.
82
+ window_rgb_frames = 41
83
+ # ``action_cfg`` keys that describe the Wan DiT in-sequence readout, which
84
+ # only that encoder has. Accepting them elsewhere would silently describe an
85
+ # encoder the run does not train.
86
+ unsupported_action_cfg_keys = ('query_init_std',)
87
+
88
+ def prepare_trainer(self, trainer, action_cfg):
89
+ """Set encoder-specific trainer attributes before common construction."""
90
+
91
+ @abstractmethod
92
+ def build_contract(self, trainer, idm_cfg):
93
+ """Return metadata that identifies the action space this encoder defines."""
94
+
95
+ @abstractmethod
96
+ def build_encoder(self, trainer, idm_cfg, dtype):
97
+ """Construct, adapt, select trainable parameters, and FSDP-wrap the encoder."""
98
+
99
+ @abstractmethod
100
+ def encode(self, encoder, *, latents=None, pixel_values=None, prompt_embeds=None) -> dict:
101
+ """Return the action posterior for one clip, reading whichever form this encoder reads.
102
+
103
+ Callers pass every form they already hold; an encoder takes the one it
104
+ needs and ignores the rest. The latents are the ones the world model
105
+ will condition, so the VAE is never run a second time here.
106
+ """
107
+
108
+ def validate_state_contract(self, state, expected, label):
109
+ """Refuse an encoder state whose action space was defined by a different encoder."""
110
+ name = state.get('idm_backend')
111
+ if name is not None and name != self.name:
112
+ raise RuntimeError(f'{label} was written by the {name!r} action encoder, not {self.name!r}.')
113
+ actual = state.get('idm_contract')
114
+ if actual is None:
115
+ for key in self.legacy_contract_state_keys:
116
+ if state.get(key) is not None:
117
+ actual = state[key]
118
+ break
119
+ if not isinstance(actual, dict):
120
+ raise RuntimeError(f'{label} has no valid encoder contract; refusing to load an action space of unknown origin.')
121
+ if actual != expected:
122
+ differing = {
123
+ key: (expected.get(key), actual.get(key))
124
+ for key in set(expected) | set(actual)
125
+ if expected.get(key) != actual.get(key)
126
+ }
127
+ raise RuntimeError(f'{label} encoder contract mismatch: {differing}.')
128
+
129
+ def configure_optimizer_groups(self, trainer, groups):
130
+ """Apply encoder-specific optimizer rates after common grouping."""
131
+ unknown = [group['name'] for group in groups if group['name'] not in PARAM_GROUP_NAMES]
132
+ if unknown:
133
+ raise RuntimeError(f'Unknown optimizer parameter groups {unknown}; expected a subset of {list(PARAM_GROUP_NAMES)}.')
134
+ return groups
135
+
136
+
137
+ def resolve_codes_per_transition(spec, action_cfg):
138
+ """The encoder's code rate, checking any config that restates it.
139
+
140
+ The rate is fixed by the architecture, so a config may only agree with it.
141
+ """
142
+ action_cfg = action_cfg or {}
143
+ present = [key for key in spec.unsupported_action_cfg_keys if key in action_cfg]
144
+ if present:
145
+ raise ValueError(f'action_cfg keys {present} describe a readout the {spec.name!r} action encoder does not have.')
146
+ required = int(spec.codes_per_transition)
147
+ stated = action_cfg.get(spec.action_ratio_cfg_key)
148
+ if stated is not None and int(stated) != required:
149
+ raise ValueError(f'{spec.name} emits {required} codes per latent transition; {spec.action_ratio_cfg_key}={stated} disagrees.')
150
+ return required
O2LaF/o2laf/action_encoders/posterior.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Diagonal-Gaussian posterior over latent actions, and its KL to N(0, I)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+
8
+
9
+ class GaussianActionHead(nn.Module):
10
+ """Project features to ``(mu, logvar)`` of a diagonal Gaussian action posterior.
11
+
12
+ Moments and the reparameterisation run in fp32 regardless of the surrounding
13
+ autocast dtype, because ``exp(0.5 * logvar)`` overflows easily in bf16. The
14
+ projection is near-zero-initialised, so at step 0 the posterior is the prior
15
+ and KL is ~0. In eval mode the returned ``action`` is the posterior mean.
16
+ """
17
+
18
+ def __init__(
19
+ self,
20
+ input_dim: int,
21
+ latent_dim: int = 32,
22
+ logvar_min: float = -10.0,
23
+ logvar_max: float = 10.0,
24
+ init_std: float = 1e-3,
25
+ ) -> None:
26
+ super().__init__()
27
+ if int(latent_dim) < 1:
28
+ raise ValueError(f'latent_dim must be >= 1, got {latent_dim}')
29
+ if float(logvar_min) >= float(logvar_max):
30
+ raise ValueError(f'logvar_min={logvar_min} must be < logvar_max={logvar_max}')
31
+ self.latent_dim = int(latent_dim)
32
+ self.logvar_min = float(logvar_min)
33
+ self.logvar_max = float(logvar_max)
34
+ self.to_moments = nn.Linear(input_dim, 2 * self.latent_dim)
35
+ nn.init.normal_(self.to_moments.weight, mean=0.0, std=float(init_std))
36
+ nn.init.zeros_(self.to_moments.bias)
37
+
38
+ def forward(self, hidden_states: torch.Tensor) -> dict[str, torch.Tensor]:
39
+ moments = self.to_moments(hidden_states)
40
+ moments = torch.nan_to_num(moments, nan=0.0, posinf=0.0, neginf=0.0)
41
+ action_mu, action_logvar = moments.float().chunk(2, dim=-1)
42
+ action_logvar = torch.nan_to_num(action_logvar, nan=0.0, posinf=0.0, neginf=0.0).clamp(
43
+ self.logvar_min, self.logvar_max
44
+ )
45
+ if self.training:
46
+ deviation = torch.exp(0.5 * action_logvar)
47
+ action = action_mu + torch.randn_like(deviation) * deviation
48
+ else:
49
+ action = action_mu
50
+ return {
51
+ 'action': action.to(hidden_states.dtype),
52
+ 'action_mu': action_mu,
53
+ 'action_logvar': action_logvar,
54
+ }
55
+
56
+
57
+ def kl_divergence(action_mu: torch.Tensor, action_logvar: torch.Tensor) -> torch.Tensor:
58
+ """KL to a standard normal in nats per action: summed over the code, averaged elsewhere."""
59
+ action_mu = action_mu.float()
60
+ action_logvar = action_logvar.float()
61
+ return -0.5 * (1 + action_logvar - action_mu.square() - action_logvar.exp()).sum(dim=-1).mean()
62
+
63
+
64
+ def kl_per_dimension(action_mu: torch.Tensor, action_logvar: torch.Tensor) -> torch.Tensor:
65
+ """Per-code-dimension KL ``[latent_dim]``; a dimension near 0 carries nothing."""
66
+ action_mu = action_mu.float()
67
+ action_logvar = action_logvar.float()
68
+ per_dimension = -0.5 * (1 + action_logvar - action_mu.square() - action_logvar.exp())
69
+ return per_dimension.reshape(-1, per_dimension.shape[-1]).mean(dim=0)
O2LaF/o2laf/action_encoders/wan_dit.py ADDED
@@ -0,0 +1,477 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+ """Action encoder built on the Wan 2.2 DiT trunk.
17
+
18
+ The encoder reads Wan VAE latents and emits one Gaussian action code per latent
19
+ transition. One learnable query token is interleaved into Wan's own token
20
+ sequence after every latent frame, so it is shaped by all pretrained blocks.
21
+
22
+ The attention mask has three clauses:
23
+
24
+ * video -> video is frame-causal (frame ``t`` reads frames ``0..t``), so
25
+ ``a_t`` depends only on frames ``0..t+1``;
26
+ * video -> action is forbidden, so video tokens compute exactly what they would
27
+ without the extra tokens;
28
+ * action -> video reads only the two frames ``{t, t+1}`` of its transition, and
29
+ action -> action is forbidden, so the codes cannot agree on a clip-level label.
30
+
31
+ The head reads the query of transition ``t`` directly (pairwise readout).
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import torch
37
+ import torch.nn as nn
38
+ from diffusers import WanTransformer3DModel
39
+ from diffusers.utils import apply_lora_scale
40
+
41
+ from peft import LoraConfig, get_peft_model
42
+
43
+ from o2laf.action_encoders.base import ActionEncoderSpec, register_action_encoder_spec
44
+ from o2laf.action_encoders.posterior import GaussianActionHead
45
+ from o2laf.utils.dist_util import fsdp2_wrap
46
+ from o2laf.utils.lora_util import LORA_ADAPTER_NAME, LORA_STATE_KEYS, filter_learnable_module
47
+ from o2laf.utils.flex_attention import (
48
+ WanFlexAttnProcessor,
49
+ cached_block_mask,
50
+ install_flex_attention,
51
+ pad_sequence_dim,
52
+ padded_length,
53
+ verify_flex_attention,
54
+ )
55
+ from o2laf.utils.registry import ACTION_ENCODER_REGISTRY
56
+
57
+
58
+ class PaddedFlexAttnProcessor(WanFlexAttnProcessor):
59
+ """Flex self-attention that pads the sequence around the attention call.
60
+
61
+ The encoder cannot pad ``hidden_states`` before its block loop, because the
62
+ per-frame timestep embedding is broadcast by ``repeat_interleave`` and needs
63
+ the unpadded length. Padding rows are zeros, the mask rejects them in both
64
+ directions, and the output is sliced back before it leaves this call.
65
+ """
66
+
67
+ def __init__(self) -> None:
68
+ super().__init__()
69
+ self.padded_seq_len = None
70
+
71
+ def __call__(
72
+ self,
73
+ attn,
74
+ hidden_states: torch.Tensor,
75
+ encoder_hidden_states: torch.Tensor | None = None,
76
+ attention_mask: torch.Tensor | None = None,
77
+ rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
78
+ ) -> torch.Tensor:
79
+ if self.block_mask is None:
80
+ return super().__call__(attn, hidden_states, encoder_hidden_states, attention_mask, rotary_emb)
81
+ if self.padded_seq_len is None:
82
+ raise RuntimeError('block_mask was installed without padded_seq_len; they must be set together.')
83
+ real_seq_len = hidden_states.shape[1]
84
+ padded_seq_len = int(self.padded_seq_len)
85
+ if padded_seq_len < real_seq_len:
86
+ raise RuntimeError(
87
+ f'padded_seq_len={padded_seq_len} is shorter than the sequence {real_seq_len}; '
88
+ 'the block mask does not match this input.'
89
+ )
90
+ hidden_states = pad_sequence_dim(hidden_states, padded_seq_len, dim=1)
91
+ if rotary_emb is not None:
92
+ rotary_emb = tuple(pad_sequence_dim(freqs, padded_seq_len, dim=1) for freqs in rotary_emb)
93
+ output = super().__call__(attn, hidden_states, encoder_hidden_states, attention_mask, rotary_emb)
94
+ return output[:, :real_seq_len]
95
+
96
+
97
+ class InSequenceReadout(nn.Module):
98
+ """The per-frame query token, its RoPE angle, and the Gaussian head.
99
+
100
+ Every parameter the readout adds lives here, under ``idm_head`` in the
101
+ encoder, so parameter grouping and checkpointing can select it by name.
102
+ Length-agnostic: one query weight is expanded to however many frames the
103
+ input has.
104
+ """
105
+
106
+ def __init__(
107
+ self,
108
+ input_dim: int,
109
+ latent_dim: int = 32,
110
+ attention_head_dim: int = 128,
111
+ logvar_min: float = -10.0,
112
+ logvar_max: float = 10.0,
113
+ query_init_std: float = 0.02,
114
+ ) -> None:
115
+ super().__init__()
116
+ self.input_dim = int(input_dim)
117
+ self.latent_dim = int(latent_dim)
118
+
119
+ # Small init keeps the token's residual stream dominated by what it reads.
120
+ self.action_query = nn.Parameter(torch.empty(1, self.input_dim))
121
+ if float(query_init_std) > 0.0:
122
+ nn.init.normal_(self.action_query, mean=0.0, std=float(query_init_std))
123
+ else:
124
+ nn.init.zeros_(self.action_query)
125
+
126
+ # Spatial RoPE for the token, parameterised by angle so it is always a
127
+ # rotation. Zero is the identity: the token carries a purely temporal
128
+ # position. The released configs keep it frozen at zero.
129
+ head_dim = int(attention_head_dim)
130
+ self.temporal_width = head_dim - 2 * (head_dim // 3)
131
+ self.spatial_width = 2 * (head_dim // 3)
132
+ if self.spatial_width % 2 != 0:
133
+ raise ValueError(f'attention_head_dim={head_dim} gives an odd spatial RoPE width {self.spatial_width}.')
134
+ self.action_rope_angle = nn.Parameter(torch.zeros(self.spatial_width // 2))
135
+
136
+ self.query_norm = nn.LayerNorm(self.input_dim)
137
+ self.outputs = GaussianActionHead(
138
+ input_dim=self.input_dim,
139
+ latent_dim=self.latent_dim,
140
+ logvar_min=float(logvar_min),
141
+ logvar_max=float(logvar_max),
142
+ )
143
+
144
+ def spatial_rope_columns(self, dtype: torch.dtype) -> tuple[torch.Tensor, torch.Tensor]:
145
+ """``(cos, sin)`` of width ``spatial_width``, laid out like Wan's own RoPE buffer."""
146
+ angle = self.action_rope_angle.float()
147
+ cos = torch.cos(angle).repeat_interleave(2).to(dtype)
148
+ sin = torch.sin(angle).repeat_interleave(2).to(dtype)
149
+ return cos, sin
150
+
151
+ def transition_features(self, action_tokens: torch.Tensor) -> torch.Tensor:
152
+ """Per-frame query tokens ``[B, F, D]`` to per-transition features ``[B, F-1, D]``.
153
+
154
+ Query ``t`` has read both frames of transition ``t -> t+1``, so it is the
155
+ transition feature directly.
156
+ """
157
+ if action_tokens.ndim != 3:
158
+ raise ValueError(f'Expected per-frame action tokens [B,F,D], got {tuple(action_tokens.shape)}.')
159
+ if action_tokens.shape[1] < 2:
160
+ raise ValueError(f'Need >= 2 latent frames to form a transition, got {action_tokens.shape[1]}.')
161
+ if action_tokens.shape[-1] != self.input_dim:
162
+ raise ValueError(f'Expected width {self.input_dim}, got {action_tokens.shape[-1]}.')
163
+ return self.query_norm(action_tokens)[:, :-1]
164
+
165
+ def forward(self, action_tokens: torch.Tensor) -> dict[str, torch.Tensor]:
166
+ return self.outputs(self.transition_features(action_tokens))
167
+
168
+
169
+ @ACTION_ENCODER_REGISTRY.register()
170
+ class WanDiTActionEncoder(WanTransformer3DModel):
171
+ """Wan DiT trunk that reads one latent action per latent transition."""
172
+
173
+ def setup_readout(
174
+ self,
175
+ latent_dim: int = 32,
176
+ query_init_std: float = 0.02,
177
+ logvar_min: float = -10.0,
178
+ logvar_max: float = 10.0,
179
+ ) -> None:
180
+ """Attach the readout and the masked attention. Call before PEFT."""
181
+ inner_dim = int(self.config.num_attention_heads * self.config.attention_head_dim)
182
+ self.latent_action_dim = int(latent_dim)
183
+ self.idm_head = InSequenceReadout(
184
+ input_dim=inner_dim,
185
+ latent_dim=int(latent_dim),
186
+ attention_head_dim=int(self.config.attention_head_dim),
187
+ logvar_min=float(logvar_min),
188
+ logvar_max=float(logvar_max),
189
+ query_init_std=float(query_init_std),
190
+ )
191
+ install_flex_attention(self.blocks, PaddedFlexAttnProcessor)
192
+ verify_flex_attention(self.blocks, PaddedFlexAttnProcessor, label='action encoder')
193
+
194
+ @staticmethod
195
+ def in_sequence_mask_mod(num_frames: int, tokens_per_frame: int, device: torch.device):
196
+ """Token predicate for the interleaved ``[video tokens | 1 query]`` per-frame layout.
197
+
198
+ Returns ``(mask_mod, real_seq_len, padded_seq_len)``; split out so the
199
+ predicate can be checked on CPU without a flex-attention kernel.
200
+ """
201
+ per_frame = int(tokens_per_frame) + 1
202
+ real_seq_len = int(num_frames) * per_frame
203
+ padded_seq_len = padded_length(real_seq_len)
204
+ position = torch.arange(padded_seq_len, device=device)
205
+ frame_index = position // per_frame
206
+ is_action = (position % per_frame) >= int(tokens_per_frame)
207
+
208
+ def mask_mod(b, h, q_idx, kv_idx):
209
+ q_frame = frame_index[q_idx]
210
+ kv_frame = frame_index[kv_idx]
211
+ q_is_action = is_action[q_idx]
212
+ kv_is_video = ~is_action[kv_idx]
213
+ action_reach = (kv_frame == q_frame) | (kv_frame == q_frame + 1)
214
+ video_reach = kv_frame <= q_frame
215
+ allow = torch.where(q_is_action, kv_is_video & action_reach, kv_is_video & video_reach)
216
+ is_padding = (q_idx >= real_seq_len) | (kv_idx >= real_seq_len)
217
+ return allow & ~is_padding
218
+
219
+ return mask_mod, real_seq_len, padded_seq_len
220
+
221
+ @staticmethod
222
+ def dense_in_sequence_mask(mask_mod, real_seq_len: int, device) -> torch.Tensor:
223
+ """The predicate of :meth:`in_sequence_mask_mod` as a ``[S, S]`` boolean SDPA mask."""
224
+ position = torch.arange(int(real_seq_len), device=device)
225
+ zero = torch.zeros((), dtype=torch.long, device=device)
226
+ return mask_mod(zero, zero, position[:, None], position[None, :])
227
+
228
+ @staticmethod
229
+ def interleave_per_frame(
230
+ sequence: torch.Tensor, extra: torch.Tensor, num_frames: int, tokens_per_frame: int
231
+ ) -> torch.Tensor:
232
+ """Insert ``extra`` after each frame's block of tokens, on dim 1.
233
+
234
+ Works for hidden states ``[B, S, D]`` and RoPE frequencies alike, so the
235
+ two always agree about the layout.
236
+ """
237
+ batch_size = sequence.shape[0]
238
+ trailing = tuple(sequence.shape[2:])
239
+ expected = int(num_frames) * int(tokens_per_frame)
240
+ if sequence.shape[1] != expected:
241
+ raise ValueError(f'Expected {expected} = {num_frames}x{tokens_per_frame} tokens on dim 1, got {sequence.shape[1]}.')
242
+ blocks = sequence.reshape(batch_size, int(num_frames), int(tokens_per_frame), *trailing)
243
+ extra = extra.expand(batch_size, int(num_frames), 1, *trailing)
244
+ return torch.cat([blocks, extra], dim=2).flatten(1, 2)
245
+
246
+ @staticmethod
247
+ def extract_interleaved(sequence: torch.Tensor, num_frames: int, tokens_per_frame: int) -> torch.Tensor:
248
+ """Pull back out what :meth:`interleave_per_frame` put in."""
249
+ batch_size = sequence.shape[0]
250
+ trailing = tuple(sequence.shape[2:])
251
+ per_frame = int(tokens_per_frame) + 1
252
+ expected = int(num_frames) * per_frame
253
+ if sequence.shape[1] != expected:
254
+ raise ValueError(f'Expected {expected} = {num_frames}x{per_frame} tokens on dim 1, got {sequence.shape[1]}.')
255
+ blocks = sequence.reshape(batch_size, int(num_frames), per_frame, *trailing)
256
+ return blocks[:, :, int(tokens_per_frame)]
257
+
258
+ def build_in_sequence_rotary_emb(
259
+ self, rotary_emb: tuple[torch.Tensor, torch.Tensor], num_frames: int, tokens_per_frame: int
260
+ ) -> tuple[torch.Tensor, torch.Tensor]:
261
+ """Give each query token its frame's temporal RoPE and the learned spatial angle."""
262
+ head_dim = int(self.config.attention_head_dim)
263
+ split_sizes = [head_dim - 2 * (head_dim // 3), head_dim // 3, head_dim // 3]
264
+ freqs_cos, freqs_sin = rotary_emb
265
+ if freqs_cos.shape[-1] != head_dim:
266
+ raise RuntimeError(f'Expected RoPE frequencies of width {head_dim}, got {freqs_cos.shape[-1]}.')
267
+ temporal_cos = self.rope.freqs_cos.split(split_sizes, dim=1)[0][:num_frames]
268
+ temporal_sin = self.rope.freqs_sin.split(split_sizes, dim=1)[0][:num_frames]
269
+ spatial_cos, spatial_sin = self.idm_head.spatial_rope_columns(temporal_cos.dtype)
270
+ token_cos = torch.cat([temporal_cos, spatial_cos.unsqueeze(0).expand(num_frames, -1)], dim=-1).view(
271
+ 1, num_frames, 1, 1, head_dim
272
+ )
273
+ token_sin = torch.cat([temporal_sin, spatial_sin.unsqueeze(0).expand(num_frames, -1)], dim=-1).view(
274
+ 1, num_frames, 1, 1, head_dim
275
+ )
276
+ return (
277
+ self.interleave_per_frame(freqs_cos, token_cos.to(freqs_cos.dtype), num_frames, tokens_per_frame),
278
+ self.interleave_per_frame(freqs_sin, token_sin.to(freqs_sin.dtype), num_frames, tokens_per_frame),
279
+ )
280
+
281
+ def encode_query_tokens(
282
+ self,
283
+ hidden_states: torch.Tensor,
284
+ timestep: torch.Tensor,
285
+ encoder_hidden_states: torch.Tensor,
286
+ encoder_hidden_states_image: torch.Tensor | None = None,
287
+ ) -> torch.Tensor:
288
+ """Run the trunk with query tokens in the sequence; return them as ``[B, F, D]``."""
289
+ _, _, num_frames, height, width = hidden_states.shape
290
+ p_t, p_h, p_w = self.config.patch_size
291
+ if num_frames % p_t != 0 or height % p_h != 0 or width % p_w != 0:
292
+ raise ValueError(
293
+ f'Latent shape {(num_frames, height, width)} is not divisible by patch size {(p_t, p_h, p_w)}.'
294
+ )
295
+ post_patch_num_frames = num_frames // p_t
296
+ tokens_per_frame = (height // p_h) * (width // p_w)
297
+ if post_patch_num_frames < 2:
298
+ raise ValueError(f'Need >= 2 post-patch frames to have a transition, got {post_patch_num_frames}.')
299
+
300
+ rotary_emb = self.rope(hidden_states)
301
+ rotary_emb = self.build_in_sequence_rotary_emb(rotary_emb, post_patch_num_frames, tokens_per_frame)
302
+
303
+ hidden_states = self.patch_embedding(hidden_states)
304
+ hidden_states = hidden_states.flatten(2).transpose(1, 2).contiguous()
305
+ hidden_states = self.interleave_per_frame(
306
+ hidden_states,
307
+ self.idm_head.action_query.to(hidden_states.dtype).view(1, 1, 1, -1),
308
+ post_patch_num_frames,
309
+ tokens_per_frame,
310
+ )
311
+ sequence_length = hidden_states.shape[1]
312
+
313
+ if timestep.ndim == 2:
314
+ ts_seq_len = timestep.shape[1]
315
+ timestep = timestep.flatten()
316
+ else:
317
+ ts_seq_len = None
318
+
319
+ _, timestep_proj, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
320
+ timestep, encoder_hidden_states, encoder_hidden_states_image, timestep_seq_len=ts_seq_len
321
+ )
322
+ if ts_seq_len is not None:
323
+ if ts_seq_len != sequence_length:
324
+ if sequence_length % ts_seq_len != 0:
325
+ raise ValueError(f'Cannot expand {ts_seq_len} timestep embeddings to {sequence_length} tokens.')
326
+ timestep_proj = timestep_proj.repeat_interleave(sequence_length // ts_seq_len, dim=1)
327
+ timestep_proj = timestep_proj.unflatten(2, (6, -1))
328
+ else:
329
+ timestep_proj = timestep_proj.unflatten(1, (6, -1))
330
+
331
+ if encoder_hidden_states_image is not None:
332
+ encoder_hidden_states = torch.concat([encoder_hidden_states_image, encoder_hidden_states], dim=1)
333
+
334
+ # Left installed on return: under gradient checkpointing the blocks are
335
+ # re-run during backward and must see the same mask.
336
+ # A dense boolean mask through SDPA: the sequence is a few thousand
337
+ # tokens, so the mask is small, and unlike flex attention it needs no
338
+ # torch.compile (seconds per new shape, repeated in every fresh process).
339
+ mask_mod, real_seq_len, _ = self.in_sequence_mask_mod(
340
+ post_patch_num_frames, tokens_per_frame, hidden_states.device
341
+ )
342
+ dense_mask = cached_block_mask(
343
+ self, (int(post_patch_num_frames), int(tokens_per_frame), str(hidden_states.device)),
344
+ lambda: self.dense_in_sequence_mask(mask_mod, real_seq_len, hidden_states.device),
345
+ )
346
+ for block in self.blocks:
347
+ block.attn1.processor.block_mask = dense_mask
348
+ block.attn1.processor.padded_seq_len = real_seq_len
349
+
350
+ for block in self.blocks:
351
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
352
+ hidden_states = self._gradient_checkpointing_func(
353
+ block, hidden_states, encoder_hidden_states, timestep_proj, rotary_emb
354
+ )
355
+ else:
356
+ hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb)
357
+
358
+ return self.extract_interleaved(hidden_states, post_patch_num_frames, tokens_per_frame)
359
+
360
+ @apply_lora_scale('attention_kwargs')
361
+ def forward(
362
+ self,
363
+ hidden_states: torch.Tensor,
364
+ timestep: torch.LongTensor,
365
+ encoder_hidden_states: torch.Tensor,
366
+ r_timestep: torch.LongTensor | None = None,
367
+ encoder_hidden_states_image: torch.Tensor | None = None,
368
+ attention_kwargs: dict | None = None,
369
+ ) -> dict[str, torch.Tensor]:
370
+ """Latents ``[B, C, F, H, W]`` to ``{'action', 'action_mu', 'action_logvar'}`` with F-1 codes."""
371
+ del r_timestep, attention_kwargs
372
+ if not hasattr(self, 'idm_head'):
373
+ raise RuntimeError('setup_readout() must run after from_pretrained() and before encoding.')
374
+ tokens = self.encode_query_tokens(hidden_states, timestep, encoder_hidden_states, encoder_hidden_states_image)
375
+ return self.idm_head(tokens)
376
+
377
+
378
+ @register_action_encoder_spec('wan_dit')
379
+ class WanDiTSpec(ActionEncoderSpec):
380
+ """Build and run the Wan DiT action encoder.
381
+
382
+ This encoder's preprocessing is the VAE: it reads the clip as latents, which
383
+ the world model needs anyway, so it emits one code per latent transition and
384
+ consumes the whole clip rather than a window of RGB frames.
385
+ """
386
+
387
+ codes_per_transition = 1
388
+ action_ratio_cfg_key = 'action_compression_ratio'
389
+ legacy_contract_state_keys = ()
390
+ reads_pixels = False
391
+ window_rgb_frames = None
392
+ unsupported_action_cfg_keys = ()
393
+
394
+ def prepare_trainer(self, trainer, action_cfg):
395
+ trainer.readout_query_init_std = float((action_cfg or {}).get('query_init_std', 0.02))
396
+
397
+ # States written before this was fixed recorded the base model's local path,
398
+ # which changes from machine to machine and says nothing about the action space.
399
+ LEGACY_CONTRACT_FIELDS = ('model_name',)
400
+
401
+ def build_contract(self, trainer, idm_cfg):
402
+ return {
403
+ 'version': 1,
404
+ 'architecture': 'wan_dit',
405
+ 'action_compression_ratio': trainer.action_compression_ratio,
406
+ }
407
+
408
+ def build_encoder(self, trainer, idm_cfg, dtype):
409
+ """Wan DiT action encoder with the in-sequence readout, adapted and FSDP2-wrapped."""
410
+ encoder = ACTION_ENCODER_REGISTRY.get(idm_cfg['model_type']).from_pretrained(
411
+ idm_cfg['model_name'], subfolder='transformer', torch_dtype=dtype
412
+ )
413
+ # Before PEFT, so that PEFT sees the final module tree.
414
+ encoder.setup_readout(latent_dim=trainer.latent_action_dim, query_init_std=float(trainer.readout_query_init_std))
415
+
416
+ if 'lora_config' in idm_cfg:
417
+ lora_cfg = idm_cfg['lora_config']
418
+ target_modules = filter_learnable_module(encoder, lora_cfg['target_module_name'])
419
+ if not target_modules:
420
+ raise ValueError(f'Action encoder LoRA target selection matched no linear modules: {lora_cfg["target_module_name"]}.')
421
+ encoder = get_peft_model(
422
+ encoder,
423
+ LoraConfig(
424
+ r=int(lora_cfg['lora_rank']),
425
+ lora_alpha=int(lora_cfg['lora_alpha']),
426
+ target_modules=target_modules,
427
+ lora_dropout=0.0,
428
+ bias='none',
429
+ ),
430
+ adapter_name=LORA_ADAPTER_NAME,
431
+ )
432
+ # The readout is fully trainable already; an adapter on it would be
433
+ # stepped at two learning rates at once.
434
+ adapted_head = [
435
+ name for name, _ in encoder.named_parameters()
436
+ if 'idm_head' in name and any(key in name for key in LORA_STATE_KEYS)
437
+ ]
438
+ if adapted_head:
439
+ raise ValueError(
440
+ f'Action encoder LoRA reached {len(adapted_head)} readout parameters; restrict '
441
+ f'target_module_name to the trunk (e.g. ["blocks."]). First: {adapted_head[0]}.'
442
+ )
443
+
444
+ trainer.set_params_to_optimize(encoder, idm_cfg['param_names_to_optimize'], idm_cfg.get('param_names_to_exclude', []))
445
+ if idm_cfg.get('enable_gradient_checkpoint', False):
446
+ encoder.enable_gradient_checkpointing()
447
+ return fsdp2_wrap(encoder, transformer_block_clsname='WanTransformerBlock')
448
+
449
+ def validate_state_contract(self, state, expected, label):
450
+ """Check the contract when the state carries one.
451
+
452
+ States from the research code record no contract at all; their action
453
+ space is still identified, by the hash of the encoder's weights
454
+ (``action_space_id``), which world model training binds to. A missing
455
+ contract is therefore not an unknown origin and must not be rejected.
456
+ """
457
+ if state.get('idm_contract') is None and state.get('idm_backend') is None:
458
+ return
459
+ contract = state.get('idm_contract')
460
+ if isinstance(contract, dict):
461
+ contract = {key: value for key, value in contract.items() if key not in self.LEGACY_CONTRACT_FIELDS}
462
+ state = {**state, 'idm_contract': contract}
463
+ super().validate_state_contract(state, expected, label)
464
+
465
+ def encode(self, encoder, *, latents=None, pixel_values=None, prompt_embeds=None):
466
+ """Run the encoder on clean latents at timestep 0."""
467
+ del pixel_values # this encoder's preprocessing is the VAE the caller already ran
468
+ timestep = torch.zeros(latents.shape[:1] + latents.shape[2:3], device=latents.device, dtype=torch.float32)
469
+ outputs = encoder(
470
+ hidden_states=latents,
471
+ timestep=timestep,
472
+ encoder_hidden_states=prompt_embeds,
473
+ r_timestep=timestep,
474
+ )
475
+ if not isinstance(outputs, dict) or 'action' not in outputs:
476
+ raise RuntimeError(f'The action encoder did not return an action dict; got {type(outputs)}.')
477
+ return outputs
O2LaF/o2laf/assets/prompt_embeds/wan2.2-ti2v-5b__a_video.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:17308dd8de3fe39bf00cb5d4da0e0b26d94d6790fe245b3143fe4ba6da7972f6
3
+ size 4194512
O2LaF/o2laf/inference/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Inference: load a released model and generate video from actions."""
2
+
3
+ from o2laf.inference.sampling import ActionGuidance
4
+
5
+ __all__ = ['ActionGuidance']
O2LaF/o2laf/inference/action_library.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Named atomic actions shipped with a model.
2
+
3
+ A library is a ``<name>.json`` record and a ``<name>.safetensors`` file of
4
+ arrays in the model's ``action_library/`` directory. Each action is one group of
5
+ ``codes_per_transition`` codes, meant to be repeated across every transition of
6
+ a generation ("walk forward", "turn left", ...).
7
+
8
+ A library is bound to the action space it was extracted in, and refuses to load
9
+ into a model whose action encoder defines a different one: the same code means
10
+ a different motion under a different encoder.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ import torch
21
+ from safetensors.torch import load_file
22
+
23
+ LIBRARY_SCHEMA = 'o2laf_atomic_action_library_v1'
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class AtomicAction:
28
+ name: str
29
+ values: torch.Tensor # [codes_per_transition, action_dim]
30
+ support: int | None
31
+ metadata: dict[str, Any]
32
+
33
+
34
+ class AtomicActionLibrary:
35
+ """The atomic actions of one library, checked against the model they drive."""
36
+
37
+ def __init__(self, metadata_path: str | Path, *, action_space_id: str, action_dim: int, codes_per_transition: int):
38
+ metadata_path = Path(metadata_path)
39
+ metadata = json.loads(metadata_path.read_text(encoding='utf-8'))
40
+ if metadata.get('schema_version') != LIBRARY_SCHEMA:
41
+ raise ValueError(f'{metadata_path} has schema {metadata.get("schema_version")!r}, not {LIBRARY_SCHEMA!r}.')
42
+ if metadata.get('action_space_id') != action_space_id:
43
+ raise RuntimeError(
44
+ f'{metadata_path} was extracted in action space {metadata.get("action_space_id")}, '
45
+ f'but this model is {action_space_id}.'
46
+ )
47
+ arrays = load_file(str(metadata_path.with_name(metadata['weights'])))
48
+ names = list(metadata['names'])
49
+ actions = arrays['actions'].float()
50
+ if len(set(names)) != len(names):
51
+ raise ValueError(f'{metadata_path} repeats action names.')
52
+ if actions.ndim == 2:
53
+ actions = actions[:, None, :]
54
+ expected = (len(names), int(codes_per_transition), int(action_dim))
55
+ if tuple(actions.shape) != expected:
56
+ raise ValueError(f'{metadata_path} actions are {tuple(actions.shape)}, expected {expected}.')
57
+ if not torch.isfinite(actions).all():
58
+ raise ValueError(f'{metadata_path} actions contain NaN or infinity.')
59
+ support = arrays.get('support')
60
+ classes = {entry['name']: entry for entry in metadata.get('classes', []) if isinstance(entry, dict)}
61
+ self.actions = {
62
+ name: AtomicAction(
63
+ name=name,
64
+ values=actions[index].clone(),
65
+ support=int(support[index]) if support is not None else None,
66
+ metadata=classes.get(name, {}),
67
+ )
68
+ for index, name in enumerate(names)
69
+ }
70
+ self.metadata = metadata
71
+ self.metadata_path = metadata_path
72
+ self.action_dim = int(action_dim)
73
+ self.codes_per_transition = int(codes_per_transition)
74
+
75
+ @classmethod
76
+ def from_model_dir(cls, model_dir: str | Path, index: dict[str, Any], name: str | None = None) -> 'AtomicActionLibrary':
77
+ """A library shipped with a model: ``name``, or the first one its index lists.
78
+
79
+ Needs only the index and the library files, not the model's weights.
80
+ """
81
+ available = library_names(index)
82
+ if not available:
83
+ raise FileNotFoundError(f'{model_dir} ships no action library.')
84
+ name = name or available[0]
85
+ if name not in available:
86
+ raise KeyError(f'Unknown action library {name!r}; this model ships {available}.')
87
+ return cls(
88
+ Path(model_dir) / index['action_library']['directory'] / f'{name}.json',
89
+ action_space_id=index['action_space_id'],
90
+ action_dim=int(index['action_dim']),
91
+ codes_per_transition=int(index['codes_per_transition']),
92
+ )
93
+
94
+ @classmethod
95
+ def from_pipeline(cls, pipeline, name: str | None = None) -> 'AtomicActionLibrary':
96
+ """A library shipped with ``pipeline``'s model; see :meth:`from_model_dir`."""
97
+ return cls.from_model_dir(pipeline.model_dir, pipeline.model_index, name)
98
+
99
+ @property
100
+ def name(self) -> str:
101
+ return self.metadata_path.stem
102
+
103
+ def names(self) -> tuple[str, ...]:
104
+ return tuple(self.actions)
105
+
106
+ def get(self, name: str) -> AtomicAction:
107
+ if name not in self.actions:
108
+ raise KeyError(f'Unknown action {name!r}; available: {list(self.actions)}.')
109
+ return self.actions[name]
110
+
111
+ def tensor(self, name: str, *, groups: int, device, dtype) -> torch.Tensor:
112
+ """``[1, groups * codes_per_transition, action_dim]``: one action repeated over every transition."""
113
+ if groups < 1:
114
+ raise ValueError('groups must be positive.')
115
+ values = self.get(name).values.repeat(groups, 1)
116
+ return values.reshape(1, groups * self.codes_per_transition, self.action_dim).to(device=device, dtype=dtype)
117
+
118
+
119
+ def library_names(index: dict[str, Any]) -> list[str]:
120
+ """The action libraries a model's index lists, in order; the first is the default."""
121
+ entry = index.get('action_library') or {}
122
+ return list(entry.get('libraries', ()))
O2LaF/o2laf/inference/attention.py ADDED
@@ -0,0 +1,735 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Raw pairwise action-query attention extraction and visualisation for Wan DiT encoders.
2
+
3
+ During a Wan DiT latent action encoder forward pass, each transition ``t -> t+1``
4
+ has one interleaved action query token ``a_t`` that attends exclusively to the
5
+ video tokens of latent frames ``t`` (source) and ``t+1`` (target).
6
+
7
+ This module captures the post-projection, post-QK-norm, post-RoPE query and key
8
+ tensors at a requested transformer block (1-indexed, ``1..30``) and recomputes
9
+ the exact joint-softmax attention distribution over all ``2 * H * W`` video keys
10
+ for a single head (0-indexed, ``0..23``). Source and target share one softmax
11
+ denominator (``source_mass + target_mass = 1``) and one video-global colour
12
+ scale; no head/block aggregation, conditional normalisation, thresholding,
13
+ debiasing, Gaussian blur, or temporal smoothing is applied.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import gc
19
+ import math
20
+ from contextlib import contextmanager
21
+ from dataclasses import dataclass
22
+ from pathlib import Path
23
+ from typing import Any, Sequence
24
+
25
+ import cv2
26
+ import imageio.v2 as imageio
27
+ import numpy as np
28
+ import torch
29
+ import torch.nn.functional as F
30
+ from diffusers.models import AutoencoderKLWan
31
+ from PIL import Image, ImageDraw, ImageFont
32
+
33
+ from o2laf.action_encoders.base import unwrap_peft
34
+ from o2laf.action_encoders.wan_dit import PaddedFlexAttnProcessor, WanDiTActionEncoder
35
+ from o2laf.inference import hub
36
+ from o2laf.inference.pipeline import _build_action_encoder
37
+ from o2laf.inference.prompts import fixed_prompt_embeds
38
+ from o2laf.utils.file_util import write_json_atomic
39
+ from o2laf.utils.video_util import VideoLoader, select_frame_indices
40
+
41
+ DEFAULT_BLOCK = 30
42
+ DEFAULT_HEAD = 11
43
+ DEFAULT_WINDOW_FRAMES = 121
44
+ DEFAULT_PERCENTILE = 99.0
45
+ DEFAULT_GAMMA = 0.8
46
+ DEFAULT_ALPHA = 0.6
47
+ DEFAULT_ALPHA_POWER = 1.1
48
+
49
+ GAP_WIDTH = 8
50
+ CAPTION_HEIGHT = 58
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class AttentionRenderConfig:
55
+ """Display parameters for side-by-side source|target attention overlays."""
56
+
57
+ percentile: float = DEFAULT_PERCENTILE
58
+ gamma: float = DEFAULT_GAMMA
59
+ alpha: float = DEFAULT_ALPHA
60
+ alpha_power: float = DEFAULT_ALPHA_POWER
61
+
62
+ def __post_init__(self) -> None:
63
+ if not 0.0 < float(self.percentile) <= 100.0:
64
+ raise ValueError(f'percentile must lie in (0, 100], got {self.percentile}.')
65
+ if float(self.gamma) <= 0.0:
66
+ raise ValueError(f'gamma must be positive, got {self.gamma}.')
67
+ if not 0.0 <= float(self.alpha) <= 1.0:
68
+ raise ValueError(f'alpha must lie in [0, 1], got {self.alpha}.')
69
+ if float(self.alpha_power) <= 0.0:
70
+ raise ValueError(f'alpha_power must be positive, got {self.alpha_power}.')
71
+
72
+ def to_dict(self) -> dict[str, Any]:
73
+ return {
74
+ 'cmap': 'turbo',
75
+ 'interpolation': 'bicubic',
76
+ 'percentile': float(self.percentile),
77
+ 'gamma': float(self.gamma),
78
+ 'alpha': float(self.alpha),
79
+ 'alpha_power': float(self.alpha_power),
80
+ 'gaussian_blur': False,
81
+ }
82
+
83
+
84
+ @dataclass
85
+ class AttentionResult:
86
+ """Extracted raw pairwise attention maps and aligned RGB transition endpoints."""
87
+
88
+ maps: np.ndarray # [T, 2, H, W] float32 joint-softmax probabilities
89
+ source_frames: np.ndarray # [T, H_rgb, W_rgb, 3] uint8
90
+ target_frames: np.ndarray # [T, H_rgb, W_rgb, 3] uint8
91
+ source_frame_indices: np.ndarray # [T] int64 native source-video indices
92
+ target_frame_indices: np.ndarray # [T] int64 native source-video indices
93
+ block: int
94
+ head: int
95
+ target_fps: float
96
+ window_frames: int
97
+ windows: list[dict[str, Any]]
98
+
99
+
100
+ def _resample_indices(total_frames: int, source_fps: float, target_fps: float) -> list[int]:
101
+ if total_frames < 1:
102
+ return []
103
+ if source_fps <= 0 or target_fps <= 0:
104
+ raise ValueError('source_fps and target_fps must be positive.')
105
+ if source_fps <= target_fps + 1e-6:
106
+ return list(range(total_frames))
107
+ return select_frame_indices(total_frames, source_fps, target_fps)
108
+
109
+
110
+ def adjacent_temporal_windows(
111
+ num_frames: int,
112
+ *,
113
+ window_frames: int = DEFAULT_WINDOW_FRAMES,
114
+ temporal_compression_ratio: int = 4,
115
+ ) -> list[tuple[int, int]]:
116
+ """Adjacent windows sharing one endpoint; each length is ``1 mod ratio``."""
117
+ ratio = int(temporal_compression_ratio)
118
+ window = int(window_frames)
119
+ if ratio < 1:
120
+ raise ValueError('temporal_compression_ratio must be positive.')
121
+ if window < 1 + ratio or (window - 1) % ratio:
122
+ raise ValueError(f'window_frames must be {ratio}k+1 with k >= 1, got {window}.')
123
+ windows = []
124
+ start = 0
125
+ while start + ratio < int(num_frames):
126
+ available = int(num_frames) - start
127
+ length = min(window, 1 + ratio * ((available - 1) // ratio))
128
+ if length < 1 + ratio:
129
+ break
130
+ windows.append((start, length))
131
+ start += window - 1
132
+ return windows
133
+
134
+
135
+ def pairwise_attention_from_qk(
136
+ query: torch.Tensor,
137
+ key: torch.Tensor,
138
+ num_frames: int,
139
+ *,
140
+ grid_height: int,
141
+ grid_width: int,
142
+ heads: Sequence[int] | None = None,
143
+ ) -> torch.Tensor:
144
+ """Exact pairwise action-query attention over the complete ``2*H*W`` key set.
145
+
146
+ Args:
147
+ query, key: Post-projection, post-QK-norm, post-RoPE tensors shaped
148
+ ``[B, num_heads, padded_seq_len, head_dim]``.
149
+ num_frames: Number of latent frames ``F`` (produces ``F - 1`` transitions).
150
+ grid_height, grid_width: Post-patch spatial token grid dimensions.
151
+ heads: Optional subset of 0-indexed attention heads to compute.
152
+
153
+ Returns:
154
+ Float32 tensor ``[B, F - 1, H_sel, 2, grid_height, grid_width]`` where
155
+ axis 3 is ``(source, target)`` and sums jointly to 1 per transition/head.
156
+ """
157
+ if query.ndim != 4 or key.ndim != 4 or query.shape != key.shape:
158
+ raise ValueError(f'query and key must share shape [B,H,S,D], got {tuple(query.shape)} and {tuple(key.shape)}.')
159
+ num_frames = int(num_frames)
160
+ if num_frames < 2:
161
+ raise ValueError(f'pairwise attention needs >= 2 latent frames, got {num_frames}.')
162
+ grid_height, grid_width = int(grid_height), int(grid_width)
163
+ tokens_per_frame = grid_height * grid_width
164
+ per_frame = tokens_per_frame + 1
165
+ real_length = num_frames * per_frame
166
+ if query.shape[2] < real_length:
167
+ raise ValueError(f'q/k sequence length {query.shape[2]} is shorter than {real_length}.')
168
+
169
+ if heads is not None:
170
+ num_heads = int(query.shape[1])
171
+ head_indices = [int(h) for h in heads]
172
+ invalid = [h for h in head_indices if h < 0 or h >= num_heads]
173
+ if invalid:
174
+ raise ValueError(f'Head indices must lie in [0, {num_heads - 1}], got {invalid}.')
175
+ query = query[:, head_indices]
176
+ key = key[:, head_indices]
177
+
178
+ scale = 1.0 / math.sqrt(query.shape[-1])
179
+ maps = []
180
+ for transition in range(num_frames - 1):
181
+ source_begin = transition * per_frame
182
+ source_span = slice(source_begin, source_begin + tokens_per_frame)
183
+ action_index = source_begin + tokens_per_frame
184
+ target_begin = (transition + 1) * per_frame
185
+ target_span = slice(target_begin, target_begin + tokens_per_frame)
186
+
187
+ action = query[:, :, action_index, :].float()
188
+ video = torch.cat([key[:, :, source_span, :], key[:, :, target_span, :]], dim=2).float()
189
+ logits = torch.einsum('bhd,bhnd->bhn', action, video) * scale
190
+ weights = torch.softmax(logits, dim=-1)
191
+ maps.append(weights.reshape(query.shape[0], query.shape[1], 2, grid_height, grid_width))
192
+ return torch.stack(maps, dim=1)
193
+
194
+
195
+ class _CapturingPaddedFlexAttnProcessor(PaddedFlexAttnProcessor):
196
+ """Capture exact pairwise attention at ``_attend`` without altering outputs."""
197
+
198
+ def __init__(
199
+ self,
200
+ *,
201
+ block: int,
202
+ num_frames: int,
203
+ grid_height: int,
204
+ grid_width: int,
205
+ heads: tuple[int, ...] | None,
206
+ sink: dict[int, torch.Tensor],
207
+ ) -> None:
208
+ super().__init__()
209
+ self._block = int(block)
210
+ self._num_frames = int(num_frames)
211
+ self._grid_height = int(grid_height)
212
+ self._grid_width = int(grid_width)
213
+ self._heads = heads
214
+ self._sink = sink
215
+
216
+ def _attend(self, query, key, value, attention_mask):
217
+ self._sink[self._block] = (
218
+ pairwise_attention_from_qk(
219
+ query,
220
+ key,
221
+ self._num_frames,
222
+ grid_height=self._grid_height,
223
+ grid_width=self._grid_width,
224
+ heads=self._heads,
225
+ )
226
+ .detach()
227
+ .cpu()
228
+ )
229
+ return super()._attend(query, key, value, attention_mask)
230
+
231
+
232
+ @contextmanager
233
+ def capture_pairwise_attention(
234
+ action_encoder: torch.nn.Module,
235
+ *,
236
+ blocks: Sequence[int],
237
+ num_frames: int,
238
+ grid_height: int,
239
+ grid_width: int,
240
+ heads: Sequence[int] | None = None,
241
+ ):
242
+ """Temporarily instrument selected 1-indexed blocks of a ``WanDiTActionEncoder``."""
243
+ base = unwrap_peft(action_encoder)
244
+ if not isinstance(base, WanDiTActionEncoder):
245
+ raise TypeError(
246
+ f'Pairwise action-query attention is only defined for WanDiTActionEncoder, got {type(base).__name__}.'
247
+ )
248
+ num_blocks = len(base.blocks)
249
+ requested = tuple(sorted(set(int(block) for block in blocks)))
250
+ if not requested or any(block < 1 or block > num_blocks for block in requested):
251
+ raise ValueError(f'blocks must lie in [1, {num_blocks}], got {list(blocks)}.')
252
+ head_tuple = tuple(int(h) for h in heads) if heads is not None else None
253
+ if head_tuple is not None:
254
+ num_heads = int(base.config.num_attention_heads)
255
+ if not head_tuple or any(h < 0 or h >= num_heads for h in head_tuple):
256
+ raise ValueError(f'heads must lie in [0, {num_heads - 1}], got {list(head_tuple)}.')
257
+
258
+ captured: dict[int, torch.Tensor] = {}
259
+ originals: dict[int, Any] = {}
260
+ for block in requested:
261
+ attn = base.blocks[block - 1].attn1
262
+ originals[block] = attn.processor
263
+ attn.set_processor(
264
+ _CapturingPaddedFlexAttnProcessor(
265
+ block=block,
266
+ num_frames=num_frames,
267
+ grid_height=grid_height,
268
+ grid_width=grid_width,
269
+ heads=head_tuple,
270
+ sink=captured,
271
+ )
272
+ )
273
+ try:
274
+ yield captured
275
+ finally:
276
+ for block, processor in originals.items():
277
+ base.blocks[block - 1].attn1.set_processor(processor)
278
+
279
+
280
+ def head_clip_scale(maps: np.ndarray, percentile: float = DEFAULT_PERCENTILE) -> float:
281
+ """One shared colour scale over ``[T, 2, H, W]`` (all frames, both sides)."""
282
+ scale = float(np.percentile(np.asarray(maps, dtype=np.float32), float(percentile)))
283
+ return max(scale, 1e-12)
284
+
285
+
286
+ def render_attention_overlay(
287
+ frame: np.ndarray,
288
+ attention: np.ndarray,
289
+ *,
290
+ scale: float,
291
+ config: AttentionRenderConfig = AttentionRenderConfig(),
292
+ ) -> np.ndarray:
293
+ """Overlay a single ``[H, W]`` attention map onto an RGB uint8 frame."""
294
+ normalized = np.clip(np.asarray(attention, dtype=np.float32) / float(scale), 0.0, 1.0)
295
+ normalized = cv2.resize(normalized, (frame.shape[1], frame.shape[0]), interpolation=cv2.INTER_CUBIC)
296
+ normalized = np.clip(normalized, 0.0, 1.0)
297
+ heatmap = np.power(normalized, float(config.gamma))
298
+ colour = cv2.applyColorMap(np.round(heatmap * 255.0).astype(np.uint8), cv2.COLORMAP_TURBO)
299
+ colour = cv2.cvtColor(colour, cv2.COLOR_BGR2RGB).astype(np.float32)
300
+ opacity = (float(config.alpha) * np.power(heatmap, float(config.alpha_power)))[..., None]
301
+ blended = (1.0 - opacity) * frame.astype(np.float32) + opacity * colour
302
+ return np.clip(blended, 0.0, 255.0).round().astype(np.uint8)
303
+
304
+
305
+ def _load_font(size: int, *, bold: bool = False) -> ImageFont.ImageFont:
306
+ name = 'DejaVuSans-Bold.ttf' if bold else 'DejaVuSans.ttf'
307
+ for directory in (
308
+ Path('/usr/share/fonts/truetype/dejavu'),
309
+ Path('/usr/share/fonts/dejavu'),
310
+ Path('/Library/Fonts'),
311
+ ):
312
+ candidate = directory / name
313
+ if candidate.is_file():
314
+ try:
315
+ return ImageFont.truetype(str(candidate), size)
316
+ except OSError:
317
+ pass
318
+ try:
319
+ return ImageFont.load_default(size=size)
320
+ except TypeError:
321
+ return ImageFont.load_default()
322
+
323
+
324
+ def render_caption_bar(
325
+ *,
326
+ panel_width: int,
327
+ block: int,
328
+ head: int,
329
+ source_mass: float,
330
+ target_mass: float,
331
+ source_index: int,
332
+ target_index: int,
333
+ transition: int,
334
+ label_font: ImageFont.ImageFont | None = None,
335
+ small_font: ImageFont.ImageFont | None = None,
336
+ ) -> np.ndarray:
337
+ """Caption strip placed below the side-by-side SOURCE | TARGET panels."""
338
+ label_font = label_font or _load_font(20, bold=True)
339
+ small_font = small_font or _load_font(16)
340
+ width = 2 * int(panel_width) + GAP_WIDTH
341
+ image = Image.new('RGB', (width, CAPTION_HEIGHT), (20, 22, 26))
342
+ draw = ImageDraw.Draw(image)
343
+ entries = (
344
+ (
345
+ 0,
346
+ f'SOURCE | block {block:02d} head {head:02d} | mass {source_mass:.1%}',
347
+ f'frame {source_index} | transition {transition}',
348
+ ),
349
+ (
350
+ int(panel_width) + GAP_WIDTH,
351
+ f'TARGET | block {block:02d} head {head:02d} | mass {target_mass:.1%}',
352
+ f'frame {target_index} | transition {transition}',
353
+ ),
354
+ )
355
+ for x, title, subtitle in entries:
356
+ draw.text((x + 10, 6), title, fill=(247, 247, 247), font=label_font)
357
+ draw.text((x + 10, 34), subtitle, fill=(185, 190, 198), font=small_font)
358
+ draw.rectangle((int(panel_width), 0, int(panel_width) + GAP_WIDTH - 1, image.height), fill=(238, 238, 238))
359
+ return np.asarray(image)
360
+
361
+
362
+ def render_attention_video(
363
+ result: AttentionResult,
364
+ output_path: str | Path,
365
+ *,
366
+ fps: float | None = None,
367
+ config: AttentionRenderConfig = AttentionRenderConfig(),
368
+ ) -> dict[str, Any]:
369
+ """Render side-by-side SOURCE | TARGET raw attention MP4 and return summary stats."""
370
+ output_path = Path(output_path)
371
+ output_path.parent.mkdir(parents=True, exist_ok=True)
372
+ render_fps = float(fps) if fps is not None else float(result.target_fps) / 4.0
373
+ if render_fps <= 0.0:
374
+ raise ValueError(f'output fps must be positive, got {render_fps}.')
375
+
376
+ scale = head_clip_scale(result.maps, percentile=config.percentile)
377
+ label_font = _load_font(20, bold=True)
378
+ small_font = _load_font(16)
379
+ gap = np.full((result.source_frames.shape[1], GAP_WIDTH, 3), 238, dtype=np.uint8)
380
+ source_masses = []
381
+ target_masses = []
382
+
383
+ writer = imageio.get_writer(
384
+ str(output_path),
385
+ fps=render_fps,
386
+ codec='libx264',
387
+ quality=8,
388
+ macro_block_size=1,
389
+ )
390
+ try:
391
+ for transition in range(len(result.maps)):
392
+ pair = result.maps[transition]
393
+ src_mass = float(pair[0].sum())
394
+ tgt_mass = float(pair[1].sum())
395
+ source_masses.append(src_mass)
396
+ target_masses.append(tgt_mass)
397
+ left = render_attention_overlay(result.source_frames[transition], pair[0], scale=scale, config=config)
398
+ right = render_attention_overlay(result.target_frames[transition], pair[1], scale=scale, config=config)
399
+ pixels = np.concatenate([left, gap, right], axis=1)
400
+ caption = render_caption_bar(
401
+ panel_width=left.shape[1],
402
+ block=result.block,
403
+ head=result.head,
404
+ source_mass=src_mass,
405
+ target_mass=tgt_mass,
406
+ source_index=int(result.source_frame_indices[transition]),
407
+ target_index=int(result.target_frame_indices[transition]),
408
+ transition=transition,
409
+ label_font=label_font,
410
+ small_font=small_font,
411
+ )
412
+ writer.append_data(np.concatenate([pixels, caption], axis=0))
413
+ finally:
414
+ writer.close()
415
+
416
+ return {
417
+ 'output': str(output_path.resolve()),
418
+ 'output_fps': render_fps,
419
+ 'num_transitions': int(len(result.maps)),
420
+ 'head_clip_scale': scale,
421
+ 'source_mass_mean': float(np.mean(source_masses)),
422
+ 'target_mass_mean': float(np.mean(target_masses)),
423
+ 'vis_config': config.to_dict(),
424
+ }
425
+
426
+
427
+ def save_attention_npz(result: AttentionResult, path: str | Path) -> Path:
428
+ """Save raw attention probabilities and aligned RGB frames as a compressed ``.npz``."""
429
+ path = Path(path)
430
+ path.parent.mkdir(parents=True, exist_ok=True)
431
+ np.savez_compressed(
432
+ path,
433
+ attention=result.maps.astype(np.float32),
434
+ source_rgb=result.source_frames.astype(np.uint8),
435
+ target_rgb=result.target_frames.astype(np.uint8),
436
+ source_frame_indices=result.source_frame_indices.astype(np.int64),
437
+ target_frame_indices=result.target_frame_indices.astype(np.int64),
438
+ block=np.asarray(int(result.block), dtype=np.int64),
439
+ head=np.asarray(int(result.head), dtype=np.int64),
440
+ target_fps=np.asarray(float(result.target_fps), dtype=np.float32),
441
+ )
442
+ return path
443
+
444
+
445
+ @dataclass
446
+ class ActionAttentionExtractor:
447
+ """Encoder-only loader for extracting raw pairwise attention without loading a world model."""
448
+
449
+ model_dir: Path
450
+ model_index: dict[str, Any]
451
+ action_space_id: str
452
+ action_encoder: torch.nn.Module
453
+ vae: AutoencoderKLWan
454
+ prompt_embeddings: torch.Tensor
455
+ device: torch.device
456
+ dtype: torch.dtype
457
+ height: int
458
+ width: int
459
+ fps: int
460
+ temporal_compression_ratio: int
461
+ action_encoder_step: int
462
+
463
+ @classmethod
464
+ def from_pretrained(
465
+ cls,
466
+ pretrained_model_name_or_path: str | Path,
467
+ *,
468
+ base_model: str | Path | None = None,
469
+ device: str | torch.device = 'cuda',
470
+ dtype: torch.dtype = torch.bfloat16,
471
+ revision: str | None = None,
472
+ cache_dir: str | Path | None = None,
473
+ local_files_only: bool = False,
474
+ token: str | bool | None = None,
475
+ verify_action_space: bool = False,
476
+ ) -> 'ActionAttentionExtractor':
477
+ """Load only the Wan DiT action encoder and VAE from a Hub model or local directory."""
478
+ device = torch.device(device)
479
+ root = hub.resolve_model_dir(
480
+ pretrained_model_name_or_path,
481
+ fetch='action_encoder',
482
+ revision=revision,
483
+ cache_dir=cache_dir,
484
+ local_files_only=local_files_only,
485
+ token=token,
486
+ )
487
+ index = hub.read_model_index(root)
488
+ encoder_at = index['action_encoder']
489
+ encoder_config = hub.load_part_config(root, encoder_at)
490
+ encoder_name = str(encoder_config.get('action_encoder'))
491
+ if encoder_name != 'wan_dit':
492
+ raise ValueError(
493
+ f'Action-query attention visualisation requires a wan_dit latent action encoder, '
494
+ f'but {pretrained_model_name_or_path} uses {encoder_name!r}.'
495
+ )
496
+ action_space_id = str(index['action_space_id'])
497
+ if encoder_config.get('action_space_id') != action_space_id:
498
+ raise RuntimeError(
499
+ f'The action encoder was trained in action space {encoder_config.get("action_space_id")}, '
500
+ f'but the model index records {action_space_id}.'
501
+ )
502
+ encoder_state = hub.load_part_state(root, encoder_at)
503
+ if verify_action_space:
504
+ actual = 'sha256:' + hub.tensor_content_sha256(encoder_state)
505
+ if actual != action_space_id:
506
+ raise RuntimeError(f'The action encoder weights hash to {actual}, not the recorded {action_space_id}.')
507
+
508
+ base_model_path = str(base_model or index['base_model'])
509
+ base_kwargs = {'cache_dir': cache_dir, 'local_files_only': local_files_only, 'token': token}
510
+ prompt_embeddings = fixed_prompt_embeds(
511
+ base_model=index['base_model'],
512
+ prompt=index['fixed_prompt'],
513
+ base_model_path=base_model_path,
514
+ device=device,
515
+ dtype=dtype,
516
+ **base_kwargs,
517
+ )
518
+ vae = AutoencoderKLWan.from_pretrained(base_model_path, subfolder='vae', torch_dtype=dtype, **base_kwargs).to(device)
519
+ vae.requires_grad_(False)
520
+ vae.eval()
521
+ action_encoder = _build_action_encoder(encoder_state, encoder_config, base_model_path, device, dtype, **base_kwargs)
522
+ del encoder_state
523
+
524
+ mode_config = index['modes'].get('bidirectional') or next(iter(index['modes'].values()))
525
+ extractor = cls(
526
+ model_dir=root,
527
+ model_index=index,
528
+ action_space_id=action_space_id,
529
+ action_encoder=action_encoder,
530
+ vae=vae,
531
+ prompt_embeddings=prompt_embeddings,
532
+ device=device,
533
+ dtype=dtype,
534
+ height=int(mode_config['height']),
535
+ width=int(mode_config['width']),
536
+ fps=int(mode_config['fps']),
537
+ temporal_compression_ratio=int(index['temporal_compression_ratio']),
538
+ action_encoder_step=int(encoder_config['global_step']),
539
+ )
540
+ gc.collect()
541
+ return extractor
542
+
543
+ @classmethod
544
+ def from_pipeline(cls, pipeline) -> 'ActionAttentionExtractor':
545
+ """Reuse an already-loaded ``LatentActionPipeline`` without loading extra weights."""
546
+ base = unwrap_peft(pipeline.action_encoder)
547
+ if not isinstance(base, WanDiTActionEncoder):
548
+ raise ValueError(
549
+ f'Action-query attention visualisation requires a wan_dit latent action encoder, '
550
+ f'got {pipeline.action_encoder_name!r}.'
551
+ )
552
+ encoder_cfg = hub.load_part_config(pipeline.model_dir, pipeline.model_index['action_encoder'])
553
+ return cls(
554
+ model_dir=pipeline.model_dir,
555
+ model_index=pipeline.model_index,
556
+ action_space_id=pipeline.action_space_id,
557
+ action_encoder=pipeline.action_encoder,
558
+ vae=pipeline.vae,
559
+ prompt_embeddings=pipeline.prompt_embeddings,
560
+ device=pipeline.device,
561
+ dtype=pipeline.dtype,
562
+ height=pipeline.height,
563
+ width=pipeline.width,
564
+ fps=pipeline.fps,
565
+ temporal_compression_ratio=pipeline.temporal_compression_ratio,
566
+ action_encoder_step=int(encoder_cfg['global_step']),
567
+ )
568
+
569
+ @torch.no_grad()
570
+ def _encode_window(self, frames: np.ndarray) -> tuple[torch.Tensor, np.ndarray]:
571
+ tensor = torch.as_tensor(np.array(frames), dtype=torch.float32).permute(0, 3, 1, 2)
572
+ resized = F.interpolate(tensor, size=(self.height, self.width), mode='bilinear', align_corners=False, antialias=True)
573
+ endpoints = resized[::self.temporal_compression_ratio].round().clamp(0, 255).to(torch.uint8).permute(0, 2, 3, 1).numpy()
574
+
575
+ pixels = resized.div(255.0).sub_(0.5).div_(0.5).unsqueeze(0)
576
+ video = pixels.permute(0, 2, 1, 3, 4).contiguous().to(device=self.device, dtype=self.dtype)
577
+ moments = self.vae._encode(video)
578
+ mean, _ = torch.chunk(moments, 2, dim=1)
579
+ latent_mean = torch.as_tensor(self.vae.config.latents_mean, device=self.device, dtype=torch.float32).view(1, -1, 1, 1, 1)
580
+ latent_std = torch.as_tensor(self.vae.config.latents_std, device=self.device, dtype=torch.float32).view(1, -1, 1, 1, 1)
581
+ latents = ((mean.float() - latent_mean) / latent_std).to(self.dtype)
582
+ if endpoints.shape[0] != latents.shape[2]:
583
+ raise RuntimeError(f'RGB endpoint/latent mismatch: {endpoints.shape[0]} vs {latents.shape[2]}.')
584
+ return latents, endpoints
585
+
586
+ @torch.no_grad()
587
+ def extract(
588
+ self,
589
+ video_path: str | Path,
590
+ *,
591
+ block: int = DEFAULT_BLOCK,
592
+ head: int = DEFAULT_HEAD,
593
+ target_fps: float | None = None,
594
+ source_fps: float | None = None,
595
+ window_frames: int = DEFAULT_WINDOW_FRAMES,
596
+ ) -> AttentionResult:
597
+ """Extract raw pairwise attention ``[T, 2, H, W]`` across a full video."""
598
+ video_path = Path(video_path)
599
+ if not video_path.is_file():
600
+ raise FileNotFoundError(f'Video not found: {video_path}.')
601
+
602
+ base = unwrap_peft(self.action_encoder)
603
+ _, patch_h, patch_w = base.config.patch_size
604
+ effective_fps = float(target_fps) if target_fps is not None else float(self.fps)
605
+
606
+ with VideoLoader(str(video_path), name=str(video_path)) as loader:
607
+ native_fps = float(source_fps or loader.get_fps())
608
+ picks = _resample_indices(loader.get_frame_count(), native_fps, effective_fps)
609
+ windows = adjacent_temporal_windows(
610
+ len(picks),
611
+ window_frames=int(window_frames),
612
+ temporal_compression_ratio=self.temporal_compression_ratio,
613
+ )
614
+ if not windows:
615
+ raise ValueError(
616
+ f'{video_path} has only {len(picks)} frames at {effective_fps:g} fps; '
617
+ f'need at least {1 + self.temporal_compression_ratio} frames for one transition.'
618
+ )
619
+
620
+ source_frames: list[np.ndarray] = []
621
+ target_frames: list[np.ndarray] = []
622
+ source_indices: list[int] = []
623
+ target_indices: list[int] = []
624
+ attention_chunks: list[np.ndarray] = []
625
+ window_reports: list[dict[str, Any]] = []
626
+
627
+ for window_index, (start, length) in enumerate(windows):
628
+ indices = [picks[i] for i in range(start, start + length)]
629
+ decoded = loader.get_frames(indices)
630
+ latents, endpoints = self._encode_window(decoded)
631
+ num_latent_frames = int(latents.shape[2])
632
+ grid_height = int(latents.shape[3]) // int(patch_h)
633
+ grid_width = int(latents.shape[4]) // int(patch_w)
634
+ timestep = torch.zeros(1, num_latent_frames, device=self.device, dtype=torch.float32)
635
+
636
+ with capture_pairwise_attention(
637
+ self.action_encoder,
638
+ blocks=(int(block),),
639
+ num_frames=num_latent_frames,
640
+ grid_height=grid_height,
641
+ grid_width=grid_width,
642
+ heads=(int(head),),
643
+ ) as captured:
644
+ self.action_encoder(
645
+ hidden_states=latents,
646
+ timestep=timestep,
647
+ encoder_hidden_states=self.prompt_embeddings,
648
+ r_timestep=timestep,
649
+ )
650
+
651
+ endpoint_indices = indices[::self.temporal_compression_ratio]
652
+ if len(endpoint_indices) != num_latent_frames:
653
+ raise RuntimeError(f'{video_path.name} window {window_index}: endpoint/latent mismatch.')
654
+
655
+ # captured[block] is [1, F-1, 1, 2, H, W]; squeeze batch and single-head axes.
656
+ attention_chunks.append(captured[int(block)][0, :, 0].numpy().astype(np.float32))
657
+ source_frames.extend(endpoints[:-1])
658
+ target_frames.extend(endpoints[1:])
659
+ source_indices.extend(endpoint_indices[:-1])
660
+ target_indices.extend(endpoint_indices[1:])
661
+ window_reports.append({
662
+ 'window': window_index,
663
+ 'resampled_start': int(start),
664
+ 'rgb_frames': int(length),
665
+ 'latent_frames': num_latent_frames,
666
+ 'transitions': num_latent_frames - 1,
667
+ 'source_frame_span': [int(indices[0]), int(indices[-1])],
668
+ })
669
+ del decoded, latents
670
+ if self.device.type == 'cuda':
671
+ torch.cuda.empty_cache()
672
+
673
+ return AttentionResult(
674
+ maps=np.concatenate(attention_chunks, axis=0),
675
+ source_frames=np.stack(source_frames, axis=0),
676
+ target_frames=np.stack(target_frames, axis=0),
677
+ source_frame_indices=np.asarray(source_indices, dtype=np.int64),
678
+ target_frame_indices=np.asarray(target_indices, dtype=np.int64),
679
+ block=int(block),
680
+ head=int(head),
681
+ target_fps=effective_fps,
682
+ window_frames=int(window_frames),
683
+ windows=window_reports,
684
+ )
685
+
686
+ def visualize(
687
+ self,
688
+ video_path: str | Path,
689
+ output_path: str | Path,
690
+ *,
691
+ block: int = DEFAULT_BLOCK,
692
+ head: int = DEFAULT_HEAD,
693
+ target_fps: float | None = None,
694
+ source_fps: float | None = None,
695
+ output_fps: float | None = None,
696
+ window_frames: int = DEFAULT_WINDOW_FRAMES,
697
+ render_config: AttentionRenderConfig = AttentionRenderConfig(),
698
+ save_npz: str | Path | None = None,
699
+ ) -> dict[str, Any]:
700
+ """Extract attention, render the MP4, write its JSON manifest, and optionally save raw NPZ."""
701
+ video_path = Path(video_path)
702
+ output_path = Path(output_path)
703
+ result = self.extract(
704
+ video_path,
705
+ block=block,
706
+ head=head,
707
+ target_fps=target_fps,
708
+ source_fps=source_fps,
709
+ window_frames=window_frames,
710
+ )
711
+ render_summary = render_attention_video(result, output_path, fps=output_fps, config=render_config)
712
+ npz_path = save_attention_npz(result, save_npz) if save_npz is not None else None
713
+ manifest = {
714
+ 'schema_version': 'o2laf_attention_viz_v1',
715
+ 'model': str(self.model_dir),
716
+ 'action_space_id': self.action_space_id,
717
+ 'action_encoder_step': self.action_encoder_step,
718
+ 'video': str(video_path.resolve()),
719
+ 'block': result.block,
720
+ 'head': result.head,
721
+ 'target_fps': result.target_fps,
722
+ 'window_frames': result.window_frames,
723
+ 'windows': result.windows,
724
+ 'attention_semantics': {
725
+ 'raw_joint_softmax': True,
726
+ 'source_target_shared_denominator': True,
727
+ 'single_block_single_head': True,
728
+ 'normalization_scope': 'all frames, source and target, for this (block, head) clip',
729
+ },
730
+ **render_summary,
731
+ 'npz': str(npz_path.resolve()) if npz_path is not None else None,
732
+ }
733
+ manifest_path = output_path.with_suffix('.json')
734
+ write_json_atomic(manifest_path, manifest)
735
+ return {'manifest': manifest, 'manifest_path': manifest_path, 'npz_path': npz_path}
O2LaF/o2laf/inference/encoder_windows.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """How the action encoder covers a source video of any length.
2
+
3
+ The action encoder was trained on clips of one fixed length (41 RGB frames, 10
4
+ latent transitions). A source video is read in windows of that length, and only
5
+ the first half of each window's transitions is kept. The next window starts
6
+ where the kept transitions end, so the kept actions tile the video once, with
7
+ no gap and no overlap. Once fewer than a full window of frames remains, the
8
+ last window is shortened to just the transitions still needed.
9
+
10
+ Every window starts on the temporal grid of the VAE (4 RGB frames per latent),
11
+ so the RGB clock and the action clock stay aligned. Up to three trailing RGB
12
+ frames that do not complete a transition are dropped.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from dataclasses import dataclass
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class EncoderWindow:
22
+ """One action-encoder pass, and which of its transitions are kept."""
23
+
24
+ start_rgb_frame: int
25
+ num_rgb_frames: int
26
+ kept_transitions: int # the first ``kept_transitions`` of this window's transitions
27
+
28
+
29
+ def usable_transitions(num_rgb_frames: int, temporal_compression_ratio: int = 4) -> int:
30
+ """Latent transitions a clip of ``num_rgb_frames`` covers; trailing partial ones are dropped."""
31
+ if num_rgb_frames < temporal_compression_ratio + 1:
32
+ raise ValueError(
33
+ f'A source video needs at least {temporal_compression_ratio + 1} frames, got {num_rgb_frames}.'
34
+ )
35
+ return (int(num_rgb_frames) - 1) // int(temporal_compression_ratio)
36
+
37
+
38
+ def plan_encoder_windows(
39
+ num_rgb_frames: int,
40
+ *,
41
+ window_rgb_frames: int,
42
+ temporal_compression_ratio: int = 4,
43
+ ) -> list[EncoderWindow]:
44
+ """Windows that cover ``num_rgb_frames`` with each window's first half of transitions.
45
+
46
+ ``window_rgb_frames`` is the clip length the action encoder was trained on.
47
+ """
48
+ ratio = int(temporal_compression_ratio)
49
+ window = int(window_rgb_frames)
50
+ if ratio < 1:
51
+ raise ValueError('temporal_compression_ratio must be positive.')
52
+ if window < ratio + 1 or (window - 1) % ratio:
53
+ raise ValueError(f'window_rgb_frames must be {ratio}k+1 with k >= 1, got {window}.')
54
+ keep = max(1, (window - 1) // ratio // 2)
55
+ total = usable_transitions(num_rgb_frames, ratio)
56
+ aligned_rgb_frames = 1 + total * ratio
57
+
58
+ windows = []
59
+ done = 0
60
+ while done < total:
61
+ kept = min(keep, total - done)
62
+ start = done * ratio
63
+ length = window if start + window <= aligned_rgb_frames else 1 + kept * ratio
64
+ windows.append(EncoderWindow(start_rgb_frame=start, num_rgb_frames=length, kept_transitions=kept))
65
+ done += kept
66
+ return windows
O2LaF/o2laf/inference/hub.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The on-disk layout of a released model, as published on Hugging Face.
2
+
3
+ ::
4
+
5
+ <model>/
6
+ model_index.json what the model is and which files make it up
7
+ latent_action_model/ the action encoder and the causal world model, as
8
+ latent action learning trained them: one config,
9
+ tensors under ``action_encoder.`` and ``world_model.``
10
+ world_model/ the bidirectional world model (sharded when large)
11
+ action_library/ optional atomic actions
12
+
13
+ The latent action model is one component because it is one trained object: the
14
+ encoder and the causal world model were optimised jointly, a run that continues
15
+ training restores both, and neither is meaningful paired with another's
16
+ partner. Bidirectional inference reads only its ``action_encoder.`` tensors.
17
+
18
+ The fixed prompt's embedding is not part of a model: it depends only on the base
19
+ model's text encoder and the prompt, so it ships with the package
20
+ (:mod:`o2laf.inference.prompts`).
21
+
22
+ Weights are stored exactly as trained, in the dtype they were trained in.
23
+ Tensor names are the model's own parameter names with PEFT's wrapper removed:
24
+ no ``base_model.model.`` prefix, no ``base_layer`` segment, no adapter name. A
25
+ file therefore does not depend on how the model was wrapped when it was
26
+ trained, and :func:`hub_keys_to_model_keys` puts the wrapper back for whatever
27
+ module it is loaded into.
28
+
29
+ Writing and reading live together here so the format is defined in one place.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import hashlib
35
+ import json
36
+ import os
37
+ import re
38
+ from pathlib import Path
39
+ from typing import Any, Iterable, Mapping
40
+
41
+ import torch
42
+ from safetensors import safe_open
43
+ from safetensors.torch import save_file
44
+
45
+ from o2laf.utils.action_util import NULL_ACTION_CONVENTIONS
46
+ from o2laf.utils.file_util import write_json_atomic
47
+ from o2laf.utils.lora_util import LORA_ADAPTER_NAME
48
+
49
+ MODEL_FORMAT = 'o2laf_model_v1'
50
+ MODEL_INDEX_NAME = 'model_index.json'
51
+ COMPONENT_CONFIG_NAME = 'config.json'
52
+ WEIGHTS_NAME = 'model.safetensors'
53
+ WEIGHTS_INDEX_NAME = 'model.safetensors.index.json'
54
+ INFERENCE_MODES = ('causal', 'bidirectional')
55
+
56
+ LATENT_ACTION_MODEL_DIR = 'latent_action_model'
57
+ WORLD_MODEL_DIR = 'world_model'
58
+ # Parts of the latent action model; each is also the key of its config section.
59
+ ACTION_ENCODER_PART = 'action_encoder'
60
+ WORLD_MODEL_PART = 'world_model'
61
+
62
+ # PEFT's wrapper prefix, at the start of a module path -- which, inside a joint
63
+ # component, is after the part's own prefix (``action_encoder.base_model...``).
64
+ _PEFT_PREFIX = re.compile(r'(^|\.)base_model\.model\.')
65
+ _BASE_LAYER = '.base_layer'
66
+ # ``<module>.lora_A.real.weight`` (or ``lora_B``, ``lora_magnitude_vector``,
67
+ # ...) with this package's adapter name. Only that name is stripped: matching
68
+ # any segment would also strip the ``weight`` of an already-clean name, and the
69
+ # mapping must be safe to apply twice.
70
+ _PEFT_ADAPTER = re.compile(rf'\.(lora_[A-Za-z_]+)\.{re.escape(LORA_ADAPTER_NAME)}(?=\.|$)')
71
+
72
+ _REQUIRED_INDEX_KEYS = (
73
+ 'format',
74
+ 'base_model',
75
+ 'fixed_prompt',
76
+ 'action_space_id',
77
+ 'action_encoder',
78
+ 'action_dim',
79
+ 'codes_per_transition',
80
+ 'temporal_compression_ratio',
81
+ 'modes',
82
+ )
83
+ _REQUIRED_MODE_KEYS = (
84
+ 'world_model', 'null_action', 'num_rgb_frames', 'num_context_frames', 'height', 'width', 'fps', 'scheduler_cfg',
85
+ )
86
+
87
+
88
+ def save_tensors(tensors: Mapping[str, torch.Tensor], path: str | Path, metadata: dict[str, str] | None = None) -> None:
89
+ """``safetensors.save_file``, readable by others.
90
+
91
+ safetensors creates its files owner-only, which leaves a model directory
92
+ shared on a cluster unreadable to everyone else. The mode is set outright
93
+ rather than derived from the umask, which can only be read by changing it --
94
+ process-wide, and so not safely while other threads create files.
95
+ """
96
+ save_file(dict(tensors), str(path), metadata={'format': 'pt', **(metadata or {})})
97
+ os.chmod(path, 0o644)
98
+
99
+
100
+ # -- tensor names -------------------------------------------------------------
101
+
102
+
103
+ def to_hub_key(name: str) -> str:
104
+ """A parameter name with PEFT's wrapper removed, with or without a part prefix."""
105
+ name = _PEFT_PREFIX.sub(r'\1', name)
106
+ name = name.replace(_BASE_LAYER + '.', '.')
107
+ return _PEFT_ADAPTER.sub(r'.\1', name)
108
+
109
+
110
+ def hub_keys_to_model_keys(hub_keys: Iterable[str], model_keys: Iterable[str]) -> dict[str, str]:
111
+ """Map each hub tensor name to the name it has in ``model_keys``.
112
+
113
+ The model may or may not be PEFT-wrapped; the mapping is found by stripping
114
+ the model's own names the same way the hub names were stripped. A hub name with no counterpart, or with several, is an
115
+ error rather than a guess.
116
+ """
117
+ by_hub_key: dict[str, list[str]] = {}
118
+ for model_key in model_keys:
119
+ by_hub_key.setdefault(to_hub_key(model_key), []).append(model_key)
120
+ mapping, missing, ambiguous = {}, [], []
121
+ for hub_key in hub_keys:
122
+ candidates = by_hub_key.get(hub_key, [])
123
+ if not candidates:
124
+ missing.append(hub_key)
125
+ elif len(candidates) > 1:
126
+ ambiguous.append((hub_key, candidates))
127
+ else:
128
+ mapping[hub_key] = candidates[0]
129
+ if missing:
130
+ raise KeyError(f'{len(missing)} stored tensors have no parameter in the model, e.g. {missing[:3]}.')
131
+ if ambiguous:
132
+ raise KeyError(f'{len(ambiguous)} stored tensors match several parameters, e.g. {ambiguous[:1]}.')
133
+ return mapping
134
+
135
+
136
+ def tensor_content_sha256(state: Mapping[str, torch.Tensor]) -> str:
137
+ """A digest of names, dtypes, shapes and bytes, independent of file layout.
138
+
139
+ Two files holding the same tensors hash alike however they are sharded or
140
+ ordered, so this identifies weights rather than a particular serialisation.
141
+ """
142
+ digest = hashlib.sha256()
143
+ for name in sorted(state):
144
+ tensor = state[name].detach().cpu().contiguous()
145
+ digest.update(name.encode('utf-8'))
146
+ digest.update(str(tensor.dtype).encode('utf-8'))
147
+ digest.update(json.dumps(list(tensor.shape)).encode('utf-8'))
148
+ digest.update(tensor.reshape(-1).view(torch.uint8).numpy().tobytes())
149
+ return digest.hexdigest()
150
+
151
+
152
+ def action_space_id(encoder_state: Mapping[str, torch.Tensor]) -> str:
153
+ """The identity of the action space an encoder defines: a hash of its weights.
154
+
155
+ Names are compared with PEFT's wrapper removed, so a training state and its
156
+ released form give the same id. World model training records it, the release
157
+ records it, and action libraries are bound to it -- one definition for all.
158
+ """
159
+ return 'sha256:' + tensor_content_sha256({to_hub_key(name): tensor for name, tensor in encoder_state.items()})
160
+
161
+
162
+ # -- components -----------------------------------------------------------------
163
+
164
+
165
+ def save_component(directory: str | Path, config: Mapping[str, Any], state: Mapping[str, torch.Tensor], *,
166
+ max_shard_size: int | str = '5GB') -> list[str]:
167
+ """Write one component's ``config.json`` and weights; return the weight file names."""
168
+ from huggingface_hub import split_torch_state_dict_into_shards
169
+
170
+ directory = Path(directory)
171
+ directory.mkdir(parents=True, exist_ok=True)
172
+ renamed = {to_hub_key(name): name for name in state}
173
+ if len(renamed) != len(state):
174
+ raise ValueError('Two tensors map to one stored name once the PEFT wrapper is removed.')
175
+ tensors = {hub_key: state[name].detach().cpu().contiguous() for hub_key, name in renamed.items()}
176
+
177
+ split = split_torch_state_dict_into_shards(tensors, filename_pattern='model{suffix}.safetensors',
178
+ max_shard_size=max_shard_size)
179
+ for filename, names in split.filename_to_tensors.items():
180
+ save_tensors({name: tensors[name] for name in names}, directory / filename)
181
+ if split.is_sharded:
182
+ write_json_atomic(directory / WEIGHTS_INDEX_NAME, {'metadata': split.metadata, 'weight_map': split.tensor_to_filename})
183
+ write_json_atomic(directory / COMPONENT_CONFIG_NAME, dict(config))
184
+ return sorted(split.filename_to_tensors)
185
+
186
+
187
+ def load_component_config(directory: str | Path) -> dict[str, Any]:
188
+ path = Path(directory) / COMPONENT_CONFIG_NAME
189
+ if not path.is_file():
190
+ raise FileNotFoundError(f'Component has no {COMPONENT_CONFIG_NAME}: {path}.')
191
+ config = json.loads(path.read_text(encoding='utf-8'))
192
+ if not isinstance(config, dict):
193
+ raise TypeError(f'{path} must contain a JSON object.')
194
+ return config
195
+
196
+
197
+ def load_component_state(directory: str | Path, part: str | None = None) -> dict[str, torch.Tensor]:
198
+ """The tensors of one component, from a single file or its shards.
199
+
200
+ With ``part``, only the tensors stored under ``<part>.`` are read -- the
201
+ others are never loaded -- and they are returned without that prefix.
202
+ """
203
+ directory = Path(directory)
204
+ prefix = f'{part}.' if part else ''
205
+ index_path = directory / WEIGHTS_INDEX_NAME
206
+ if not index_path.is_file():
207
+ single = directory / WEIGHTS_NAME
208
+ if not single.is_file():
209
+ raise FileNotFoundError(f'Component has neither {WEIGHTS_NAME} nor {WEIGHTS_INDEX_NAME}: {directory}.')
210
+ return _read_tensors(single, prefix)
211
+
212
+ index = json.loads(index_path.read_text(encoding='utf-8'))
213
+ weight_map = index.get('weight_map')
214
+ if not isinstance(weight_map, dict) or not weight_map:
215
+ raise ValueError(f'{index_path} has no weight_map.')
216
+ # The weight map alone cannot reveal a dropped entry whose tensor had a
217
+ # shard to itself: that shard is simply never read. The shard names and the
218
+ # recorded total size are independent witnesses to what was written.
219
+ filenames = sorted(set(weight_map.values()))
220
+ expected = _expected_shard_names(filenames)
221
+ if filenames != expected:
222
+ raise ValueError(f'{index_path} references shards {filenames}, but their names say {expected}.')
223
+ stored: dict[str, int] = {}
224
+ state: dict[str, torch.Tensor] = {}
225
+ for filename in filenames:
226
+ with safe_open(str(directory / filename), framework='pt') as handle:
227
+ for name in handle.keys():
228
+ if name in stored:
229
+ raise ValueError(f'Tensor {name!r} is stored in more than one shard.')
230
+ tensor_slice = handle.get_slice(name)
231
+ stored[name] = _stored_bytes(tensor_slice.get_shape(), tensor_slice.get_dtype())
232
+ if name.startswith(prefix):
233
+ state[name[len(prefix):]] = handle.get_tensor(name)
234
+ if stored.keys() != weight_map.keys():
235
+ missing = sorted(weight_map.keys() - stored.keys())
236
+ extra = sorted(stored.keys() - weight_map.keys())
237
+ raise ValueError(f'Shards disagree with {WEIGHTS_INDEX_NAME}: missing {missing[:3]}, unlisted {extra[:3]}.')
238
+ recorded = (index.get('metadata') or {}).get('total_size')
239
+ if recorded is not None and int(recorded) != sum(stored.values()):
240
+ raise ValueError(f'{index_path} records {recorded} bytes of weights, but the shards hold {sum(stored.values())}.')
241
+ if prefix and not state:
242
+ raise KeyError(f'{directory} stores no tensors under {prefix!r}.')
243
+ return state
244
+
245
+
246
+ _DTYPE_BYTES = {'BOOL': 1, 'U8': 1, 'I8': 1, 'F8_E4M3': 1, 'F8_E5M2': 1, 'I16': 2, 'U16': 2, 'F16': 2, 'BF16': 2,
247
+ 'I32': 4, 'U32': 4, 'F32': 4, 'I64': 8, 'U64': 8, 'F64': 8}
248
+
249
+
250
+ def _stored_bytes(shape, dtype: str) -> int:
251
+ count = 1
252
+ for size in shape:
253
+ count *= int(size)
254
+ return count * _DTYPE_BYTES[dtype]
255
+
256
+
257
+ def _read_tensors(path: Path, prefix: str) -> dict[str, torch.Tensor]:
258
+ with safe_open(str(path), framework='pt') as handle:
259
+ state = {name[len(prefix):]: handle.get_tensor(name) for name in handle.keys() if name.startswith(prefix)}
260
+ if prefix and not state:
261
+ raise KeyError(f'{path} stores no tensors under {prefix!r}.')
262
+ return state
263
+
264
+
265
+ def _expected_shard_names(filenames: list[str]) -> list[str]:
266
+ """The complete set of ``model-0000k-of-0000n`` names the first one implies."""
267
+ match = re.fullmatch(r'model-\d+-of-(\d+)\.safetensors', filenames[0])
268
+ if match is None:
269
+ raise ValueError(f'Unexpected shard name {filenames[0]!r}.')
270
+ width, count = len(match.group(1)), int(match.group(1))
271
+ return [f'model-{index:0{width}d}-of-{count:0{width}d}.safetensors' for index in range(1, count + 1)]
272
+
273
+
274
+ # -- the model index ------------------------------------------------------------
275
+
276
+
277
+ def read_model_index(root: str | Path) -> dict[str, Any]:
278
+ """Read and check ``model_index.json``.
279
+
280
+ Components are checked when they are loaded rather than here: a download
281
+ for one mode deliberately leaves out the other mode's world model.
282
+ """
283
+ root = Path(root)
284
+ path = root / MODEL_INDEX_NAME
285
+ if not path.is_file():
286
+ raise FileNotFoundError(f'Not an O²LaF model directory (no {MODEL_INDEX_NAME}): {root}.')
287
+ index = json.loads(path.read_text(encoding='utf-8'))
288
+ if not isinstance(index, dict):
289
+ raise TypeError(f'{path} must contain a JSON object.')
290
+ if index.get('format') != MODEL_FORMAT:
291
+ raise ValueError(f'{path} has format {index.get("format")!r}; this package reads {MODEL_FORMAT!r}.')
292
+ missing = [key for key in _REQUIRED_INDEX_KEYS if key not in index]
293
+ if missing:
294
+ raise KeyError(f'{path} is missing {missing}.')
295
+ modes = index['modes']
296
+ if not isinstance(modes, dict) or not modes or set(modes) - set(INFERENCE_MODES):
297
+ raise ValueError(f'{path} modes must be a non-empty subset of {INFERENCE_MODES}, got {modes!r}.')
298
+ for name, mode in modes.items():
299
+ absent = [key for key in _REQUIRED_MODE_KEYS if key not in mode]
300
+ if absent:
301
+ raise KeyError(f'{path} mode {name!r} is missing {absent}.')
302
+ if mode['null_action'] not in NULL_ACTION_CONVENTIONS:
303
+ raise ValueError(f'{path} mode {name!r} has unknown null_action {mode["null_action"]!r}.')
304
+ return index
305
+
306
+
307
+ def component_paths(index: Mapping[str, Any], mode: str) -> tuple[dict[str, str], dict[str, str]]:
308
+ """Where the action encoder and ``mode``'s world model live.
309
+
310
+ Each is ``{'component': <directory>, 'part': <section or None>}``: a part
311
+ names the config section and tensor prefix inside a joint component.
312
+ """
313
+ if mode not in index['modes']:
314
+ raise ValueError(f'This model has no {mode!r} mode; it has {sorted(index["modes"])}.')
315
+ return dict(index['action_encoder']), dict(index['modes'][mode]['world_model'])
316
+
317
+
318
+ def load_part_config(root: str | Path, location: Mapping[str, str]) -> dict[str, Any]:
319
+ """The config of the part at ``location``: its section of a joint component, or the whole component."""
320
+ config = load_component_config(Path(root) / location['component'])
321
+ part = location.get('part')
322
+ if not part:
323
+ return config
324
+ if part not in config:
325
+ raise KeyError(f'{location["component"]}/{COMPONENT_CONFIG_NAME} has no {part!r} section.')
326
+ return dict(config[part])
327
+
328
+
329
+ def load_part_state(root: str | Path, location: Mapping[str, str]) -> dict[str, torch.Tensor]:
330
+ return load_component_state(Path(root) / location['component'], location.get('part'))
331
+
332
+
333
+ FETCH_MODES = ('mode', 'metadata', 'action_encoder')
334
+
335
+
336
+ def resolve_model_dir(pretrained_model_name_or_path: str | Path, *, mode: str = 'bidirectional', revision: str | None = None,
337
+ cache_dir: str | Path | None = None, local_files_only: bool = False,
338
+ token: str | bool | None = None, fetch: str = 'mode') -> Path:
339
+ """A local directory holding a model, downloading from the Hub if given a repo id.
340
+
341
+ A Hub model is ``<org>/<repo>/<model>``: one repository holds several
342
+ models, each in its own subfolder, e.g. ``YuxinJ/O2LaF/o2laf_dit_mixed``.
343
+ ``<org>/<repo>`` alone names a model at the repository root.
344
+
345
+ ``fetch`` says how much of a Hub model to download:
346
+
347
+ * ``'mode'``: everything ``mode`` needs to run -- the latent action model,
348
+ that mode's world model and the action library. Causal inference never
349
+ downloads the 10 GB bidirectional world model.
350
+ * ``'metadata'``: the index, every component's ``config.json`` and the
351
+ action library; no weights at all.
352
+ * ``'action_encoder'``: the metadata, plus the component holding the action
353
+ encoder.
354
+
355
+ A local directory is returned as it is.
356
+ """
357
+ if fetch not in FETCH_MODES:
358
+ raise ValueError(f'fetch must be one of {FETCH_MODES}, got {fetch!r}.')
359
+ name = str(pretrained_model_name_or_path)
360
+ local = Path(name).expanduser()
361
+ if local.is_dir():
362
+ return local.resolve()
363
+ if _looks_like_a_path(name):
364
+ raise FileNotFoundError(f'No model directory at {local}. (A Hub model is named "<org>/<name>".)')
365
+
366
+ from huggingface_hub import hf_hub_download, snapshot_download
367
+ from huggingface_hub.errors import EntryNotFoundError, LocalEntryNotFoundError
368
+
369
+ repo_id, subfolder = _split_hub_name(name)
370
+ prefix = f'{subfolder}/' if subfolder else ''
371
+ hub = {'revision': revision, 'cache_dir': cache_dir, 'local_files_only': local_files_only, 'token': token}
372
+ try:
373
+ index_file = hf_hub_download(repo_id, prefix + MODEL_INDEX_NAME, **hub)
374
+ except EntryNotFoundError as error:
375
+ if isinstance(error, LocalEntryNotFoundError):
376
+ raise
377
+ raise FileNotFoundError(_no_model_here(repo_id, subfolder, revision, token)) from error
378
+ index = read_model_index_file(Path(index_file))
379
+ # Every component the model has, from the index alone: `mode` is only
380
+ # looked up below, when its weights are asked for, so a model without the
381
+ # default mode can still be described.
382
+ every_component = {index['action_encoder']['component']}
383
+ every_component |= {mode_entry['world_model']['component'] for mode_entry in index['modes'].values()}
384
+ patterns = [MODEL_INDEX_NAME, *(f'{component}/{COMPONENT_CONFIG_NAME}' for component in sorted(every_component))]
385
+ if fetch == 'mode':
386
+ weights = {location['component'] for location in component_paths(index, mode)}
387
+ elif fetch == 'action_encoder':
388
+ weights = {index['action_encoder']['component']}
389
+ else:
390
+ weights = set()
391
+ patterns += [f'{component}/*' for component in sorted(weights)]
392
+ if index.get('action_library'):
393
+ patterns.append(f'{index["action_library"]["directory"]}/*')
394
+ snapshot = Path(snapshot_download(repo_id, allow_patterns=[prefix + pattern for pattern in patterns], **hub))
395
+ return snapshot / subfolder if subfolder else snapshot
396
+
397
+
398
+ def _looks_like_a_path(name: str) -> bool:
399
+ """Whether ``name`` was meant as a local path rather than a Hub model (``org/repo`` or ``org/repo/model``)."""
400
+ return name.startswith(('/', './', '../', '~', '.\\')) or name in ('.', '..') or name.count('/') > 2
401
+
402
+
403
+ def _split_hub_name(name: str) -> tuple[str, str | None]:
404
+ """``org/repo/model`` to ``('org/repo', 'model')``; ``org/repo`` to ``('org/repo', None)``."""
405
+ parts = name.split('/')
406
+ if len(parts) not in (2, 3) or not all(parts):
407
+ raise ValueError(f'{name!r} is not a Hub model: expected "<org>/<repo>" or "<org>/<repo>/<model>".')
408
+ return '/'.join(parts[:2]), parts[2] if len(parts) == 3 else None
409
+
410
+
411
+ def _no_model_here(repo_id: str, subfolder: str | None, revision, token) -> str:
412
+ """Explain a missing index, naming the models the repository does hold."""
413
+ where = f'{repo_id}/{subfolder}' if subfolder else repo_id
414
+ try:
415
+ from huggingface_hub import HfApi
416
+
417
+ files = HfApi().list_repo_files(repo_id, revision=revision, token=token)
418
+ except Exception: # noqa: BLE001 - the listing only improves the message
419
+ return f'{where} holds no {MODEL_INDEX_NAME}.'
420
+ models = sorted(f'{repo_id}/{path.rsplit("/", 1)[0]}' for path in files if path.endswith(f'/{MODEL_INDEX_NAME}'))
421
+ if not models:
422
+ return f'{where} holds no {MODEL_INDEX_NAME}, and neither does any folder of {repo_id}.'
423
+ return f'{where} is not a model. {repo_id} holds: {", ".join(models)}.'
424
+
425
+
426
+ def read_model_index_file(path: Path) -> dict[str, Any]:
427
+ """The index alone, before the rest of the model is present to check it against."""
428
+ index = json.loads(Path(path).read_text(encoding='utf-8'))
429
+ if not isinstance(index, dict) or index.get('format') != MODEL_FORMAT:
430
+ raise ValueError(f'{path} is not an {MODEL_FORMAT} model index.')
431
+ return index
O2LaF/o2laf/inference/pipeline.py ADDED
@@ -0,0 +1,560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone inference: encode actions from a source video and generate from a first frame.
2
+
3
+ Two modes share one action encoder:
4
+
5
+ * ``causal``: the causal world model trained jointly with the encoder;
6
+ * ``bidirectional``: the fully fine-tuned bidirectional world model trained
7
+ against the frozen encoder.
8
+
9
+ A model is a directory in the layout of :mod:`o2laf.inference.hub`, local or on
10
+ the Hugging Face Hub. The base model (Wan 2.2 TI2V-5B) supplies the VAE, the
11
+ scheduler and the transformer the action encoder and causal world model adapt.
12
+ Its text encoder is loaded only for a model whose fixed prompt has no embedding
13
+ packaged with this library (:mod:`o2laf.inference.prompts`).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import gc
19
+ import warnings
20
+ from dataclasses import dataclass
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ import numpy as np
25
+ import torch
26
+ import torch.nn.functional as F
27
+ from diffusers.models import AutoencoderKLWan
28
+ from peft import LoraConfig, get_peft_model
29
+
30
+ from o2laf.action_encoders.base import build_action_encoder_spec, unwrap_peft
31
+ from o2laf.action_encoders.wan_dit import WanDiTActionEncoder
32
+ from o2laf.inference import hub
33
+ from o2laf.inference.encoder_windows import plan_encoder_windows, usable_transitions
34
+ from o2laf.inference.prompts import fixed_prompt_embeds
35
+ from o2laf.inference.sampling import MAX_RGB_FRAMES, ActionGuidance, sample_with_guidance
36
+ from o2laf.schedulers.flow_match_euler import FlowMatchEulerScheduler
37
+ from o2laf.utils.action_util import (
38
+ NULL_ACTION_NO_BIAS,
39
+ prepend_action_anchor,
40
+ process_actions_for_latent_space,
41
+ validate_null_action,
42
+ )
43
+ from o2laf.utils.lora_util import LORA_ADAPTER_NAME, LORA_STATE_KEYS, filter_learnable_module
44
+ from o2laf.world_models import build_world_model_from_config
45
+
46
+ INFERENCE_MODES = hub.INFERENCE_MODES
47
+
48
+
49
+ def _cast_and_freeze(module, device, dtype):
50
+ module = module.to(device=device, dtype=dtype)
51
+ wrong = [
52
+ (name, parameter.dtype)
53
+ for name, parameter in module.named_parameters()
54
+ if parameter.is_floating_point() and parameter.dtype != dtype
55
+ ]
56
+ if wrong:
57
+ raise RuntimeError(f'{len(wrong)} parameters were not cast to {dtype}, e.g. {wrong[:3]}.')
58
+ module.requires_grad_(False)
59
+ module.eval()
60
+ return module
61
+
62
+
63
+ def _selected_parameter_names(module, config):
64
+ include = tuple(config.get('param_names_to_optimize', ()))
65
+ exclude = tuple(config.get('param_names_to_exclude', ()))
66
+ return {
67
+ name
68
+ for name, _ in module.named_parameters()
69
+ if any(keyword in name for keyword in include) and not any(keyword in name for keyword in exclude)
70
+ }
71
+
72
+
73
+ def _load_selected_state(module, stored, config, label):
74
+ """Load stored tensors into ``module``; every tensor its training optimised must be among them."""
75
+ mapping = hub.hub_keys_to_model_keys(stored, module.state_dict())
76
+ source = {mapping[name]: tensor for name, tensor in stored.items()}
77
+ required = _selected_parameter_names(module, config)
78
+ absent = required - set(source)
79
+ if absent:
80
+ raise RuntimeError(f'{len(absent)} required {label} tensors are absent, e.g. {sorted(absent)[:3]}.')
81
+ missing, unexpected = module.load_state_dict(source, strict=False)
82
+ if unexpected:
83
+ raise RuntimeError(f'{len(unexpected)} unexpected {label} tensors, e.g. {unexpected[:3]}.')
84
+ missing_required = required.intersection(missing)
85
+ if missing_required:
86
+ raise RuntimeError(f'{len(missing_required)} required {label} tensors did not load, e.g. {sorted(missing_required)[:3]}.')
87
+
88
+
89
+ def _attach_lora(module, lora_cfg, label):
90
+ targets = filter_learnable_module(module, lora_cfg['target_module_name'])
91
+ if not targets:
92
+ raise ValueError(f'{label} LoRA selection matched no modules.')
93
+ return get_peft_model(
94
+ module,
95
+ LoraConfig(
96
+ r=int(lora_cfg['lora_rank']),
97
+ lora_alpha=int(lora_cfg['lora_alpha']),
98
+ target_modules=targets,
99
+ lora_dropout=float(lora_cfg.get('lora_dropout', 0.0)),
100
+ bias='none',
101
+ ),
102
+ adapter_name=LORA_ADAPTER_NAME,
103
+ )
104
+
105
+
106
+ def _build_world_model(state: dict[str, torch.Tensor], config: dict[str, Any], base_model: str, device, dtype,
107
+ **load_kwargs):
108
+ world_model = build_world_model_from_config(
109
+ {'model_name': base_model, 'model_type': config['_class_name']},
110
+ {'latent_action_dim': config['action_dim'], 'gamma_init': config['action_gain_init']},
111
+ num_latent_frames=int(config['num_latent_frames']),
112
+ causal=bool(config['causal']),
113
+ dtype=dtype,
114
+ **load_kwargs,
115
+ )
116
+ if config.get('lora_config') is not None:
117
+ world_model = _attach_lora(world_model, config['lora_config'], 'world model')
118
+ label = f'{"causal" if config["causal"] else "bidirectional"} world model'
119
+ _load_selected_state(world_model, state, config, label)
120
+ return _cast_and_freeze(world_model, device, dtype)
121
+
122
+
123
+ def _build_wan_dit_encoder(config, base_model, dtype, **load_kwargs):
124
+ encoder = WanDiTActionEncoder.from_pretrained(base_model, subfolder='transformer', torch_dtype=dtype, **load_kwargs)
125
+ encoder.setup_readout(latent_dim=int(config['latent_dim']), query_init_std=float(config['query_init_std']))
126
+ return encoder
127
+
128
+
129
+ def _build_action_encoder(state: dict[str, torch.Tensor], config: dict[str, Any], base_model: str, device, dtype,
130
+ **load_kwargs):
131
+ name = config.get('action_encoder')
132
+ if name != 'wan_dit':
133
+ raise NotImplementedError(f'This inference-only copy supports the wan_dit action encoder, not {name!r}.')
134
+ encoder = _build_wan_dit_encoder(config, base_model, dtype, **load_kwargs)
135
+ if config.get('lora_config') is not None:
136
+ encoder = _attach_lora(encoder, config['lora_config'], 'action encoder')
137
+ adapted_head = [
138
+ name for name, _ in encoder.named_parameters()
139
+ if 'idm_head' in name and any(key in name for key in LORA_STATE_KEYS)
140
+ ]
141
+ if adapted_head:
142
+ raise RuntimeError('Action encoder LoRA unexpectedly reached the readout head.')
143
+ _load_selected_state(encoder, state, config, 'action encoder')
144
+ if config.get('lora_config') is not None:
145
+ # Inference never changes the adapter: fold it into the base weights so
146
+ # every linear layer is one matmul instead of three.
147
+ encoder = encoder.merge_and_unload()
148
+ return _cast_and_freeze(encoder, device, dtype)
149
+
150
+
151
+ def _check_action_space(index, encoder_config, world_model_config, world_model_name) -> str:
152
+ """Every part must describe the same action space, or the world model reads codes it never saw."""
153
+ action_space_id = str(index['action_space_id'])
154
+ for label, recorded in (('action encoder', encoder_config.get('action_space_id')),
155
+ (f'world model {world_model_name!r}', world_model_config.get('action_space_id'))):
156
+ if recorded != action_space_id:
157
+ raise RuntimeError(f'The {label} was trained in action space {recorded}, but the model is {action_space_id}.')
158
+ return action_space_id
159
+
160
+
161
+ @dataclass
162
+ class LatentActionPipeline:
163
+ """One action encoder plus one world model (causal or bidirectional), ready to sample."""
164
+
165
+ model_dir: Path
166
+ model_index: dict[str, Any]
167
+ action_space_id: str
168
+ mode: str
169
+ # What this mode's world model learned "no action" to be, from the dropout
170
+ # its training used. Guidance and the no-action control must ask for the
171
+ # same thing, or the unconditional branch is off-distribution.
172
+ null_action: str
173
+ world_model: torch.nn.Module
174
+ action_encoder: torch.nn.Module
175
+ vae: AutoencoderKLWan
176
+ scheduler: FlowMatchEulerScheduler
177
+ prompt_embeddings: torch.Tensor
178
+ device: torch.device
179
+ dtype: torch.dtype
180
+ # The clip length this mode's world model was trained on, and its default.
181
+ num_rgb_frames: int
182
+ num_latent_frames: int
183
+ num_context_frames: int
184
+ # The clip length the action encoder was trained on; longer source videos
185
+ # are read in windows of this length (see o2laf.inference.encoder_windows).
186
+ encoder_window_rgb_frames: int
187
+ # Which encoder this model carries, and whether it reads the clip's pixels
188
+ # or the VAE latents of those pixels.
189
+ action_encoder_name: str
190
+ encoder_reads_pixels: bool
191
+ action_dim: int
192
+ action_compression_ratio: int
193
+ height: int
194
+ width: int
195
+ fps: int
196
+ world_model_step: int
197
+
198
+ @classmethod
199
+ def from_pretrained(
200
+ cls,
201
+ pretrained_model_name_or_path: str | Path,
202
+ *,
203
+ mode: str = 'bidirectional',
204
+ base_model: str | Path | None = None,
205
+ device: str | torch.device = 'cuda',
206
+ dtype: torch.dtype = torch.bfloat16,
207
+ revision: str | None = None,
208
+ cache_dir: str | Path | None = None,
209
+ local_files_only: bool = False,
210
+ token: str | bool | None = None,
211
+ verify_action_space: bool = False,
212
+ ) -> 'LatentActionPipeline':
213
+ """Load a model from a Hub repo id or a local directory.
214
+
215
+ Args:
216
+ mode: ``'bidirectional'`` (the model the paper evaluates) or ``'causal'``.
217
+ base_model: the Wan 2.2 TI2V-5B base, as a Hub id or local path;
218
+ defaults to the one the model records.
219
+ verify_action_space: recompute the action encoder's content hash and
220
+ check it against the recorded action space (a few seconds).
221
+ """
222
+ if mode not in INFERENCE_MODES:
223
+ raise ValueError(f'mode must be one of {list(INFERENCE_MODES)}, got {mode!r}.')
224
+ device = torch.device(device)
225
+ root = hub.resolve_model_dir(
226
+ pretrained_model_name_or_path, mode=mode, revision=revision, cache_dir=cache_dir,
227
+ local_files_only=local_files_only, token=token,
228
+ )
229
+ index = hub.read_model_index(root)
230
+ encoder_at, world_model_at = hub.component_paths(index, mode)
231
+ mode_config = index['modes'][mode]
232
+ encoder_config = hub.load_part_config(root, encoder_at)
233
+ world_model_config = hub.load_part_config(root, world_model_at)
234
+ action_space_id = _check_action_space(index, encoder_config, world_model_config, world_model_at['component'])
235
+ encoder_state = hub.load_part_state(root, encoder_at)
236
+ if verify_action_space:
237
+ actual = 'sha256:' + hub.tensor_content_sha256(encoder_state)
238
+ if actual != action_space_id:
239
+ raise RuntimeError(f'The action encoder weights hash to {actual}, not the recorded {action_space_id}.')
240
+ # Where to load the base model from; the embedding depends on which one
241
+ # the model was trained on, which is what the index records.
242
+ base_model_path = str(base_model or index['base_model'])
243
+
244
+ # The base model comes from the same Hub cache, credentials and offline
245
+ # setting as this model; its own revision is whatever base_model names.
246
+ base_kwargs = {'cache_dir': cache_dir, 'local_files_only': local_files_only, 'token': token}
247
+ prompt_embeddings = fixed_prompt_embeds(
248
+ base_model=index['base_model'], prompt=index['fixed_prompt'], base_model_path=base_model_path,
249
+ device=device, dtype=dtype, **base_kwargs,
250
+ )
251
+ vae = AutoencoderKLWan.from_pretrained(base_model_path, subfolder='vae', torch_dtype=dtype, **base_kwargs).to(device)
252
+ vae.requires_grad_(False)
253
+ vae.eval()
254
+ world_model = _build_world_model(
255
+ hub.load_part_state(root, world_model_at), world_model_config, base_model_path, device, dtype, **base_kwargs
256
+ )
257
+ action_encoder = _build_action_encoder(
258
+ encoder_state, encoder_config, base_model_path, device, dtype,
259
+ **base_kwargs,
260
+ )
261
+ del encoder_state
262
+ scheduler = FlowMatchEulerScheduler.from_pretrained(
263
+ base_model_path, subfolder='scheduler', **mode_config['scheduler_cfg'], **base_kwargs
264
+ )
265
+
266
+ pipeline = cls(
267
+ model_dir=root,
268
+ model_index=index,
269
+ action_space_id=action_space_id,
270
+ mode=mode,
271
+ null_action=validate_null_action(mode_config['null_action']),
272
+ world_model=world_model,
273
+ action_encoder=action_encoder,
274
+ vae=vae,
275
+ scheduler=scheduler,
276
+ prompt_embeddings=prompt_embeddings,
277
+ device=device,
278
+ dtype=dtype,
279
+ num_rgb_frames=int(mode_config['num_rgb_frames']),
280
+ num_latent_frames=int(world_model_config['num_latent_frames']),
281
+ num_context_frames=int(mode_config['num_context_frames']),
282
+ encoder_window_rgb_frames=int(encoder_config['num_rgb_frames']),
283
+ action_encoder_name=str(encoder_config['action_encoder']),
284
+ encoder_reads_pixels=bool(build_action_encoder_spec(encoder_config['action_encoder']).reads_pixels),
285
+ action_dim=int(index['action_dim']),
286
+ action_compression_ratio=int(index['codes_per_transition']),
287
+ height=int(mode_config['height']),
288
+ width=int(mode_config['width']),
289
+ fps=int(mode_config['fps']),
290
+ world_model_step=int(world_model_config['global_step']),
291
+ )
292
+ gc.collect()
293
+ return pipeline
294
+
295
+ def preprocess_frames(self, frames) -> torch.Tensor:
296
+ """uint8 ``[T,H,W,3]`` frames to normalised model pixels ``[1,T,3,H,W]``."""
297
+ # Decoded video frames are often a read-only array; copy rather than wrap
298
+ # it, which torch warns about. ``.float()`` below copies anyway.
299
+ pixels = torch.as_tensor(np.array(frames)) if isinstance(frames, np.ndarray) else torch.as_tensor(frames)
300
+ if pixels.ndim != 4 or pixels.shape[-1] != 3:
301
+ raise ValueError(f'frames must be [T,H,W,3], got {tuple(pixels.shape)}.')
302
+ pixels = pixels.float().permute(0, 3, 1, 2).div_(255.0)
303
+ pixels = F.interpolate(pixels, size=(self.height, self.width), mode='bilinear', align_corners=False, antialias=True)
304
+ pixels = pixels.sub_(0.5).div_(0.5)
305
+ return pixels.unsqueeze(0)
306
+
307
+ @torch.no_grad()
308
+ def encode_latents(self, pixels: torch.Tensor) -> torch.Tensor:
309
+ """Normalised ``[B,T,3,H,W]`` pixels to Wan latents."""
310
+ if pixels.ndim != 5 or pixels.shape[2] != 3:
311
+ raise ValueError(f'pixels must be [B,T,3,H,W], got {tuple(pixels.shape)}.')
312
+ video = pixels.permute(0, 2, 1, 3, 4).contiguous().to(device=self.device, dtype=self.dtype)
313
+ moments = self.vae._encode(video)
314
+ mean, _ = torch.chunk(moments, 2, dim=1)
315
+ latent_mean = torch.as_tensor(self.vae.config.latents_mean, device=self.device, dtype=torch.float32).view(1, -1, 1, 1, 1)
316
+ latent_std = torch.as_tensor(self.vae.config.latents_std, device=self.device, dtype=torch.float32).view(1, -1, 1, 1, 1)
317
+ return ((mean.float() - latent_mean) / latent_std).to(self.dtype)
318
+
319
+ @torch.no_grad()
320
+ def decode_latents(self, latents: torch.Tensor) -> torch.Tensor:
321
+ """Normalised latents to ``[B,T,3,H,W]`` pixels in ``[0,1]``."""
322
+ z_dim = int(self.vae.config.z_dim)
323
+ latent_mean = torch.as_tensor(self.vae.config.latents_mean, device=latents.device, dtype=self.vae.dtype).view(1, z_dim, 1, 1, 1)
324
+ inverse_std = 1.0 / torch.as_tensor(self.vae.config.latents_std, device=latents.device, dtype=self.vae.dtype).view(
325
+ 1, z_dim, 1, 1, 1
326
+ )
327
+ decoded = self.vae.decode(latents.to(self.vae.dtype) / inverse_std + latent_mean, return_dict=False)[0]
328
+ decoded = (decoded.float() / 2 + 0.5).clamp(0, 1)
329
+ return decoded.permute(0, 2, 1, 3, 4).contiguous()
330
+
331
+ @property
332
+ def temporal_compression_ratio(self) -> int:
333
+ return int(self.model_index['temporal_compression_ratio'])
334
+
335
+ def num_latent_frames_for(self, num_rgb_frames: int) -> int:
336
+ """Latent frames of a ``num_rgb_frames`` clip, which must be ``1 + 4k`` frames long."""
337
+ ratio = self.temporal_compression_ratio
338
+ if num_rgb_frames < 1 + ratio or (num_rgb_frames - 1) % ratio:
339
+ raise ValueError(f'A clip must be {ratio}k+1 frames long with k >= 1, got {num_rgb_frames}.')
340
+ return (num_rgb_frames - 1) // ratio + 1
341
+
342
+ def num_rgb_frames_for(self, num_latent_frames: int) -> int:
343
+ return 1 + (num_latent_frames - 1) * self.temporal_compression_ratio
344
+
345
+ @property
346
+ def encoder_spec(self):
347
+ return build_action_encoder_spec(self.action_encoder_name)
348
+
349
+ @torch.no_grad()
350
+ def encode_source_actions(self, frames) -> torch.Tensor:
351
+ """Actions ``[1, K, D]`` of a source video of any length, as uint8 ``[T,H,W,3]`` frames at ``fps``.
352
+
353
+ The action encoder reads the video in windows of the length it was
354
+ trained on and keeps the first half of each window's transitions
355
+ (:func:`~o2laf.inference.encoder_windows.plan_encoder_windows`). Each
356
+ window is VAE-encoded on its own. ``K`` is ``(T - 1) // 4`` transitions
357
+ times the codes per transition; up to three trailing frames are dropped.
358
+ """
359
+ num_frames = len(frames)
360
+ if num_frames > MAX_RGB_FRAMES:
361
+ raise ValueError(f'The source video has {num_frames} frames; at most {MAX_RGB_FRAMES} are supported.')
362
+ windows = plan_encoder_windows(
363
+ num_frames, window_rgb_frames=self.encoder_window_rgb_frames,
364
+ temporal_compression_ratio=self.temporal_compression_ratio,
365
+ )
366
+ codes = self.action_compression_ratio
367
+ pieces = []
368
+ for window in windows:
369
+ clip = frames[window.start_rgb_frame:window.start_rgb_frame + window.num_rgb_frames]
370
+ pixels = self.preprocess_frames(clip)
371
+ # Each encoder's preprocessing is its own: the Wan VAE for wan_dit,
372
+ # a square crop for vjepa2, a resize for st_transformer.
373
+ actions = (
374
+ self._encode_actions(pixels=pixels) if self.encoder_reads_pixels
375
+ else self._encode_actions(latents=self.encode_latents(pixels))
376
+ )
377
+ pieces.append(actions[:, :window.kept_transitions * codes])
378
+ actions = torch.cat(pieces, dim=1)
379
+ expected = usable_transitions(num_frames, self.temporal_compression_ratio) * codes
380
+ if actions.shape[1] != expected:
381
+ raise RuntimeError(f'Stitched {actions.shape[1]} action codes, expected {expected}.')
382
+ return actions
383
+
384
+ @torch.no_grad()
385
+ def encode_actions_from_latents(self, latents: torch.Tensor) -> torch.Tensor:
386
+ """Posterior-mean actions ``[B, F-1, D]`` from the latents of one clip of this mode's length, in one pass.
387
+
388
+ :meth:`encode_source_actions` is what the commands use; this single
389
+ pass is how training reads its clips. Only the encoders that read VAE
390
+ latents have this path.
391
+ """
392
+ if self.encoder_reads_pixels:
393
+ raise TypeError(
394
+ f'The {self.action_encoder_name} action encoder reads pixels, not latents; '
395
+ 'use encode_source_actions().'
396
+ )
397
+ if latents.shape[2] != self.num_latent_frames:
398
+ raise ValueError(f'Expected {self.num_latent_frames} latent frames, got {latents.shape[2]}.')
399
+ return self._encode_actions(latents=latents)
400
+
401
+ def _encode_actions(self, *, latents: torch.Tensor | None = None, pixels: torch.Tensor | None = None) -> torch.Tensor:
402
+ """Posterior-mean actions, handing the encoder whichever form of the clip it reads."""
403
+ if pixels is not None:
404
+ # preprocess_frames leaves the clip on the CPU; encode_latents moves
405
+ # it for the encoders that read latents, so the pixel path must too.
406
+ pixels = pixels.to(device=self.device, dtype=self.dtype)
407
+ reference = pixels if latents is None else latents
408
+ prompt = self.prompt_embeddings
409
+ if prompt.shape[0] != reference.shape[0]:
410
+ prompt = prompt.expand(reference.shape[0], -1, -1)
411
+ outputs = self.encoder_spec.encode(
412
+ self.action_encoder, latents=latents, pixel_values=pixels, prompt_embeds=prompt,
413
+ )
414
+ return outputs['action_mu']
415
+
416
+ def num_latent_frames_for_actions(self, actions: torch.Tensor) -> int:
417
+ """Latent frames a clip driven by ``actions`` ``[B, K, D]`` has: one per transition plus the first frame."""
418
+ codes = self.action_compression_ratio
419
+ if actions.ndim != 3 or actions.shape[2] != self.action_dim or actions.shape[1] < codes or actions.shape[1] % codes:
420
+ raise ValueError(
421
+ f'Expected actions [B, k*{codes}, {self.action_dim}] with k >= 1, got {tuple(actions.shape)}.'
422
+ )
423
+ return actions.shape[1] // codes + self.num_context_frames
424
+
425
+ def pack_actions(self, actions: torch.Tensor) -> torch.Tensor:
426
+ return process_actions_for_latent_space(
427
+ prepend_action_anchor(actions.to(self.dtype)),
428
+ num_latent_frames=self.num_latent_frames_for_actions(actions),
429
+ compression_ratio=self.action_compression_ratio,
430
+ )
431
+
432
+ @torch.no_grad()
433
+ def no_action_condition(self, actions: torch.Tensor) -> torch.Tensor | None:
434
+ """The actions that stand for "no action" in this mode.
435
+
436
+ The counterpart of
437
+ :meth:`~o2laf.training.latent_action.LatentActionTrainer.eval_no_action_condition`:
438
+ ``None`` for no bias at all, an all-zero code otherwise.
439
+ """
440
+ if self.null_action == NULL_ACTION_NO_BIAS:
441
+ return None
442
+ return torch.zeros_like(actions)
443
+
444
+ def null_action_bias(self, actions: torch.Tensor) -> torch.Tensor | None:
445
+ """The bias that stands for "no action here" in this mode.
446
+
447
+ ``None`` means no bias at all. Zero-code mode instead embeds an all-zero
448
+ code, which still carries the embedder's own bias.
449
+ """
450
+ if self.null_action == NULL_ACTION_NO_BIAS:
451
+ return None
452
+ return self.compute_action_bias(torch.zeros_like(actions))
453
+
454
+ def compute_action_bias(self, actions: torch.Tensor) -> torch.Tensor:
455
+ return unwrap_peft(self.world_model).compute_action_bias(self.pack_actions(actions))
456
+
457
+ def latent_shape(self, num_latent_frames: int | None = None) -> tuple[int, ...]:
458
+ scale = int(self.vae.config.scale_factor_spatial)
459
+ frames = self.num_latent_frames if num_latent_frames is None else int(num_latent_frames)
460
+ return (1, int(self.vae.config.z_dim), frames, self.height // scale, self.width // scale)
461
+
462
+ def predict_velocity(self, latents, action_bias, timestep, next_timestep):
463
+ """World model velocity for ``latents`` under a precomputed action bias (None = no action)."""
464
+ prompt = self.prompt_embeddings
465
+ if prompt.shape[0] != latents.shape[0]:
466
+ prompt = prompt.expand(latents.shape[0], -1, -1)
467
+ return self.world_model(
468
+ latents,
469
+ chunk_partition=[1] * latents.shape[2],
470
+ timestep=timestep.to(self.device),
471
+ r_timestep=next_timestep.to(self.device),
472
+ encoder_hidden_states=prompt,
473
+ temb_bias=action_bias,
474
+ return_dict=False,
475
+ )
476
+
477
+ def _resolve_num_latent_frames(self, actions: torch.Tensor | None, num_latent_frames: int | None) -> int:
478
+ """The clip length: the actions fix it; without actions it is ``num_latent_frames`` or this mode's default."""
479
+ if actions is not None:
480
+ implied = self.num_latent_frames_for_actions(actions)
481
+ if num_latent_frames is not None and int(num_latent_frames) != implied:
482
+ raise ValueError(f'{actions.shape[1]} action codes drive {implied} latent frames, not {num_latent_frames}.')
483
+ num_latent_frames = implied
484
+ frames = self.num_latent_frames if num_latent_frames is None else int(num_latent_frames)
485
+ num_rgb_frames = self.num_rgb_frames_for(frames)
486
+ if frames <= self.num_context_frames or num_rgb_frames > MAX_RGB_FRAMES:
487
+ raise ValueError(
488
+ f'A clip of {num_rgb_frames} frames is outside the supported range '
489
+ f'({self.num_rgb_frames_for(self.num_context_frames + 1)} to {MAX_RGB_FRAMES}).'
490
+ )
491
+ if frames > self.num_latent_frames:
492
+ warnings.warn(
493
+ f'Generating {num_rgb_frames} frames; the {self.mode} world model was trained on '
494
+ f'{self.num_rgb_frames}, so the rest is extrapolated.',
495
+ stacklevel=3,
496
+ )
497
+ return frames
498
+
499
+ @torch.no_grad()
500
+ def generate_latents(
501
+ self,
502
+ *,
503
+ actions: torch.Tensor | None,
504
+ first_frame_latents: torch.Tensor,
505
+ num_latent_frames: int | None = None,
506
+ num_steps: int = 20,
507
+ seed: int = 0,
508
+ guidance: ActionGuidance = ActionGuidance(),
509
+ ) -> torch.Tensor:
510
+ """Sample latents that start at ``first_frame_latents`` and follow ``actions`` (None = no action).
511
+
512
+ The clip has one latent frame per action transition plus the first
513
+ frame. Without actions, ``num_latent_frames`` sets the length (default:
514
+ this mode's training length).
515
+ """
516
+ num_latent_frames = self._resolve_num_latent_frames(actions, num_latent_frames)
517
+ bias = self.compute_action_bias(actions) if actions is not None else None
518
+ null_bias = self.null_action_bias(actions) if actions is not None else None
519
+ return sample_with_guidance(
520
+ predict=self.predict_velocity,
521
+ scheduler=self.scheduler,
522
+ latent_shape=self.latent_shape(num_latent_frames),
523
+ action_bias=bias,
524
+ anchor=first_frame_latents,
525
+ num_context_frames=self.num_context_frames,
526
+ num_steps=num_steps,
527
+ seed=seed,
528
+ device=self.device,
529
+ dtype=self.dtype,
530
+ guidance=guidance,
531
+ null_bias=null_bias,
532
+ )
533
+
534
+ @torch.no_grad()
535
+ def generate(
536
+ self,
537
+ *,
538
+ actions: torch.Tensor | None,
539
+ first_frame,
540
+ num_latent_frames: int | None = None,
541
+ num_steps: int = 20,
542
+ seed: int = 0,
543
+ guidance: ActionGuidance = ActionGuidance(),
544
+ ) -> torch.Tensor:
545
+ """A video ``[1, T, 3, H, W]`` in ``[0, 1]`` that starts at ``first_frame`` and follows ``actions``.
546
+
547
+ ``first_frame`` is one uint8 RGB frame, ``[H, W, 3]`` or ``[1, H, W, 3]``,
548
+ resized to the model's resolution. See :meth:`generate_latents` for the
549
+ other arguments.
550
+ """
551
+ # A decoded frame is often a read-only array; preprocess_frames copies it.
552
+ first_frame = torch.as_tensor(np.array(first_frame)) if isinstance(first_frame, np.ndarray) else torch.as_tensor(first_frame)
553
+ if first_frame.ndim == 3:
554
+ first_frame = first_frame.unsqueeze(0)
555
+ first_frame_latents = self.encode_latents(self.preprocess_frames(first_frame))
556
+ latents = self.generate_latents(
557
+ actions=actions, first_frame_latents=first_frame_latents, num_latent_frames=num_latent_frames,
558
+ num_steps=num_steps, seed=seed, guidance=guidance,
559
+ )
560
+ return self.decode_latents(latents)
O2LaF/o2laf/inference/prompts.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The fixed prompt's text embedding.
2
+
3
+ Every model in this package conditions on one constant prompt ("a video"), so
4
+ its UMT5 embedding depends only on the base model's text encoder and the prompt
5
+ text -- not on any O²LaF checkpoint. It ships with the package, tagged with both,
6
+ and inference uses it instead of loading the 11 GB text encoder. A model trained
7
+ with another prompt or base model finds no packaged match and has its prompt
8
+ encoded on load, as before.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import gc
14
+ from importlib import resources
15
+ from pathlib import Path
16
+
17
+ import torch
18
+ import torch.nn.functional as F
19
+ from safetensors import safe_open
20
+
21
+ PROMPT_EMBEDS_KEY = 'prompt_embeds'
22
+ TEXT_MAX_LENGTH = 512
23
+ PACKAGED_DIR = 'assets/prompt_embeds'
24
+
25
+
26
+ def save_prompt_embeds(path: str | Path, embeds: torch.Tensor, *, base_model: str, prompt: str) -> None:
27
+ from o2laf.inference.hub import save_tensors
28
+
29
+ metadata = {'base_model': base_model, 'prompt': prompt, 'max_length': str(TEXT_MAX_LENGTH)}
30
+ save_tensors({PROMPT_EMBEDS_KEY: embeds.detach().cpu().contiguous()}, path, metadata=metadata)
31
+
32
+
33
+ def load_prompt_embeds(path: str | Path) -> tuple[torch.Tensor, dict[str, str]]:
34
+ with safe_open(str(path), framework='pt') as handle:
35
+ names = list(handle.keys())
36
+ if names != [PROMPT_EMBEDS_KEY]:
37
+ raise KeyError(f'{path} must hold exactly one tensor named {PROMPT_EMBEDS_KEY!r}, found {names}.')
38
+ return handle.get_tensor(PROMPT_EMBEDS_KEY), dict(handle.metadata() or {})
39
+
40
+
41
+ def packaged_prompt_embeds(base_model: str, prompt: str) -> torch.Tensor | None:
42
+ """The shipped embedding of ``prompt`` under ``base_model``'s text encoder, if there is one."""
43
+ directory = resources.files('o2laf').joinpath(PACKAGED_DIR)
44
+ if not directory.is_dir():
45
+ return None
46
+ for entry in sorted(directory.iterdir(), key=lambda item: item.name):
47
+ if not entry.name.endswith('.safetensors'):
48
+ continue
49
+ with resources.as_file(entry) as path:
50
+ embeds, metadata = load_prompt_embeds(path)
51
+ if metadata.get('base_model') == base_model and metadata.get('prompt') == prompt:
52
+ return embeds
53
+ return None
54
+
55
+
56
+ @torch.no_grad()
57
+ def encode_prompt(model_path: str, prompt: str, device, dtype, **load_kwargs) -> torch.Tensor:
58
+ """UMT5 embedding of ``prompt``, zero-padded to the text length Wan expects."""
59
+ from transformers import AutoTokenizer, UMT5EncoderModel
60
+
61
+ tokenizer = AutoTokenizer.from_pretrained(model_path, subfolder='tokenizer', use_fast=False, **load_kwargs)
62
+ text_encoder = UMT5EncoderModel.from_pretrained(
63
+ model_path, subfolder='text_encoder', torch_dtype=dtype, **load_kwargs
64
+ ).to(device)
65
+ text_encoder.requires_grad_(False)
66
+ text_encoder.eval()
67
+ inputs = tokenizer(
68
+ [prompt],
69
+ padding='max_length',
70
+ max_length=TEXT_MAX_LENGTH,
71
+ truncation=True,
72
+ add_special_tokens=True,
73
+ return_attention_mask=True,
74
+ return_tensors='pt',
75
+ )
76
+ ids = inputs.input_ids.to(device)
77
+ mask = inputs.attention_mask.to(device)
78
+ length = int(mask[0].sum())
79
+ embeddings = text_encoder(ids, mask).last_hidden_state[:, :length]
80
+ embeddings = F.pad(embeddings, (0, 0, 0, TEXT_MAX_LENGTH - length)).to(dtype)
81
+ del tokenizer, text_encoder, inputs, ids, mask
82
+ gc.collect()
83
+ torch.cuda.empty_cache()
84
+ return embeddings
85
+
86
+
87
+ def fixed_prompt_embeds(*, base_model: str, prompt: str, base_model_path: str, device, dtype, **load_kwargs) -> torch.Tensor:
88
+ """The packaged embedding when one matches, else ``prompt`` encoded with the base model's text encoder.
89
+
90
+ ``base_model`` is the id the model was trained on, which is what the
91
+ embedding depends on; ``base_model_path`` is where to load it from if it
92
+ has to be computed.
93
+ """
94
+ embeds = packaged_prompt_embeds(base_model, prompt)
95
+ if embeds is None:
96
+ embeds = encode_prompt(base_model_path, prompt, device, dtype, **load_kwargs)
97
+ return embeds.to(device=device, dtype=dtype)
O2LaF/o2laf/inference/sampling.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Euler sampling of the world model, with optional classifier-free guidance on the actions.
2
+
3
+ Guidance combines a conditional and an unconditional velocity,
4
+ ``v = v_uncond + scale * (v_cond - v_uncond)``. ``scale == 1`` returns the
5
+ conditional velocity exactly and skips the unconditional forward. The prompt is
6
+ a constant, so the action is the only guided condition.
7
+
8
+ The unconditional branch replaces the action bias with the *null-action* bias,
9
+ which is what the model's training taught it "no action" looks like: either no
10
+ bias at all, or the bias a zero action code produces. See
11
+ ``utils.action_util.NULL_ACTION_*``.
12
+
13
+ Two forms of "unconditional" are available:
14
+
15
+ * ``full``: every action frame's bias is removed at once (two forwards per step);
16
+ * ``per_frame``: frame ``t`` comes from the branch in which only frame ``t``'s
17
+ bias is removed (one extra forward per action frame, batched).
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from dataclasses import dataclass
23
+ from typing import Callable, Sequence
24
+
25
+ import torch
26
+
27
+ UNCONDITIONAL_MODES = ('full', 'per_frame')
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class ActionGuidance:
32
+ """Classifier-free guidance settings for the action condition.
33
+
34
+ Attributes:
35
+ scale: guidance scale; 1.0 disables guidance.
36
+ unconditional_mode: ``'full'`` or ``'per_frame'`` (see module docstring).
37
+ guidance_sigma_min: if set, guide only at steps with sigma >= this value.
38
+ variant_batch_size: unconditional variants per forward in ``per_frame`` mode.
39
+ """
40
+
41
+ scale: float = 1.0
42
+ unconditional_mode: str = 'full'
43
+ guidance_sigma_min: float | None = None
44
+ variant_batch_size: int = 4
45
+
46
+ def __post_init__(self):
47
+ if self.scale < 0:
48
+ raise ValueError(f'scale must be nonnegative, got {self.scale}.')
49
+ if self.unconditional_mode not in UNCONDITIONAL_MODES:
50
+ raise ValueError(f'unconditional_mode must be one of {UNCONDITIONAL_MODES}, got {self.unconditional_mode!r}.')
51
+ if self.guidance_sigma_min is not None and not 0.0 < self.guidance_sigma_min < 1.0:
52
+ raise ValueError(f'guidance_sigma_min must be in (0, 1), got {self.guidance_sigma_min}.')
53
+ if self.variant_batch_size < 1:
54
+ raise ValueError('variant_batch_size must be positive.')
55
+
56
+ @property
57
+ def active(self) -> bool:
58
+ return self.scale != 1.0
59
+
60
+
61
+ # The longest video either world model generates, in RGB frames (7.5 s at
62
+ # 16 fps). Both world models run at any length up to this. Past the length
63
+ # they were trained on (81 or 41 frames), they extrapolate.
64
+ MAX_RGB_FRAMES = 121
65
+
66
+
67
+ def combine_guidance(conditional: torch.Tensor, unconditional: torch.Tensor, scale: float) -> torch.Tensor:
68
+ """``unconditional + scale * (conditional - unconditional)``; exactly ``conditional`` at scale 1."""
69
+ if conditional.shape != unconditional.shape:
70
+ raise ValueError(
71
+ f'Guidance branches have different shapes: {tuple(conditional.shape)} and {tuple(unconditional.shape)}.'
72
+ )
73
+ if scale == 1.0:
74
+ return conditional
75
+ return unconditional + float(scale) * (conditional - unconditional)
76
+
77
+
78
+ def action_frame_indices(num_latent_frames: int) -> tuple[int, ...]:
79
+ """Latent frames that carry an action bias: every frame after the clean first one."""
80
+ if num_latent_frames < 2:
81
+ raise ValueError('Action guidance requires at least two latent frames.')
82
+ return tuple(range(1, num_latent_frames))
83
+
84
+
85
+ def build_unconditional_biases(
86
+ action_bias: torch.Tensor, mode: str, *, action_frames: Sequence[int], null_bias: torch.Tensor | None = None
87
+ ) -> torch.Tensor:
88
+ """Unconditional bias variants: the null-action bias everywhere (``full``) or one frame at a time (``per_frame``).
89
+
90
+ ``null_bias`` is what the model was taught "no action here" looks like. It
91
+ defaults to zeros, which is the no-bias convention; a model trained with
92
+ zero-code dropout passes the bias a zero code produces instead.
93
+ """
94
+ if action_bias.ndim != 3 or action_bias.shape[0] != 1:
95
+ raise ValueError(f'action_bias must be [1, F, C], got {tuple(action_bias.shape)}.')
96
+ if null_bias is None:
97
+ null_bias = torch.zeros_like(action_bias)
98
+ elif null_bias.shape != action_bias.shape:
99
+ raise ValueError(f'null_bias must be {tuple(action_bias.shape)}, got {tuple(null_bias.shape)}.')
100
+ if mode == 'full':
101
+ return null_bias
102
+ if mode != 'per_frame':
103
+ raise ValueError(f'Unknown unconditional mode {mode!r}.')
104
+ frames = tuple(int(frame) for frame in action_frames)
105
+ if not frames:
106
+ raise ValueError('per_frame guidance needs at least one action frame.')
107
+ if min(frames) < 0 or max(frames) >= action_bias.shape[1]:
108
+ raise ValueError(f'Action frames {frames} are outside [0, {action_bias.shape[1]}).')
109
+ variants = action_bias.expand(len(frames), -1, -1).clone()
110
+ for row, frame in enumerate(frames):
111
+ variants[row, frame] = null_bias[0, frame]
112
+ return variants
113
+
114
+
115
+ def gather_per_frame_unconditional(
116
+ variants: torch.Tensor, action_frames: Sequence[int], conditional: torch.Tensor
117
+ ) -> torch.Tensor:
118
+ """Assemble each action frame from the variant that removed that frame's bias."""
119
+ frames = tuple(int(frame) for frame in action_frames)
120
+ if variants.shape[0] != len(frames):
121
+ raise ValueError(f'Expected {len(frames)} variants, got {variants.shape[0]}.')
122
+ if variants.shape[1:] != conditional.shape[1:]:
123
+ raise ValueError(
124
+ f'Variant shape {tuple(variants.shape[1:])} does not match conditional shape {tuple(conditional.shape[1:])}.'
125
+ )
126
+ if conditional.ndim != 5:
127
+ raise ValueError(f'Velocity must be [B, C, F, H, W], got {tuple(conditional.shape)}.')
128
+ result = conditional.clone()
129
+ for row, frame in enumerate(frames):
130
+ result[:, :, frame] = variants[row:row + 1, :, frame]
131
+ return result
132
+
133
+
134
+ def _forward_variants(predict, latents, bias_variants, timestep, next_timestep, batch_size):
135
+ outputs = []
136
+ for start in range(0, bias_variants.shape[0], batch_size):
137
+ block = bias_variants[start:start + batch_size]
138
+ count = block.shape[0]
139
+ outputs.append(
140
+ predict(
141
+ latents.expand(count, -1, -1, -1, -1),
142
+ block,
143
+ timestep.expand(count, -1),
144
+ next_timestep.expand(count, -1),
145
+ )
146
+ )
147
+ return torch.cat(outputs, dim=0)
148
+
149
+
150
+ @torch.no_grad()
151
+ def sample_with_guidance(
152
+ *,
153
+ predict: Callable[[torch.Tensor, torch.Tensor | None, torch.Tensor, torch.Tensor], torch.Tensor],
154
+ scheduler,
155
+ latent_shape: tuple[int, ...],
156
+ action_bias: torch.Tensor | None,
157
+ anchor: torch.Tensor | None,
158
+ num_context_frames: int,
159
+ num_steps: int,
160
+ seed: int,
161
+ device: torch.device,
162
+ dtype: torch.dtype,
163
+ guidance: ActionGuidance,
164
+ null_bias: torch.Tensor | None = None,
165
+ ) -> torch.Tensor:
166
+ """Euler-sample a clip from CPU-seeded noise, pinning the clean context frames throughout.
167
+
168
+ ``predict(latents, action_bias, timestep, next_timestep)`` returns the velocity.
169
+ """
170
+ if len(latent_shape) != 5 or latent_shape[0] != 1:
171
+ raise ValueError(f'latent_shape must be [1, C, F, H, W], got {latent_shape}.')
172
+ if num_steps < 1:
173
+ raise ValueError('num_steps must be positive.')
174
+ if not 0 <= num_context_frames < latent_shape[2]:
175
+ raise ValueError(f'num_context_frames={num_context_frames} is invalid for {latent_shape[2]} latent frames.')
176
+ if anchor is None and num_context_frames:
177
+ raise ValueError('A nonzero context length requires an anchor tensor.')
178
+ if anchor is not None and anchor.shape[2] < num_context_frames:
179
+ raise ValueError(f'Anchor has {anchor.shape[2]} frames but {num_context_frames} are required.')
180
+ if guidance.active and action_bias is None:
181
+ raise ValueError('Action guidance requires an action bias.')
182
+
183
+ generator = torch.Generator(device='cpu').manual_seed(int(seed))
184
+ latents = torch.randn(latent_shape, generator=generator, dtype=torch.float32).to(device=device, dtype=dtype)
185
+ scheduler.set_timesteps(int(num_steps), device=device)
186
+ timesteps = torch.cat([scheduler.timesteps, scheduler.timesteps.new_tensor([0])])
187
+ num_latent_frames = latent_shape[2]
188
+ action_frames = action_frame_indices(num_latent_frames)
189
+ bias_variants = (
190
+ build_unconditional_biases(
191
+ action_bias, guidance.unconditional_mode, action_frames=action_frames, null_bias=null_bias
192
+ )
193
+ if guidance.active
194
+ else None
195
+ )
196
+ train_timesteps = float(scheduler.config.num_train_timesteps)
197
+
198
+ for index, timestep_scalar in enumerate(timesteps[:-1]):
199
+ next_scalar = timesteps[index + 1]
200
+ if timestep_scalar == next_scalar:
201
+ continue
202
+ timestep = timestep_scalar.reshape(1).expand(1, num_latent_frames).contiguous()
203
+ next_timestep = next_scalar.reshape(1).expand(1, num_latent_frames).contiguous()
204
+ if num_context_frames:
205
+ latents[:, :, :num_context_frames] = anchor[:, :, :num_context_frames]
206
+ timestep[:, :num_context_frames] = 0
207
+ next_timestep[:, :num_context_frames] = 0
208
+
209
+ sigma = float(timestep_scalar) / train_timesteps
210
+ guide = guidance.active and (guidance.guidance_sigma_min is None or sigma >= guidance.guidance_sigma_min)
211
+ if guide and guidance.unconditional_mode == 'full':
212
+ # Both branches in one batch-2 forward: same result, better GPU use.
213
+ both = predict(
214
+ latents.expand(2, -1, -1, -1, -1),
215
+ torch.cat([action_bias, bias_variants], dim=0),
216
+ timestep.expand(2, -1),
217
+ next_timestep.expand(2, -1),
218
+ )
219
+ velocity = combine_guidance(both[:1], both[1:], guidance.scale)
220
+ latents = scheduler.step(velocity, timestep_scalar, latents, next_scalar).prev_sample
221
+ continue
222
+ conditional = predict(latents, action_bias, timestep, next_timestep)
223
+ if guide:
224
+ variants = _forward_variants(
225
+ predict, latents, bias_variants, timestep, next_timestep, guidance.variant_batch_size
226
+ )
227
+ unconditional = (
228
+ variants
229
+ if guidance.unconditional_mode == 'full'
230
+ else gather_per_frame_unconditional(variants, action_frames, conditional)
231
+ )
232
+ velocity = combine_guidance(conditional, unconditional, guidance.scale)
233
+ else:
234
+ velocity = conditional
235
+ latents = scheduler.step(velocity, timestep_scalar, latents, next_scalar).prev_sample
236
+
237
+ if num_context_frames:
238
+ latents[:, :, :num_context_frames] = anchor[:, :, :num_context_frames]
239
+ return latents
O2LaF/o2laf/inference/video.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reading source videos at a model's frame rate."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+
9
+ from o2laf.inference.sampling import MAX_RGB_FRAMES
10
+ from o2laf.utils.video_util import VideoLoader, select_frame_indices
11
+
12
+
13
+ def load_source_video(path: str | Path, fps: int, max_frames: int = MAX_RGB_FRAMES) -> np.ndarray:
14
+ """The whole of ``path`` resampled to ``fps``, up to its first ``max_frames`` frames, as uint8 ``[T,H,W,3]``."""
15
+ with VideoLoader(str(path), name=str(path)) as loader:
16
+ available = len(select_frame_indices(loader.get_frame_count(), loader.get_fps(), fps))
17
+ num_frames = min(available, int(max_frames))
18
+ frames = loader.get_clip(num_frames, target_fps=fps, random_sample=False)
19
+ return np.asarray(frames, dtype=np.uint8)
O2LaF/o2laf/schedulers/flow_match_euler.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+ """Shifted flow-matching schedule, training weights, and the Euler sampler step."""
17
+
18
+ from dataclasses import dataclass
19
+ from typing import Optional, Union
20
+
21
+ import torch
22
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
23
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin
24
+ from diffusers.utils import BaseOutput
25
+
26
+
27
+ @dataclass
28
+ class FlowMatchEulerSchedulerOutput(BaseOutput):
29
+ prev_sample: torch.FloatTensor
30
+
31
+
32
+ class FlowMatchEulerScheduler(SchedulerMixin, ConfigMixin):
33
+ """Flow matching with ``x_t = (1 - sigma) x_0 + sigma * noise`` and a shifted sigma grid.
34
+
35
+ Timesteps are ``sigma * num_train_timesteps``. ``shift`` maps a uniform
36
+ ``t`` to ``sigma = shift * t / (1 + (shift - 1) * t)``.
37
+ """
38
+
39
+ order = 1
40
+
41
+ @register_to_config
42
+ def __init__(
43
+ self,
44
+ num_train_timesteps: int = 1000,
45
+ shift: float = 1.0,
46
+ weight_type: str = 'gaussian',
47
+ ):
48
+ if weight_type != 'gaussian':
49
+ raise ValueError(f"Only weight_type='gaussian' is supported, got {weight_type!r}.")
50
+ self.set_timesteps(num_train_timesteps, device='cpu')
51
+ self.set_train_weight()
52
+
53
+ def set_train_weight(self):
54
+ """Gaussian per-timestep loss weights over the full training grid.
55
+
56
+ The training grid is kept separate from ``self.timesteps``, which
57
+ ``set_timesteps`` replaces with a short inference grid during sampling.
58
+ """
59
+ self.train_timesteps = self.timesteps.detach().clone()
60
+ x = self.train_timesteps
61
+ y = torch.exp(-2 * ((x - self.config.num_train_timesteps / 2) / self.config.num_train_timesteps) ** 2)
62
+ y_shifted = y - y.min()
63
+ self.linear_timesteps_weights = y_shifted * (self.config.num_train_timesteps / y_shifted.sum())
64
+
65
+ @torch.no_grad()
66
+ def get_train_weight(self, timesteps):
67
+ train_timesteps = self.train_timesteps
68
+ timestep_id = torch.argmin(
69
+ (train_timesteps.unsqueeze(1) - timesteps.flatten().unsqueeze(0).to(train_timesteps.device)).abs(),
70
+ dim=0,
71
+ ).reshape(timesteps.shape)
72
+ weights = self.linear_timesteps_weights[timestep_id]
73
+ return weights.to(timesteps.device)
74
+
75
+ def scale_noise(
76
+ self,
77
+ sample: torch.FloatTensor,
78
+ timestep: Union[float, torch.FloatTensor],
79
+ noise: Optional[torch.FloatTensor] = None,
80
+ ) -> torch.FloatTensor:
81
+ timestep = timestep.float()
82
+ timestep = timestep / self.config.num_train_timesteps
83
+ timestep = timestep.view(*timestep.shape, *([1] * (noise.ndim - timestep.ndim)))
84
+ sample = timestep * noise + (1.0 - timestep) * sample
85
+ return sample.to(noise.dtype)
86
+
87
+ def apply_shift(self, sigmas):
88
+ sigmas = sigmas.float()
89
+ if self.config.shift == 1.0:
90
+ return sigmas
91
+ return self.config.shift * sigmas / (1 + (self.config.shift - 1) * sigmas)
92
+
93
+ def set_timesteps(self, num_inference_steps: Optional[int] = None, device: Union[str, torch.device] = None):
94
+ timesteps = torch.linspace(1.0, 0.0, num_inference_steps + 1, dtype=torch.float64, device=device)[:-1]
95
+ timesteps = self.apply_shift(timesteps)
96
+ self.timesteps = timesteps * self.config.num_train_timesteps
97
+
98
+ def step(
99
+ self,
100
+ model_output: torch.FloatTensor,
101
+ timestep: torch.FloatTensor,
102
+ sample: torch.FloatTensor,
103
+ next_timestep: torch.FloatTensor,
104
+ return_dict: bool = True,
105
+ ):
106
+ """One Euler step of the velocity ``model_output`` from ``timestep`` to ``next_timestep``."""
107
+ timestep = timestep.float() / self.config.num_train_timesteps
108
+ next_timestep = next_timestep.float() / self.config.num_train_timesteps
109
+ timestep = timestep.view(*timestep.shape, *([1] * (model_output.ndim - timestep.ndim)))
110
+ next_timestep = next_timestep.view(*next_timestep.shape, *([1] * (model_output.ndim - next_timestep.ndim)))
111
+ prev_sample = sample - (timestep - next_timestep) * model_output
112
+ if not return_dict:
113
+ return (prev_sample.to(model_output.dtype),)
114
+ return FlowMatchEulerSchedulerOutput(prev_sample=prev_sample.to(model_output.dtype))
O2LaF/o2laf/utils/action_util.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared utilities for per-frame action conditioning.
2
+
3
+ An action encoder emits ``r`` codes per latent transition: the Wan DiT encoder
4
+ reads latents and emits one, V-JEPA2 emits two and the ST-Transformer four.
5
+ Everything that depends only on ``r`` -- packing to latent resolution, dropout,
6
+ shuffling -- lives here, so the transition, not the single code, is the unit of
7
+ every grouped operation. At ``r = 1`` each group holds one code and these
8
+ degenerate to the per-transition forms.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import torch
14
+
15
+
16
+ # What "no action" means when the world model is asked for an unconditional
17
+ # prediction. The two differ only by the action embedder's own bias: a zero code
18
+ # still reaches the model as ``gamma * linear.bias``, while no bias reaches it as
19
+ # exactly nothing. They coincide at initialisation, because that bias starts at
20
+ # zero, and diverge as it trains -- in the released causal model by about 4% of a
21
+ # typical action's magnitude, which classifier-free guidance then amplifies.
22
+ #
23
+ # Each trainer's action dropout teaches the model one of the two, so inference
24
+ # must ask for the same one. A model records which in its own metadata rather
25
+ # than relying on a global default.
26
+ NULL_ACTION_ZERO_CODE = 'zero_code'
27
+ NULL_ACTION_NO_BIAS = 'no_bias'
28
+ NULL_ACTION_CONVENTIONS = (NULL_ACTION_ZERO_CODE, NULL_ACTION_NO_BIAS)
29
+
30
+
31
+ def validate_null_action(convention: str) -> str:
32
+ """Return ``convention`` if it names a null-action convention, else raise."""
33
+ if convention not in NULL_ACTION_CONVENTIONS:
34
+ raise ValueError(f'Unknown null action {convention!r}; expected one of {NULL_ACTION_CONVENTIONS}.')
35
+ return convention
36
+
37
+
38
+ def prepend_action_anchor(z: torch.Tensor) -> torch.Tensor:
39
+ """Prepend a zero frame-0 anchor row to per-transition action codes.
40
+
41
+ Turns per-transition codes ``[B, T-1, D]`` into a per-frame action matrix
42
+ ``[B, T, D]`` whose first row is all zeros, because no transition produced
43
+ the first frame.
44
+
45
+ Args:
46
+ z: Per-transition codes ``[B, T-1, D]``.
47
+
48
+ Returns:
49
+ ``[B, T, D]`` with ``out[:, 0] == 0``.
50
+ """
51
+ if z.dim() != 3:
52
+ raise ValueError(f'z must be [B, T-1, D], got {tuple(z.shape)}')
53
+ batch, _, dim = z.shape
54
+ anchor = z.new_zeros(batch, 1, dim)
55
+ return torch.cat([anchor, z], dim=1)
56
+
57
+
58
+ def process_actions_for_latent_space(
59
+ actions: torch.Tensor,
60
+ num_latent_frames: int,
61
+ compression_ratio: int = 4,
62
+ ) -> torch.Tensor:
63
+ """Pack an action sequence ``[B, T, D]`` to latent resolution ``[B, F, r, D]``.
64
+
65
+ Keep-first semantics:
66
+
67
+ - group 0 repeats ``actions[:, 0]`` ``r`` times, because VAE latent frame 0
68
+ encodes the initial, action-free frame;
69
+ - group ``i >= 1`` takes the window of ``r`` actions starting at
70
+ ``1 + (i-1)*r``, mirroring the WAN VAE temporal compression.
71
+
72
+ With ``compression_ratio=1`` and ``T == num_latent_frames`` this is exactly
73
+ ``actions.unsqueeze(2)``: latent frame ``i`` receives ``actions[:, i]``. Since
74
+ the caller prepends a zero anchor, latent frame ``t+1`` receives transition
75
+ code ``a_t``, which is the alignment the AdaLN injection assumes.
76
+
77
+ Args:
78
+ actions: Float tensor ``[B, T, D]``.
79
+ num_latent_frames: Number of latent temporal frames F.
80
+ compression_ratio: VAE temporal compression ratio r.
81
+
82
+ Returns:
83
+ Tensor ``[B, F, r, D]``.
84
+ """
85
+ if actions.dim() != 3:
86
+ raise ValueError(f'actions must be [B, T, D], got {tuple(actions.shape)}')
87
+ batch, num_actions, dim = actions.shape
88
+ ratio = int(compression_ratio)
89
+ frames = int(num_latent_frames)
90
+ if ratio < 1:
91
+ raise ValueError(f'compression_ratio must be >= 1, got {ratio}')
92
+ if frames < 1:
93
+ raise ValueError(f'num_latent_frames must be >= 1, got {frames}')
94
+
95
+ out = torch.zeros(
96
+ batch, frames, ratio, dim, device=actions.device, dtype=actions.dtype
97
+ )
98
+ out[:, 0] = actions[:, 0:1].expand(batch, ratio, dim)
99
+ for index in range(1, frames):
100
+ start = 1 + (index - 1) * ratio
101
+ if start >= num_actions:
102
+ continue
103
+ chunk = actions[:, start:min(start + ratio, num_actions)]
104
+ available = chunk.shape[1]
105
+ if available < ratio:
106
+ pad = torch.zeros(
107
+ batch, ratio - available, dim,
108
+ device=actions.device, dtype=actions.dtype,
109
+ )
110
+ chunk = torch.cat([chunk, pad], dim=1)
111
+ out[:, index] = chunk
112
+ return out
113
+
114
+
115
+ def check_latent_action_frame_budget(
116
+ num_rgb_frames: int, compression_ratio: int = 4
117
+ ) -> int:
118
+ """Return the latent frame count for ``num_rgb_frames``, or raise.
119
+
120
+ WAN's VAE is causal with temporal stride ``r``, so ``T`` RGB frames become
121
+ ``(T - 1) // r + 1`` latent frames and ``T - 1`` must be divisible by ``r``.
122
+ Valid choices at ``r=4`` include 17, 33, 41, 65 and 81 frames.
123
+ """
124
+ if num_rgb_frames < 1 + compression_ratio:
125
+ raise ValueError(
126
+ f'num_rgb_frames={num_rgb_frames} is too short for '
127
+ f'compression_ratio={compression_ratio}'
128
+ )
129
+ if (num_rgb_frames - 1) % compression_ratio != 0:
130
+ raise ValueError(
131
+ f'(num_rgb_frames - 1) must be divisible by {compression_ratio}; '
132
+ f'got {num_rgb_frames}. Use e.g. 17, 33, 41, 65, or 81.'
133
+ )
134
+ return (num_rgb_frames - 1) // compression_ratio + 1
135
+
136
+
137
+ def pack_action_groups(actions: torch.Tensor, ratio: int) -> torch.Tensor:
138
+ """Pack ``[B, r*K, D]`` codes into ``[B, K+1, r, D]`` behind a zero anchor.
139
+
140
+ Latent frame 0 encodes the initial, action-free frame, so it gets the zero
141
+ anchor and latent frame ``t+1`` gets the ``r`` codes of transition ``t``.
142
+ """
143
+ if actions.ndim != 3 or actions.shape[1] % ratio:
144
+ raise ValueError(f'Expected actions [B, {ratio}K, D], got {tuple(actions.shape)}.')
145
+ num_latent_frames = actions.shape[1] // ratio + 1
146
+ return process_actions_for_latent_space(
147
+ prepend_action_anchor(actions), num_latent_frames=num_latent_frames, compression_ratio=ratio
148
+ )
149
+
150
+
151
+ def drop_action_groups(actions: torch.Tensor, ratio: int, prob: float) -> tuple[torch.Tensor, float]:
152
+ """Zero the codes of whole transitions, independently per sample and transition.
153
+
154
+ Dropping a transition's ``r`` codes together is what makes dropout mean
155
+ "this transition has no action" rather than "this transition is partly
156
+ described". The code is zeroed rather than the embedder output, so a dropped
157
+ transition still receives ``gamma * linear.bias``; KL is still charged on the
158
+ full posterior. Returns the actions and the fraction dropped.
159
+ """
160
+ if actions.ndim != 3 or actions.shape[1] % ratio:
161
+ raise ValueError(f'Expected actions [B, {ratio}K, D], got {tuple(actions.shape)}.')
162
+ if not prob:
163
+ return actions, 0.0
164
+ groups = actions.shape[1] // ratio
165
+ # One keep bit per transition, drawn before any broadcast so the number of
166
+ # random values consumed depends on the transition count alone.
167
+ keep = torch.rand(actions.shape[0], groups, 1, device=actions.device) >= prob
168
+ dropped_fraction = 1.0 - float(keep.float().mean())
169
+ keep = keep.repeat_interleave(ratio, dim=1)
170
+ return actions * keep.to(actions.dtype), dropped_fraction
171
+
172
+
173
+ def shuffle_action_groups(actions: torch.Tensor, ratio: int, seed: int) -> tuple[torch.Tensor, list[int]]:
174
+ """Permute ``[B, r*K, D]`` actions in groups of ``ratio``, keeping the order inside each group.
175
+
176
+ The permutation is drawn on the CPU from ``seed``; an identity draw is rolled
177
+ by one so the result always differs. Returns the actions and the order.
178
+ """
179
+ if actions.ndim != 3 or actions.shape[1] % ratio:
180
+ raise ValueError(f'Expected actions [B, {ratio}K, D], got {tuple(actions.shape)}.')
181
+ groups = actions.shape[1] // ratio
182
+ if groups < 2:
183
+ raise ValueError('Temporal shuffle needs at least two action groups.')
184
+ generator = torch.Generator(device='cpu').manual_seed(int(seed))
185
+ order = torch.randperm(groups, generator=generator)
186
+ if torch.equal(order, torch.arange(groups)):
187
+ order = order.roll(1)
188
+ grouped = actions.reshape(actions.shape[0], groups, ratio, actions.shape[-1])
189
+ return grouped[:, order.to(actions.device)].flatten(1, 2).contiguous(), order.tolist()
O2LaF/o2laf/utils/dist_util.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ import logging
18
+ import os
19
+ import socket
20
+ import sys
21
+ from datetime import timedelta
22
+
23
+ import torch
24
+ import torch.distributed as dist
25
+ import torch.nn as nn
26
+ from torch.distributed.checkpoint.state_dict import StateDictOptions, set_model_state_dict
27
+ from torch.distributed.device_mesh import DeviceMesh, init_device_mesh
28
+ from torch.distributed.distributed_c10d import split_group
29
+ from torch.distributed.fsdp import MixedPrecisionPolicy, OffloadPolicy, fully_shard
30
+
31
+
32
+ def is_main_process():
33
+ return not dist.is_initialized() or dist.get_rank() == 0
34
+
35
+
36
+ def _free_port() -> int:
37
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
38
+ probe.bind(('127.0.0.1', 0))
39
+ return int(probe.getsockname()[1])
40
+
41
+
42
+ def dist_init() -> None:
43
+ """Initialise the default process group, under torchrun or as a one-process run.
44
+
45
+ Run without torchrun, this sets up a real one-rank group rather than none,
46
+ so every collective the training code issues behaves the same at one GPU as
47
+ at many. A torchrun job whose rendezvous fails raises instead of carrying on
48
+ as a one-process job, which would change the batch size and typically turn
49
+ the real error into a misleading out-of-memory.
50
+ """
51
+ if is_dist_initialized():
52
+ return
53
+ if 'RANK' not in os.environ:
54
+ os.environ.update(
55
+ RANK='0', LOCAL_RANK='0', WORLD_SIZE='1', LOCAL_WORLD_SIZE='1',
56
+ MASTER_ADDR='127.0.0.1', MASTER_PORT=str(_free_port()),
57
+ )
58
+ rank = int(os.environ['RANK'])
59
+ local_rank = int(os.environ['LOCAL_RANK'])
60
+ world_size = int(os.environ['WORLD_SIZE'])
61
+ host = os.environ['MASTER_ADDR']
62
+ port = int(os.environ['MASTER_PORT'])
63
+ init_method = f'tcp://[{host}]:{port}' if ':' in host else f'tcp://{host}:{port}'
64
+
65
+ torch.cuda.set_device(local_rank)
66
+ dist.init_process_group(
67
+ rank=rank,
68
+ world_size=world_size,
69
+ backend='nccl',
70
+ init_method=init_method,
71
+ timeout=timedelta(minutes=30),
72
+ device_id=torch.device('cuda', local_rank),
73
+ )
74
+
75
+
76
+ def fsdp2_wrap(
77
+ module: nn.Module,
78
+ sharding_strategy: str = 'hybrid_full',
79
+ mixed_precision: bool = True,
80
+ transformer_block_clsname: str = None,
81
+ sync_module_state: bool = True
82
+ ):
83
+ if sync_module_state and dist.is_initialized():
84
+ # Rank 0 may spend many minutes reading a large checkpoint from shared storage
85
+ # while the other ranks construct an empty model. Synchronize on the
86
+ # 30-minute default process group before DeviceMesh creates subgroups;
87
+ # those subgroups otherwise use PyTorch's shorter default timeout and
88
+ # can expire before rank 0 reaches the first collective.
89
+ dist.barrier()
90
+
91
+ if sync_module_state:
92
+ full_state_dict = module.state_dict() if dist.get_rank() == 0 else {}
93
+
94
+ # build mixed precision policy
95
+ if mixed_precision:
96
+ mixed_precision_policy = MixedPrecisionPolicy(
97
+ param_dtype=torch.bfloat16,
98
+ reduce_dtype=torch.float32,
99
+ cast_forward_inputs=False,
100
+ )
101
+ else:
102
+ mixed_precision_policy = MixedPrecisionPolicy()
103
+
104
+ # build device mesh
105
+ world_size = int(os.environ['WORLD_SIZE'])
106
+ if 'LOCAL_WORLD_SIZE' not in os.environ and world_size > 1:
107
+ # Defaulting to 1 would treat every GPU as its own node and turn hybrid
108
+ # sharding into plain replication: the job runs, and runs out of memory.
109
+ raise RuntimeError('LOCAL_WORLD_SIZE is not set; launch with torchrun, or set it to the GPUs per node.')
110
+ gpus_per_node = int(os.environ.get('LOCAL_WORLD_SIZE', 1))
111
+ num_nodes = world_size // gpus_per_node
112
+
113
+ if sharding_strategy == 'hybrid_full' or sharding_strategy == 'hybrid_zero2':
114
+ # DeviceMesh normally creates these groups through ncclCommSplit without
115
+ # passing a timeout. PyTorch then falls back to NCCL's 10-minute
116
+ # default even though the parent process group above is configured for
117
+ # 30 minutes. A first-step compile/data straggler can therefore kill
118
+ # an otherwise healthy job in mesh_replication while the default group
119
+ # is still well within its timeout. Create the same two mesh groups
120
+ # explicitly so every collective uses the process-group timeout.
121
+ mesh = torch.arange(world_size, dtype=torch.int).reshape(
122
+ num_nodes, gpus_per_node
123
+ )
124
+ process_group_timeout = timedelta(
125
+ minutes=int(os.environ.get('O2LAF_PROCESS_GROUP_TIMEOUT_MINUTES', '30'))
126
+ )
127
+ replication_group = split_group(
128
+ parent_pg=dist.group.WORLD,
129
+ split_ranks=mesh.transpose(0, 1).tolist(),
130
+ timeout=process_group_timeout,
131
+ group_desc='mesh_replication',
132
+ )
133
+ sharding_group = split_group(
134
+ parent_pg=dist.group.WORLD,
135
+ split_ranks=mesh.tolist(),
136
+ timeout=process_group_timeout,
137
+ group_desc='mesh_sharding',
138
+ )
139
+ if replication_group is None or sharding_group is None:
140
+ raise RuntimeError('current rank is missing from the hybrid FSDP mesh')
141
+ device_mesh = DeviceMesh.from_group(
142
+ [replication_group, sharding_group],
143
+ 'cuda',
144
+ mesh=mesh,
145
+ mesh_dim_names=('replication', 'sharding'),
146
+ )
147
+ else:
148
+ device_mesh = init_device_mesh('cuda', (world_size,))
149
+
150
+ if transformer_block_clsname is not None:
151
+ for m in module.modules():
152
+ if type(m).__name__ == transformer_block_clsname:
153
+ fully_shard(m, mesh=device_mesh, reshard_after_forward=True, mp_policy=mixed_precision_policy, offload_policy=OffloadPolicy())
154
+ fully_shard(module, mesh=device_mesh, reshard_after_forward=True, mp_policy=mixed_precision_policy, offload_policy=OffloadPolicy())
155
+
156
+ if sync_module_state:
157
+ options = StateDictOptions(full_state_dict=True, cpu_offload=True, broadcast_from_rank0=True)
158
+ set_model_state_dict(module, full_state_dict, options=options)
159
+
160
+ return module
161
+
162
+
163
+ def dist_barrier():
164
+ if dist.is_initialized():
165
+ dist.barrier()
166
+
167
+
168
+ def get_dist_rank() -> int:
169
+ return int(os.environ.get('RANK', 0))
170
+
171
+
172
+ def get_world_size():
173
+ if dist.is_available() and dist.is_initialized():
174
+ return dist.get_world_size()
175
+ else:
176
+ return 1
177
+
178
+
179
+ def is_dist_initialized() -> bool:
180
+ return torch.distributed.is_initialized()
181
+
182
+
183
+ def destroy_process_group():
184
+ if is_dist_initialized():
185
+ dist_barrier()
186
+ torch.distributed.destroy_process_group()
187
+
188
+
189
+ def exit_failed_rank(code: int = 1) -> None:
190
+ """End this process now, without shutting down the process group.
191
+
192
+ Shutting down an NCCL group waits for every peer, and a peer still inside a
193
+ collective never arrives: a rank that failed alone would hang there until the
194
+ NCCL timeout. Exiting lets torchrun see the failure and stop the other ranks.
195
+ """
196
+ logging.shutdown()
197
+ sys.stdout.flush()
198
+ sys.stderr.flush()
199
+ os._exit(code)
200
+
201
+
202
+ def reduce_loss(loss):
203
+ """Mean of ``loss`` over all ranks.
204
+
205
+ Returns the local value when no process group exists, which is the identity
206
+ at one rank and is what makes the diagnostics testable. The latent-action
207
+ CPU suite exercises ``_diagnostics`` directly against a stub, and an
208
+ unconditional ``all_reduce`` put every metric in that path -- KL shares,
209
+ ``action_const_share``, the SNR split -- behind a live cluster, so the tests
210
+ written for them could not run at all.
211
+ """
212
+ rt = loss.detach().clone()
213
+ if not is_dist_initialized():
214
+ return rt.item()
215
+ dist.all_reduce(rt, op=dist.ReduceOp.SUM)
216
+ rt /= dist.get_world_size()
217
+ return rt.item()
218
+
219
+
220
+ def raise_if_any_rank_failed(error: str | None, device, message: str) -> None:
221
+ """All-reduce a per-rank failure flag and raise the same error on every rank.
222
+
223
+ Validation that only rank 0 can run (it alone holds a loaded file) must not
224
+ leave the other ranks waiting in their next collective.
225
+ """
226
+ from o2laf.utils.logger_util import get_logger # logger_util imports this module
227
+
228
+ if error is not None:
229
+ get_logger().error('%s: %s', message, error)
230
+ success = torch.tensor(float(error is None), device=device, dtype=torch.float32)
231
+ if dist.is_available() and dist.is_initialized():
232
+ dist.all_reduce(success, op=dist.ReduceOp.MIN)
233
+ if not bool(success.item()):
234
+ raise RuntimeError(f'{message}; see the error logged by the failing rank.')
235
+
236
+
237
+ def load_full_state_dict(module, source, *, required, label, source_name, device, unexpected='raise') -> None:
238
+ """Load a full (unsharded) state dict into an FSDP2 module from rank 0, checking keys first.
239
+
240
+ ``set_model_state_dict(..., full_state_dict=True, strict=False)`` reports no
241
+ missing keys, so absent tensors are detected here instead, by comparing
242
+ ``required`` (parameter names that must be restored) with ``source``'s keys
243
+ on rank 0. Other ranks may pass an empty ``source``. ``unexpected`` is
244
+ ``'raise'``, ``'warn'`` or ``'ignore'`` for source keys the module lacks.
245
+ """
246
+ rank = dist.get_rank() if dist.is_available() and dist.is_initialized() else 0
247
+ error = None
248
+ if rank == 0:
249
+ names = set(source)
250
+ absent = sorted(set(required) - names)
251
+ known = {name for name, _ in module.named_parameters()} | {name for name, _ in module.named_buffers()}
252
+ extra = sorted(names - known)
253
+ if absent:
254
+ error = f'{len(absent)} required {label} tensors are absent from {source_name}, e.g. {absent[:3]}.'
255
+ elif extra and unexpected == 'raise':
256
+ error = f'{len(extra)} unexpected {label} tensors in {source_name}, e.g. {extra[:3]}.'
257
+ elif extra and unexpected == 'warn':
258
+ from o2laf.utils.logger_util import get_logger # logger_util imports this module
259
+
260
+ get_logger().warning(f'{len(extra)} unexpected {label} keys in {source_name}, e.g. {extra[:3]}.')
261
+ raise_if_any_rank_failed(error, device, f'Could not load the {label} state')
262
+ set_model_state_dict(
263
+ module,
264
+ source if rank == 0 else {},
265
+ options=StateDictOptions(full_state_dict=True, broadcast_from_rank0=True, strict=False),
266
+ )
O2LaF/o2laf/utils/file_util.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Filesystem helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+
10
+
11
+ def sha256_file(path: str | os.PathLike) -> str:
12
+ """SHA256 of a file, read incrementally so large checkpoints stay out of memory."""
13
+ digest = hashlib.sha256()
14
+ with Path(path).open('rb') as handle:
15
+ while chunk := handle.read(8 << 20):
16
+ digest.update(chunk)
17
+ return digest.hexdigest()
18
+
19
+
20
+ def write_json_atomic(path: str | os.PathLike, payload) -> None:
21
+ """Write ``payload`` as JSON via a temporary file and an atomic rename."""
22
+ path = Path(path)
23
+ temporary = path.with_suffix(path.suffix + f'.tmp.{os.getpid()}')
24
+ temporary.write_text(json.dumps(payload, indent=2, sort_keys=True) + '\n', encoding='utf-8')
25
+ os.replace(temporary, path)
O2LaF/o2laf/utils/flex_attention.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+ """Flex-attention helpers shared by the action encoder and the world model.
17
+
18
+ Both models restrict self-attention with a token-level predicate. The predicate
19
+ is turned into a ``BlockMask`` here, and ``WanFlexAttnProcessor`` replaces the
20
+ stock Wan self-attention so that the mask installed on ``processor.block_mask``
21
+ is actually honoured.
22
+ """
23
+
24
+ import math
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ from diffusers.models.transformers.transformer_wan import _get_qkv_projections
29
+ from torch.nn.attention.flex_attention import BlockMask, flex_attention
30
+
31
+ flex_attention = torch.compile(flex_attention, dynamic=True)
32
+
33
+ BLOCK_SIZE = 128
34
+
35
+
36
+ def padded_length(seq_len: int) -> int:
37
+ """Round ``seq_len`` up to the flex-attention block size."""
38
+ return int(math.ceil(seq_len / float(BLOCK_SIZE)) * BLOCK_SIZE)
39
+
40
+
41
+ def pad_sequence_dim(tensor: torch.Tensor, padded_seq_len: int, dim: int = 1) -> torch.Tensor:
42
+ """Zero-pad ``tensor`` along ``dim`` up to ``padded_seq_len``."""
43
+ seq_len = tensor.shape[dim]
44
+ if seq_len == padded_seq_len:
45
+ return tensor
46
+ if seq_len > padded_seq_len:
47
+ raise ValueError(f'Cannot pad sequence dim {dim} from {seq_len} down to {padded_seq_len}')
48
+ pad_shape = list(tensor.shape)
49
+ pad_shape[dim] = padded_seq_len - seq_len
50
+ return torch.cat([tensor, tensor.new_zeros(pad_shape)], dim=dim)
51
+
52
+
53
+ def _ordered_block_columns(block_mask):
54
+ return torch.argsort(block_mask.to(torch.int32), dim=-1, descending=True, stable=True).to(torch.int32)
55
+
56
+
57
+ def build_block_mask(mask_mod, seq_len: int, device) -> BlockMask:
58
+ """Square ``BlockMask`` for a token predicate over ``seq_len`` positions.
59
+
60
+ Built on the host from the predicate evaluated one 128-row strip at a time,
61
+ so no flex-attention kernel is needed to construct it.
62
+ """
63
+ seq_len = int(seq_len)
64
+ num_blocks = math.ceil(seq_len / BLOCK_SIZE)
65
+ kv_num_blocks = torch.zeros((1, 1, num_blocks), dtype=torch.int32, device=device)
66
+ kv_indices = torch.zeros((1, 1, num_blocks, max(1, num_blocks)), dtype=torch.int32, device=device)
67
+ full_kv_num_blocks = torch.zeros_like(kv_num_blocks)
68
+ full_kv_indices = torch.zeros_like(kv_indices)
69
+
70
+ batch_index = torch.tensor(0, device=device)
71
+ head_index = torch.tensor(0, device=device)
72
+ kv_index = torch.arange(seq_len, device=device)[None, :]
73
+ padded_len = num_blocks * BLOCK_SIZE
74
+ with torch.no_grad():
75
+ for q_block in range(num_blocks):
76
+ q_start = q_block * BLOCK_SIZE
77
+ q_end = min(q_start + BLOCK_SIZE, seq_len)
78
+ q_index = torch.arange(q_start, q_end, device=device)[:, None]
79
+ allowed = mask_mod(batch_index, head_index, q_index, kv_index)
80
+ if not torch.is_tensor(allowed):
81
+ allowed = torch.as_tensor(allowed, device=device)
82
+ allowed = torch.broadcast_to(allowed.to(torch.bool), (q_end - q_start, seq_len))
83
+ if padded_len > seq_len:
84
+ allowed = torch.cat([allowed, allowed.new_zeros((q_end - q_start, padded_len - seq_len))], dim=1)
85
+ if q_end - q_start < BLOCK_SIZE:
86
+ allowed = torch.cat([allowed, allowed.new_zeros((BLOCK_SIZE - (q_end - q_start), padded_len))], dim=0)
87
+
88
+ block_sum = allowed.reshape(BLOCK_SIZE, num_blocks, BLOCK_SIZE).sum(dim=(0, 2))
89
+ block_all = block_sum == BLOCK_SIZE * BLOCK_SIZE
90
+ block_partial = (block_sum > 0) & ~block_all
91
+
92
+ kv_indices[0, 0, q_block] = _ordered_block_columns(block_partial)
93
+ full_kv_indices[0, 0, q_block] = _ordered_block_columns(block_all)
94
+ kv_num_blocks[0, 0, q_block] = int(block_partial.sum().item())
95
+ full_kv_num_blocks[0, 0, q_block] = int(block_all.sum().item())
96
+
97
+ return BlockMask.from_kv_blocks(
98
+ kv_num_blocks=kv_num_blocks,
99
+ kv_indices=kv_indices,
100
+ full_kv_num_blocks=full_kv_num_blocks,
101
+ full_kv_indices=full_kv_indices,
102
+ BLOCK_SIZE=(BLOCK_SIZE, BLOCK_SIZE),
103
+ mask_mod=mask_mod,
104
+ seq_lengths=(seq_len, seq_len),
105
+ )
106
+
107
+
108
+ # Masks kept per module; a handful of geometries at most, so a small bound only
109
+ # guards against a caller that varies its shapes without end.
110
+ BLOCK_MASK_CACHE_SIZE = 8
111
+
112
+
113
+ def cached_block_mask(owner, key, build):
114
+ """``build()``'s mask for ``key``, built once per owner and reused.
115
+
116
+ A mask depends only on the sequence geometry, never on the activations, and
117
+ building one costs a Python loop with two host-device syncs per 128-token
118
+ block -- on every forward pass, if it is not cached.
119
+ """
120
+ cache = owner.__dict__.setdefault('_block_mask_cache', {})
121
+ mask = cache.get(key)
122
+ if mask is None:
123
+ if len(cache) >= BLOCK_MASK_CACHE_SIZE:
124
+ cache.pop(next(iter(cache)))
125
+ mask = cache[key] = build()
126
+ return mask
127
+
128
+
129
+ def _apply_rotary_emb(hidden_states: torch.Tensor, freqs_cos: torch.Tensor, freqs_sin: torch.Tensor) -> torch.Tensor:
130
+ x1, x2 = hidden_states.unflatten(-1, (-1, 2)).unbind(-1)
131
+ cos = freqs_cos[..., 0::2]
132
+ sin = freqs_sin[..., 1::2]
133
+ out = torch.empty_like(hidden_states)
134
+ out[..., 0::2] = x1 * cos - x2 * sin
135
+ out[..., 1::2] = x1 * sin + x2 * cos
136
+ return out.type_as(hidden_states)
137
+
138
+
139
+ class WanFlexAttnProcessor:
140
+ """Wan self-attention that applies ``self.block_mask`` through flex attention.
141
+
142
+ With ``block_mask`` unset it falls back to plain SDPA, so the same processor
143
+ serves masked and unmasked calls.
144
+ """
145
+
146
+ def __init__(self):
147
+ self.block_mask = None
148
+
149
+ def _attend(self, query, key, value, attention_mask):
150
+ # A BlockMask needs the compiled flex kernel; a dense boolean mask (or
151
+ # none) runs through stock SDPA with no compilation at all.
152
+ if isinstance(attention_mask, BlockMask):
153
+ return flex_attention(query, key, value, block_mask=attention_mask)
154
+ return F.scaled_dot_product_attention(query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False)
155
+
156
+ def __call__(
157
+ self,
158
+ attn,
159
+ hidden_states: torch.Tensor,
160
+ encoder_hidden_states: torch.Tensor | None = None,
161
+ attention_mask: torch.Tensor | None = None,
162
+ rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
163
+ ) -> torch.Tensor:
164
+ query, key, value = _get_qkv_projections(attn, hidden_states, encoder_hidden_states)
165
+
166
+ if attn.norm_q is not None:
167
+ query = attn.norm_q(query)
168
+ if attn.norm_k is not None:
169
+ key = attn.norm_k(key)
170
+
171
+ query = query.unflatten(2, (attn.heads, -1))
172
+ key = key.unflatten(2, (attn.heads, -1))
173
+ value = value.unflatten(2, (attn.heads, -1))
174
+
175
+ if rotary_emb is not None:
176
+ query = _apply_rotary_emb(query, *rotary_emb)
177
+ key = _apply_rotary_emb(key, *rotary_emb)
178
+
179
+ if attention_mask is None:
180
+ attention_mask = self.block_mask
181
+ query = query.transpose(1, 2)
182
+ key = key.transpose(1, 2)
183
+ value = value.transpose(1, 2)
184
+
185
+ hidden_states = self._attend(query, key, value, attention_mask)
186
+
187
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
188
+ hidden_states = hidden_states.type_as(query)
189
+
190
+ hidden_states = attn.to_out[0](hidden_states)
191
+ hidden_states = attn.to_out[1](hidden_states)
192
+ return hidden_states
193
+
194
+
195
+ def install_flex_attention(blocks, processor_class=WanFlexAttnProcessor) -> None:
196
+ """Replace every block's self-attention processor with ``processor_class``."""
197
+ for block in blocks:
198
+ block.attn1.set_processor(processor_class())
199
+
200
+
201
+ def verify_flex_attention(blocks, processor_class=WanFlexAttnProcessor, label='model') -> None:
202
+ """Fail if any block still uses a processor that would ignore ``block_mask``.
203
+
204
+ Assigning ``block_mask`` to the stock diffusers processor parks an attribute
205
+ nobody reads, so attention silently stays unmasked.
206
+ """
207
+ stock = [index for index, block in enumerate(blocks) if not isinstance(block.attn1.processor, processor_class)]
208
+ if stock:
209
+ raise RuntimeError(
210
+ f'{len(stock)} of {len(blocks)} {label} blocks do not use {processor_class.__name__}, '
211
+ f'so the block mask would be silently ignored. First offending block: {stock[0]}.'
212
+ )
O2LaF/o2laf/utils/logger_util.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ import dataclasses
18
+ import datetime
19
+ import logging
20
+ import os
21
+ import os.path
22
+ import os.path as osp
23
+ import time
24
+ from dataclasses import dataclass
25
+ from typing import List, Optional
26
+
27
+ import torch
28
+ import torch.distributed as dist
29
+
30
+ from .dist_util import is_main_process
31
+
32
+
33
+ def _format_cuda_memory() -> str:
34
+ if not torch.cuda.is_available():
35
+ return ''
36
+ d = torch.cuda.current_device()
37
+ alloc = torch.cuda.memory_allocated(d) / (1024**3)
38
+ reserved = torch.cuda.memory_reserved(d) / (1024**3)
39
+ peak = torch.cuda.max_memory_allocated(d) / (1024**3)
40
+ return f'[cuda:{d} alloc {alloc:.2f}GiB reserved {reserved:.2f}GiB peak_alloc {peak:.2f}GiB] '
41
+
42
+
43
+ def _format_log_value(value) -> str:
44
+ if abs(value) < 1e-4:
45
+ return f'{value:.3e}'
46
+ return f'{value:.4f}'
47
+
48
+
49
+ # ----------- file/logger util ----------
50
+ def get_time_str():
51
+ return time.strftime('%Y%m%d_%H%M%S', time.localtime())
52
+
53
+
54
+ def make_exp_dirs(cfg):
55
+ """Make dirs for experiments."""
56
+ path_opt = cfg['path'].copy()
57
+ # An existing experiment directory is reused as it is: that is how a run resumes.
58
+ if cfg['mode'] == 'train':
59
+ os.makedirs(path_opt.pop('experiments_root'), exist_ok=True)
60
+ else:
61
+ os.makedirs(path_opt.pop('results_root'), exist_ok=True)
62
+ for key, path in path_opt.items():
63
+ if ('strict_load' in key) or ('pretrain_network' in key) or ('resume' in key) or ('param_key' in key) or ('lora_path' in key):
64
+ continue
65
+ else:
66
+ os.makedirs(path, exist_ok=True)
67
+
68
+
69
+ def copy_cfg_file(cfg, experiments_root):
70
+ """Write the config the run actually uses -- command-line overrides applied -- next to its outputs."""
71
+ import sys
72
+
73
+ import yaml
74
+
75
+ filename = osp.join(experiments_root, osp.basename(cfg['config_path']))
76
+ with open(filename, 'w', encoding='utf-8') as handle:
77
+ handle.write(f'# GENERATE TIME: {time.asctime()}\n# CMD:\n# {" ".join(sys.argv)}\n'
78
+ '# The resolved config, with every command-line override applied.\n\n')
79
+ yaml.safe_dump(cfg, handle, sort_keys=False)
80
+
81
+
82
+ def set_path_logger(cfg):
83
+
84
+ if 'path' not in cfg:
85
+ cfg['path'] = {}
86
+
87
+ if cfg['mode'] == 'train':
88
+ experiments_root = cfg['path'].get(
89
+ 'experiments_root', osp.join('experiments', cfg['name'])
90
+ )
91
+ cfg['path']['experiments_root'] = experiments_root
92
+ cfg['path']['models'] = osp.join(experiments_root, 'models')
93
+ cfg['path']['log'] = experiments_root
94
+ cfg['path']['visualization'] = osp.join(experiments_root, 'visualization')
95
+ else:
96
+ results_root = osp.join('results', cfg['name'])
97
+ cfg['path']['results_root'] = results_root
98
+ cfg['path']['log'] = results_root
99
+ cfg['path']['visualization'] = osp.join(results_root, 'visualization')
100
+
101
+ # Handle the output folder creation
102
+ if is_main_process():
103
+ make_exp_dirs(cfg)
104
+
105
+ if cfg['mode'] == 'train':
106
+ copy_cfg_file(cfg, cfg['path']['experiments_root'])
107
+ log_file = osp.join(cfg['path']['log'], f"train_{cfg['name']}_{get_time_str()}.log")
108
+ set_logger(log_file)
109
+ else:
110
+ copy_cfg_file(cfg, cfg['path']['results_root'])
111
+ log_file = osp.join(cfg['path']['log'], f"test_{cfg['name']}_{get_time_str()}.log")
112
+ set_logger(log_file)
113
+ else:
114
+ get_logger().propagate = False
115
+ get_logger().setLevel(logging.ERROR)
116
+ dist.barrier()
117
+
118
+
119
+ def get_logger():
120
+ logger = logging.getLogger('o2laf')
121
+ return logger
122
+
123
+
124
+ def set_logger(log_file=None):
125
+ # Make one log on every process with the configuration for debugging.
126
+ format_str = '%(asctime)s %(levelname)s: %(message)s'
127
+ log_level = logging.INFO
128
+
129
+ logger = get_logger()
130
+ logger.propagate = False
131
+ logger.setLevel(log_level)
132
+
133
+ file_handler = logging.FileHandler(log_file, 'w')
134
+ file_handler.setFormatter(logging.Formatter(format_str))
135
+ file_handler.setLevel(log_level)
136
+ logger.addHandler(file_handler)
137
+
138
+ stream_handler = logging.StreamHandler()
139
+ stream_handler.setFormatter(logging.Formatter(format_str))
140
+
141
+ logger.addHandler(stream_handler)
142
+
143
+
144
+ def dict2str(opt, indent_level=1):
145
+ """dict to string for printing options.
146
+
147
+ Args:
148
+ opt (dict): Option dict.
149
+ indent_level (int): Indent level. Default: 1.
150
+
151
+ Return:
152
+ (str): Option string for printing.
153
+ """
154
+ msg = '\n'
155
+ for k, v in opt.items():
156
+ if isinstance(v, dict):
157
+ msg += ' ' * (indent_level * 2) + k + ':['
158
+ msg += dict2str(v, indent_level + 1)
159
+ msg += ' ' * (indent_level * 2) + ']\n'
160
+ else:
161
+ msg += ' ' * (indent_level * 2) + k + ': ' + str(v) + '\n'
162
+ return msg
163
+
164
+
165
+ class MessageLogger():
166
+ """Message logger for printing.
167
+
168
+ Args:
169
+ opt (dict): Config. It contains the following keys:
170
+ name (str): Exp name.
171
+ logger (dict): Contains 'print_freq' (str) for logger interval.
172
+ train (dict): Contains 'total_iter' (int) for total iters.
173
+ use_tb_logger (bool): Use tensorboard logger.
174
+ start_iter (int): Start iter. Default: 1.
175
+ tb_logger (obj:`tb_logger`): Tensorboard logger. Default: None.
176
+ """
177
+ def __init__(self, opt, start_iter=1):
178
+ self.exp_name = opt['name']
179
+ self.interval = opt['logger']['print_freq']
180
+ self.start_iter = start_iter
181
+ self.max_iters = opt['train']['total_iter']
182
+ self.start_time = time.time()
183
+
184
+ def __call__(self, log_vars):
185
+ """Format logging message.
186
+
187
+ Args:
188
+ log_vars (dict): It contains the following keys:
189
+ epoch (int): Epoch number.
190
+ iter (int): Current iter.
191
+ lrs (list): List for learning rates.
192
+
193
+ time (float): Iter time.
194
+ data_time (float): Data time for each iter.
195
+ """
196
+ # epoch, iter, learning rates
197
+ current_iter = log_vars.pop('iter')
198
+
199
+ message = f'[{self.exp_name}][Iter:{current_iter:8,d}] '
200
+
201
+ # time and estimated time
202
+ total_time = time.time() - self.start_time
203
+ time_sec_avg = total_time / (current_iter - self.start_iter + 1)
204
+ eta_sec = time_sec_avg * (self.max_iters - current_iter - 1)
205
+ eta_str = str(datetime.timedelta(seconds=int(eta_sec)))
206
+ message += f'[eta: {eta_str}] '
207
+
208
+ # other items, especially losses
209
+ for k, v in log_vars.items():
210
+ if 'lr' in k:
211
+ message += f'{k}: {v:.3e} '
212
+ else:
213
+ message += f'{k}: {_format_log_value(v)} '
214
+
215
+ message += _format_cuda_memory()
216
+ get_logger().info(message)
217
+
218
+
219
+ def setup_wandb(name, save_dir):
220
+ try:
221
+ import wandb
222
+ except ImportError:
223
+ raise ImportError(
224
+ 'You are trying to use wandb which is not currently installed. '
225
+ 'Please install it using pip install wandb'
226
+ )
227
+ wandb_config = WANDB_CONFIG()
228
+ wandb_config.name = name
229
+ wandb_config.dir = save_dir
230
+
231
+ # auto resume
232
+ wandb_latest_dir = os.path.join(save_dir, 'wandb', 'latest-run')
233
+
234
+ if os.path.exists(wandb_latest_dir):
235
+ run_id = os.readlink(wandb_latest_dir).split('-')[-1]
236
+ wandb_config.id = run_id
237
+
238
+ init_dict = dataclasses.asdict(wandb_config)
239
+ run = wandb.init(**init_dict)
240
+ return run
241
+
242
+
243
+ @dataclass
244
+ class WANDB_CONFIG:
245
+ project: str = 'o2laf'
246
+ entity: Optional[str] = None
247
+ job_type: Optional[str] = None
248
+ tags: Optional[List[str]] = None
249
+ group: Optional[str] = None
250
+ notes: Optional[str] = None
251
+ mode: Optional[str] = None
252
+ name: Optional[str] = None
253
+ dir: Optional[str] = None
254
+ resume: str = 'allow'
255
+ id: Optional[str] = None
O2LaF/o2laf/utils/lora_util.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ import torch
18
+
19
+
20
+ # PEFT adapter name used for every LoRA in this package. It appears in
21
+ # checkpoint keys (``...lora_A.real.weight``), so it cannot change.
22
+ LORA_ADAPTER_NAME = 'real'
23
+
24
+ LORA_STATE_KEYS = ('lora_A', 'lora_B', 'lora_embedding_A', 'lora_embedding_B', 'lora_magnitude_vector')
25
+ LORA_AUXILIARY_STATE_KEYS = ('idm_head', 'action_embedder')
26
+
27
+
28
+ def canonical_lora_config(config):
29
+ """Return the architecture-defining LoRA fields in a comparable form."""
30
+ if config is None:
31
+ return None
32
+ targets = config.get('target_module_name')
33
+ if not isinstance(targets, str):
34
+ targets = tuple(targets)
35
+ return {
36
+ 'lora_rank': int(config['lora_rank']),
37
+ 'lora_alpha': int(config['lora_alpha']),
38
+ 'target_module_name': targets,
39
+ }
40
+
41
+
42
+ def validate_lora_config(configured, checkpoint, tag):
43
+ """Reject loading a checkpoint into a differently shaped LoRA tree."""
44
+ configured = canonical_lora_config(configured)
45
+ checkpoint = canonical_lora_config(checkpoint)
46
+ if configured != checkpoint:
47
+ raise ValueError(
48
+ f'{tag} LoRA config mismatch: checkpoint has {checkpoint}, '
49
+ f'but the YAML requests {configured}. Use the YAML that produced '
50
+ 'the checkpoint or start from a fresh experiment directory.'
51
+ )
52
+
53
+
54
+ def filter_learnable_module(model, target_module_name):
55
+ if target_module_name == 'all-linear':
56
+ return target_module_name
57
+ else:
58
+ assert isinstance(target_module_name, list)
59
+ target_modules = set()
60
+ for name, module in model.named_modules():
61
+ if isinstance(module, torch.nn.Linear):
62
+ for target in target_module_name:
63
+ if target in name:
64
+ target_modules.add(name)
65
+ return target_modules
66
+
67
+
68
+ def is_peft_model(model):
69
+ return any(hasattr(module, 'peft_config') for module in model.modules())
70
+
71
+
72
+ def get_lora_state_dict(transformer, state_type, ema=None):
73
+ if state_type == 'model':
74
+ return {
75
+ name: param.detach()
76
+ for name, param in transformer.named_parameters()
77
+ if any(key in name for key in LORA_STATE_KEYS + LORA_AUXILIARY_STATE_KEYS)
78
+ }
79
+ else:
80
+ assert state_type == 'ema'
81
+ ema_state_dict = ema.state_dict()
82
+ lora_ema_state_dict = {}
83
+
84
+ for name, _ in transformer.named_parameters():
85
+ if not any(key in name for key in LORA_STATE_KEYS + LORA_AUXILIARY_STATE_KEYS):
86
+ continue
87
+
88
+ ema_key = name.replace('.', '_')
89
+ if ema_key in ema_state_dict:
90
+ lora_ema_state_dict[name] = ema_state_dict[ema_key]
91
+
92
+ return lora_ema_state_dict
O2LaF/o2laf/utils/registry.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ """Small name-to-object registries used by AnyFlow-style builders."""
18
+
19
+
20
+ class Registry:
21
+ """Map stable configuration names to Python objects."""
22
+
23
+ def __init__(self, name):
24
+ self._name = str(name)
25
+ self._obj_map = {}
26
+
27
+ @property
28
+ def name(self):
29
+ return self._name
30
+
31
+ def _do_register(self, name, obj):
32
+ if name in self._obj_map:
33
+ raise KeyError(f"An object named '{name}' is already registered in '{self._name}'.")
34
+ self._obj_map[name] = obj
35
+
36
+ def register(self, obj=None):
37
+ """Register an object directly or use this method as a decorator."""
38
+
39
+ if obj is None:
40
+
41
+ def decorator(function_or_class):
42
+ self._do_register(function_or_class.__name__, function_or_class)
43
+ return function_or_class
44
+
45
+ return decorator
46
+
47
+ self._do_register(obj.__name__, obj)
48
+ return obj
49
+
50
+ def get(self, name):
51
+ if name not in self._obj_map:
52
+ available = ", ".join(sorted(self._obj_map)) or "<empty>"
53
+ raise KeyError(f"No object named '{name}' is registered in '{self._name}'. Available: {available}.")
54
+ return self._obj_map[name]
55
+
56
+ def keys(self):
57
+ return self._obj_map.keys()
58
+
59
+ def __contains__(self, name):
60
+ return name in self._obj_map
61
+
62
+ def __iter__(self):
63
+ return iter(self._obj_map.items())
64
+
65
+ def __len__(self):
66
+ return len(self._obj_map)
67
+
68
+
69
+ TRAINER_REGISTRY = Registry("trainers")
70
+ ACTION_ENCODER_REGISTRY = Registry("action_encoders")
71
+ WORLD_MODEL_REGISTRY = Registry("world_models")
72
+ DATASET_REGISTRY = Registry("datasets")
O2LaF/o2laf/utils/video_util.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ import os
18
+ import random
19
+ import tempfile
20
+ import warnings
21
+ from io import BytesIO
22
+ from typing import Optional
23
+
24
+ import numpy as np
25
+
26
+ # Decord's decoder thread count. Under many concurrent readers its threaded
27
+ # decoder can fail with `avcodec_send_packet ... (-11 vs. 0)`: -11 is EAGAIN, a
28
+ # back-pressure signal rather than a corrupt file, which decord treats as fatal.
29
+ # One thread is the documented workaround; parallelism comes from dataloader
30
+ # workers instead. Decoded pixels are unchanged. Files that still fail are read
31
+ # with PyAV (see `VideoLoader._switch_to_pyav`).
32
+ DECORD_NUM_THREADS = 1
33
+
34
+
35
+ class VideoLoader:
36
+ def __init__(
37
+ self,
38
+ fp: str | BytesIO,
39
+ name: Optional[str] = None,
40
+ ):
41
+ self.video_reader = None
42
+ self.temp_video_name = None
43
+ self.video_path = None
44
+ self._backend = None
45
+ self._decord_error = None
46
+
47
+ if isinstance(fp, str):
48
+ name = name or fp
49
+ self.video_path = fp
50
+ elif isinstance(fp, BytesIO):
51
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as temp_video:
52
+ self.temp_video_name = temp_video.name
53
+ temp_video.write(fp.read())
54
+ temp_video.flush()
55
+ name = name or self.temp_video_name
56
+ self.video_path = self.temp_video_name
57
+ else:
58
+ raise ValueError(f'Type {type(fp)} is not supported')
59
+ self.name = name
60
+
61
+ try:
62
+ self._open_decord()
63
+ except Exception as decord_error:
64
+ # Decord 0.6.x cannot open every codec/container combination seen
65
+ # in web-video corpora. In particular, builds without AV1 support
66
+ # report "cannot find video stream", and streams whose codec pixel
67
+ # format is unknown until the first decoded frame fail while
68
+ # creating Decord's filter graph with pix_fmt=-1. PyAV/FFmpeg can
69
+ # decode both cases, so retain Decord as the fast path and switch
70
+ # only the affected sample to a sequential PyAV reader.
71
+ try:
72
+ self._switch_to_pyav(decord_error)
73
+ except Exception:
74
+ self.close()
75
+ raise
76
+
77
+ def _open_decord(self):
78
+ import decord
79
+
80
+ self.video_reader = decord.VideoReader(
81
+ self.video_path, num_threads=DECORD_NUM_THREADS
82
+ )
83
+ self._backend = 'decord'
84
+
85
+ def _release_decord_reader(self):
86
+ # VideoReader has no public close(). Dropping the last Python reference
87
+ # invokes its destructor, which frees the native reader and joins its
88
+ # decoder thread. Do this before unlinking a temporary input file.
89
+ video_reader = self.video_reader
90
+ self.video_reader = None
91
+ if video_reader is not None:
92
+ del video_reader
93
+
94
+ def _switch_to_pyav(self, decord_error):
95
+ # Do not retain the exception itself: its traceback can hold a bound
96
+ # get_batch() frame and therefore keep the failed native reader alive.
97
+ self._decord_error = (
98
+ f'{type(decord_error).__name__}: {decord_error}'
99
+ )
100
+ self._release_decord_reader()
101
+ try:
102
+ self._read_pyav_metadata()
103
+ except Exception as pyav_error:
104
+ raise RuntimeError(
105
+ f'{self.name} could not be opened by Decord or PyAV. '
106
+ f'Decord: {type(decord_error).__name__}: {decord_error}; '
107
+ f'PyAV: {type(pyav_error).__name__}: {pyav_error}'
108
+ ) from pyav_error
109
+ self._backend = 'pyav'
110
+
111
+ def _read_pyav_metadata(self):
112
+ import av
113
+
114
+ with av.open(self.video_path) as container:
115
+ stream = next(
116
+ (candidate for candidate in container.streams
117
+ if candidate.type == 'video'),
118
+ None,
119
+ )
120
+ if stream is None:
121
+ raise RuntimeError('MP4 sample does not contain a video stream.')
122
+
123
+ fps_fraction = (
124
+ stream.average_rate
125
+ or stream.guessed_rate
126
+ or stream.base_rate
127
+ )
128
+ if fps_fraction is None:
129
+ raise RuntimeError('MP4 video stream does not report an FPS.')
130
+ fps = float(fps_fraction)
131
+ if not np.isfinite(fps) or fps <= 0:
132
+ raise RuntimeError(f'Invalid video FPS: {fps}.')
133
+
134
+ # nb_frames is frequently stale in clipped web videos. Their
135
+ # stream duration and average rate agree with the actual decoded
136
+ # frame count, while nb_frames can be off by hundreds of frames.
137
+ # Prefer duration-derived count and retain nb_frames as a fallback
138
+ # for containers that do not expose stream duration.
139
+ frame_count = 0
140
+ if stream.duration is not None and stream.time_base is not None:
141
+ duration_seconds = float(stream.duration * stream.time_base)
142
+ if np.isfinite(duration_seconds) and duration_seconds > 0:
143
+ frame_count = int(round(duration_seconds * fps))
144
+ if frame_count <= 0:
145
+ frame_count = int(stream.frames or 0)
146
+ if frame_count <= 0:
147
+ raise RuntimeError(
148
+ 'MP4 video stream does not report a usable frame count.'
149
+ )
150
+
151
+ self._pyav_video_stream_index = stream.index
152
+ self._pyav_frame_count = frame_count
153
+ self._pyav_fps = fps
154
+
155
+ def close(self):
156
+ self._release_decord_reader()
157
+ if self.temp_video_name is not None:
158
+ if os.path.exists(self.temp_video_name):
159
+ os.remove(self.temp_video_name)
160
+ self.temp_video_name = None
161
+
162
+ def __enter__(self):
163
+ return self
164
+
165
+ def __exit__(self, exc_type, exc_value, traceback):
166
+ self.close()
167
+
168
+ def __del__(self):
169
+ try:
170
+ self.close()
171
+ except Exception:
172
+ pass
173
+
174
+ def get_frame_count(self):
175
+ if self._backend == 'decord':
176
+ return len(self.video_reader)
177
+ return self._pyav_frame_count
178
+
179
+ def get_fps(self) -> Optional[float]:
180
+ if self._backend == 'decord':
181
+ return self.video_reader.get_avg_fps()
182
+ return self._pyav_fps
183
+
184
+ @staticmethod
185
+ def _to_numpy(frames):
186
+ if isinstance(frames, np.ndarray):
187
+ return frames
188
+ if hasattr(frames, 'asnumpy'):
189
+ return frames.asnumpy()
190
+ if hasattr(frames, 'numpy'):
191
+ return frames.numpy()
192
+ return np.asarray(frames)
193
+
194
+ def _get_batch_decord(self, frame_idxs):
195
+ frames = self.video_reader.get_batch(frame_idxs)
196
+ return self._to_numpy(frames)
197
+
198
+ def _get_batch_pyav(self, frame_idxs):
199
+ import av
200
+
201
+ requested = [int(index) for index in frame_idxs]
202
+ wanted = set(requested)
203
+ last_wanted = max(wanted)
204
+ decoded = {}
205
+ decoded_count = 0
206
+
207
+ with av.open(self.video_path) as container:
208
+ stream = next(
209
+ (
210
+ candidate
211
+ for candidate in container.streams
212
+ if candidate.index == self._pyav_video_stream_index
213
+ ),
214
+ None,
215
+ )
216
+ if stream is None:
217
+ raise RuntimeError(
218
+ 'The video stream disappeared when reopening the MP4.'
219
+ )
220
+ # Parallelism already comes from DataLoader workers. Keeping each
221
+ # fallback decoder single-threaded avoids multiplying native
222
+ # decoder threads in the same way as the Decord fast path.
223
+ stream.codec_context.thread_count = 1
224
+ for frame in container.decode(stream):
225
+ if decoded_count in wanted:
226
+ decoded[decoded_count] = frame.to_ndarray(format='rgb24')
227
+ if len(decoded) == len(wanted):
228
+ break
229
+ decoded_count += 1
230
+ if decoded_count > last_wanted:
231
+ break
232
+
233
+ missing = sorted(wanted.difference(decoded))
234
+ if missing:
235
+ raise RuntimeError(
236
+ f'{self.name} decoded only {decoded_count} frames with PyAV; '
237
+ f'requested source frame(s) {missing[:8]}.'
238
+ )
239
+ return np.stack([decoded[index] for index in requested], axis=0)
240
+
241
+ def _get_batch(self, frame_idxs):
242
+ if self._backend == 'pyav':
243
+ return self._get_batch_pyav(frame_idxs)
244
+
245
+ try:
246
+ return self._get_batch_decord(frame_idxs)
247
+ except Exception as decord_error:
248
+ # Some Decord failures (notably decoder EAGAIN and filter-graph
249
+ # setup failures) are raised only on the first get_batch(), after
250
+ # VideoReader construction and metadata queries succeeded.
251
+ self._switch_to_pyav(decord_error)
252
+ try:
253
+ return self._get_batch_pyav(frame_idxs)
254
+ except Exception as pyav_error:
255
+ raise RuntimeError(
256
+ f'{self.name} failed to decode with Decord and the PyAV '
257
+ f'fallback. Decord: {type(decord_error).__name__}: '
258
+ f'{decord_error}; PyAV: {type(pyav_error).__name__}: '
259
+ f'{pyav_error}'
260
+ ) from pyav_error
261
+
262
+ def get_frames(self, frame_idxs):
263
+ """Decode the requested 0-based frame indices as uint8 ``[N,H,W,3]``."""
264
+ return self._get_batch(frame_idxs)
265
+
266
+ def get_clip(self, num_frames: int, target_fps=None, random_sample=False, source_frame_start=0):
267
+ """Decode ``num_frames`` frames at ``target_fps`` starting at or after ``source_frame_start``.
268
+
269
+ With ``random_sample`` the clip starts at a random resampled frame,
270
+ otherwise at the first one.
271
+ """
272
+ original_fps = self.get_fps()
273
+ total_frames = self.get_frame_count()
274
+ source_frame_start = int(source_frame_start)
275
+ source_frame_end = total_frames
276
+ if not 0 <= source_frame_start < source_frame_end <= total_frames:
277
+ raise ValueError(
278
+ 'Source frame range must satisfy '
279
+ f'0 <= start < end <= {total_frames}, got '
280
+ f'[{source_frame_start}, {source_frame_end}).'
281
+ )
282
+
283
+ if target_fps is None:
284
+ target_fps = original_fps
285
+
286
+ if original_fps and target_fps > original_fps:
287
+ # select_frame_indices cannot upsample: with a stride above 1 every
288
+ # frame passes the accumulator test, so it returns the clip at its
289
+ # native rate and raises nothing. The caller then trains or evaluates
290
+ # on slower motion per frame than it asked for, silently. Warn rather
291
+ # than raise -- a corpus of millions of clips should not stop for one
292
+ # low-rate outlier -- but do not let it pass unnoticed. The fps values
293
+ # are rounded so the number of distinct messages stays small and
294
+ # Python's default "once per unique message" filter keeps this quiet.
295
+ warnings.warn(
296
+ f'Requested {target_fps} fps from a {round(original_fps)} fps '
297
+ f'source; frames are returned at the native rate, so the motion '
298
+ f'per frame is lower than requested.',
299
+ RuntimeWarning,
300
+ stacklevel=2,
301
+ )
302
+
303
+ frame_idxs = select_frame_indices(
304
+ source_frame_end - source_frame_start,
305
+ original_fps,
306
+ target_fps=target_fps
307
+ )
308
+ frame_idxs = [source_frame_start + index for index in frame_idxs]
309
+ if len(frame_idxs) < num_frames:
310
+ raise RuntimeError(f'{self.name} only has {len(frame_idxs)} frames at {target_fps} fps, expected {num_frames} frames.')
311
+
312
+ if random_sample and len(frame_idxs) > num_frames:
313
+ start_idx = random.randint(0, len(frame_idxs) - num_frames)
314
+ else:
315
+ start_idx = 0
316
+ frame_idxs = frame_idxs[start_idx:start_idx + num_frames]
317
+ return self._get_batch(frame_idxs)
318
+
319
+
320
+ def select_frame_indices(total_frames, original_fps, target_fps):
321
+
322
+ accumulator_step = target_fps / original_fps
323
+ accumulator = 0.0
324
+
325
+ frame_idxs = [0]
326
+
327
+ for i in range(1, total_frames):
328
+ accumulator += accumulator_step
329
+
330
+ if accumulator >= 1.0:
331
+ frame_idxs.append(i)
332
+ accumulator -= 1.0
333
+
334
+ return frame_idxs
O2LaF/o2laf/world_models/__init__.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """World models: action-conditioned video generators."""
2
+
3
+ from o2laf.utils.registry import WORLD_MODEL_REGISTRY
4
+ from o2laf.world_models import wan # noqa: F401 (registration)
5
+
6
+
7
+ def build_world_model(name):
8
+ """Return the world model class registered under ``name``."""
9
+ return WORLD_MODEL_REGISTRY.get(name)
10
+
11
+
12
+ def build_world_model_from_config(transformer_cfg, action_cfg, *, num_latent_frames, causal, dtype, model_class=None,
13
+ **load_kwargs):
14
+ """Construct an action-conditioned world model from the config, ready to adapt.
15
+
16
+ Training and inference agree up to this point and diverge after it: training
17
+ attaches PEFT, selects trainable parameters and wraps in FSDP2; inference
18
+ loads weights and freezes. Only the construction is shared, so that which
19
+ config key means what is written down once.
20
+
21
+ ``load_kwargs`` (``cache_dir``, ``token``, ...) go to ``from_pretrained``.
22
+ ``model_class`` bypasses the registry lookup of ``transformer_cfg['model_type']``;
23
+ tests use it to substitute a stand-in for the 5B-parameter model.
24
+ """
25
+ if model_class is None:
26
+ model_class = build_world_model(transformer_cfg['model_type'])
27
+ world_model = model_class.from_pretrained(
28
+ transformer_cfg['model_name'], subfolder='transformer', torch_dtype=dtype, **load_kwargs
29
+ )
30
+ world_model.setup_world_model(
31
+ num_latent_frames=int(num_latent_frames),
32
+ causal=bool(causal),
33
+ action_dim=int((action_cfg or {}).get('latent_action_dim', 32)),
34
+ action_gain_init=float((action_cfg or {}).get('gamma_init', 0.5)),
35
+ )
36
+ return world_model
37
+
38
+
39
+ __all__ = ['build_world_model', 'build_world_model_from_config']
O2LaF/o2laf/world_models/wan.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+ """Action-conditioned Wan 2.2 world model.
17
+
18
+ The world model predicts the flow-matching velocity of a video given its clean
19
+ first latent frame and one latent action per later frame. Actions enter as a
20
+ per-frame bias on the timestep embedding, *before* ``time_proj``, so they mix
21
+ nonlinearly with the timestep through pretrained weights and reach all six
22
+ AdaLN channels of every block.
23
+
24
+ The same class serves both attention regimes:
25
+
26
+ * causal: frame ``t`` attends to frames ``0..t`` (block mask via flex attention);
27
+ * bidirectional: every frame attends to every frame (stock SDPA).
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import math
33
+ from types import SimpleNamespace
34
+ from typing import Any
35
+
36
+ import torch
37
+ import torch.nn as nn
38
+ from diffusers import WanTransformer3DModel
39
+ from diffusers.utils import apply_lora_scale
40
+
41
+ from o2laf.utils.flex_attention import (
42
+ build_block_mask,
43
+ cached_block_mask,
44
+ install_flex_attention,
45
+ pad_sequence_dim,
46
+ padded_length,
47
+ verify_flex_attention,
48
+ )
49
+ from o2laf.utils.registry import WORLD_MODEL_REGISTRY
50
+
51
+
52
+ def _full_tensor(tensor: torch.Tensor) -> torch.Tensor:
53
+ """All-gather an FSDP2 DTensor; pass a plain tensor through unchanged."""
54
+ return tensor.full_tensor() if hasattr(tensor, 'full_tensor') else tensor
55
+
56
+
57
+ class ActionEmbedder(nn.Module):
58
+ """``gamma * Linear(action)``: maps an action code to a timestep-embedding bias.
59
+
60
+ ``gamma`` is a learnable scalar gain. Read it through :meth:`effective_gain`
61
+ rather than on its own: ``gamma`` and the projection weight are
62
+ multiplicatively coupled, so only their product says how strongly actions
63
+ reach the model.
64
+ """
65
+
66
+ def __init__(self, in_features: int, out_features: int, gain_init: float = 0.5):
67
+ super().__init__()
68
+ self.linear = nn.Linear(in_features, out_features)
69
+ nn.init.xavier_uniform_(self.linear.weight)
70
+ nn.init.zeros_(self.linear.bias)
71
+ # Shape [1] rather than 0-dim: FSDP2's fully_shard rejects 0-dim
72
+ # parameters. Broadcasting is identical.
73
+ self.gamma = nn.Parameter(torch.full((1,), float(gain_init)))
74
+
75
+ def forward(self, actions: torch.Tensor) -> torch.Tensor:
76
+ return self.gamma * self.linear(actions)
77
+
78
+ def _active_adapters(self) -> tuple[str, ...]:
79
+ active = getattr(self.linear, 'active_adapters', None)
80
+ if active is None:
81
+ active = getattr(self.linear, 'active_adapter', None)
82
+ if active is None:
83
+ return ()
84
+ return (active,) if isinstance(active, str) else tuple(active)
85
+
86
+ @torch.no_grad()
87
+ def composite_weight(self) -> torch.Tensor:
88
+ """The projection's effective weight, including any LoRA adapter.
89
+
90
+ Under an ``all-linear`` LoRA target ``self.linear`` is a PEFT
91
+ ``lora.Linear`` and ``self.linear.weight`` resolves to the base weight
92
+ alone, which would hide most of the trainable path.
93
+ """
94
+ if getattr(self.linear, 'lora_magnitude_vector', None):
95
+ raise NotImplementedError('effective_gain cannot account for DoRA magnitude scaling.')
96
+ base = getattr(self.linear, 'base_layer', self.linear)
97
+ weight = _full_tensor(base.weight.detach()).float()
98
+ lora_A = getattr(self.linear, 'lora_A', None)
99
+ lora_B = getattr(self.linear, 'lora_B', None)
100
+ if lora_A is None or lora_B is None:
101
+ return weight
102
+ for name in self._active_adapters():
103
+ if name not in lora_A or name not in lora_B:
104
+ continue
105
+ a = _full_tensor(lora_A[name].weight.detach()).float()
106
+ b = _full_tensor(lora_B[name].weight.detach()).float()
107
+ scaling = float(getattr(self.linear, 'scaling', {}).get(name, 1.0))
108
+ weight = weight + scaling * (b @ a)
109
+ return weight
110
+
111
+ @torch.no_grad()
112
+ def effective_gain(self) -> float:
113
+ """``|gamma| * ||W||_F / sqrt(out_features)``, the action-path strength.
114
+
115
+ Every tensor read here may be an FSDP2 DTensor and is all-gathered, so
116
+ this is a collective and must be called on all ranks.
117
+ """
118
+ gamma = _full_tensor(self.gamma.detach()).float()
119
+ weight = self.composite_weight()
120
+ scale = math.sqrt(weight.shape[0])
121
+ return float(gamma.reshape(-1)[0].abs() * weight.norm() / scale)
122
+
123
+
124
+ @WORLD_MODEL_REGISTRY.register()
125
+ class WanWorldModel(WanTransformer3DModel):
126
+ """Wan 2.2 transformer conditioned on one action per latent frame."""
127
+
128
+ def setup_world_model(
129
+ self,
130
+ *,
131
+ num_latent_frames: int,
132
+ causal: bool,
133
+ action_dim: int,
134
+ action_gain_init: float,
135
+ ) -> None:
136
+ """Configure attention and attach the action embedder.
137
+
138
+ Call after ``from_pretrained()`` and before PEFT, so that PEFT sees the
139
+ final module tree.
140
+ """
141
+ self.register_to_config(
142
+ chunk_partition=[1] * int(num_latent_frames),
143
+ causal_attention=bool(causal),
144
+ action_dim=int(action_dim),
145
+ action_gain_init=float(action_gain_init),
146
+ )
147
+ if causal:
148
+ install_flex_attention(self.blocks)
149
+ verify_flex_attention(self.blocks, label='world model')
150
+ inner_dim = int(self.config.num_attention_heads * self.config.attention_head_dim)
151
+ self.action_embedder = ActionEmbedder(
152
+ in_features=int(action_dim),
153
+ out_features=inner_dim,
154
+ gain_init=float(action_gain_init),
155
+ )
156
+
157
+ @property
158
+ def causal(self) -> bool:
159
+ return bool(getattr(self.config, 'causal_attention', True))
160
+
161
+ def compute_action_bias(self, actions: torch.Tensor) -> torch.Tensor:
162
+ """Embed packed actions ``[B, F, r, D]`` into a per-frame bias ``[B, F, C]``.
163
+
164
+ Each action of a latent frame's group is embedded independently and the
165
+ group is mean-pooled. Frame 0 is produced by no transition, so its bias is
166
+ exactly zero; otherwise the embedder's own bias would leak a constant into
167
+ the clean context frame.
168
+ """
169
+ if not hasattr(self, 'action_embedder'):
170
+ raise RuntimeError('setup_world_model() must run before passing actions.')
171
+ action_dim = int(self.config.action_dim)
172
+ if actions.ndim != 4:
173
+ raise ValueError(f'actions must be packed to [B, F, r, D]; got {tuple(actions.shape)}.')
174
+ if actions.shape[-1] != action_dim:
175
+ raise ValueError(f'action width {actions.shape[-1]} != configured action_dim {action_dim}.')
176
+ embeds = self.action_embedder(actions).mean(dim=2)
177
+ return torch.cat([torch.zeros_like(embeds[:, :1]), embeds[:, 1:]], dim=1)
178
+
179
+ def forward(
180
+ self,
181
+ hidden_states: torch.Tensor,
182
+ *,
183
+ actions: torch.Tensor | None = None,
184
+ action_keep_mask: torch.Tensor | None = None,
185
+ temb_bias: torch.Tensor | None = None,
186
+ **kwargs: Any,
187
+ ) -> torch.Tensor | SimpleNamespace:
188
+ """Velocity prediction.
189
+
190
+ Pass either ``actions`` (packed ``[B, F, r, D]``, embedded here) or a
191
+ precomputed ``temb_bias`` (``[B, F, C]``), not both. With neither, no
192
+ action reaches the model. ``action_keep_mask`` ``[B]`` zeroes the bias of
193
+ the samples it marks False, which is the training-time action dropout.
194
+ """
195
+ if actions is not None:
196
+ if temb_bias is not None:
197
+ raise ValueError('Pass `actions` xor `temb_bias`, not both.')
198
+ temb_bias = self.compute_action_bias(actions)
199
+ if action_keep_mask is not None:
200
+ temb_bias = temb_bias * action_keep_mask.to(temb_bias.dtype).view(-1, 1, 1)
201
+ return self._denoise(hidden_states, temb_bias=temb_bias, **kwargs)
202
+
203
+ def _inject_action_bias(self, temb, temb_bias, ts_seq_len, num_frames, chunk_frames):
204
+ """Add the per-frame action bias to ``temb`` and re-run ``time_proj``.
205
+
206
+ Runs while ``temb`` is still per frame, before the frame-to-token
207
+ expansion, so row ``f`` of the bias lines up with row ``f`` of ``temb``.
208
+ Each check below guards a silent action-to-frame misalignment.
209
+ """
210
+ if ts_seq_len is None or temb.ndim != 3:
211
+ raise ValueError(
212
+ 'temb_bias requires per-frame timesteps: pass timestep with shape [B, F]. '
213
+ f'Got ts_seq_len={ts_seq_len}, temb.ndim={temb.ndim}.'
214
+ )
215
+ if temb.shape[1] != num_frames:
216
+ raise ValueError(f'temb has {temb.shape[1]} rows but {num_frames} frames were expected.')
217
+ if chunk_frames != num_frames:
218
+ raise ValueError(
219
+ f'chunk_partition covers {chunk_frames} frames but the input has {num_frames}; '
220
+ 'the causal mask and the action bias would disagree about frame boundaries.'
221
+ )
222
+ expected_bias_shape = (temb.shape[0], num_frames, temb.shape[2])
223
+ if tuple(temb_bias.shape) != expected_bias_shape:
224
+ raise ValueError(f'temb_bias must be {expected_bias_shape}, got {tuple(temb_bias.shape)}.')
225
+
226
+ temb = temb + temb_bias.to(temb.dtype)
227
+ condition_embedder = self.condition_embedder
228
+ projection_dtype = condition_embedder.time_proj.weight.dtype
229
+ timestep_proj = condition_embedder.time_proj(condition_embedder.act_fn(temb.to(projection_dtype)))
230
+ return temb, timestep_proj
231
+
232
+ def _causal_block_mask(self, chunk_partition, token_per_frame, real_seq_len, padded_seq_len, device):
233
+ key = (tuple(int(length) for length in chunk_partition), int(token_per_frame), int(real_seq_len),
234
+ int(padded_seq_len), str(device))
235
+ return cached_block_mask(
236
+ self, key,
237
+ lambda: self._build_causal_block_mask(chunk_partition, token_per_frame, real_seq_len, padded_seq_len, device),
238
+ )
239
+
240
+ @staticmethod
241
+ def _build_causal_block_mask(chunk_partition, token_per_frame, real_seq_len, padded_seq_len, device):
242
+ frame_idx = torch.cat(
243
+ [
244
+ torch.full((chunk_len * token_per_frame,), chunk_idx, device=device, dtype=torch.long)
245
+ for chunk_idx, chunk_len in enumerate(chunk_partition)
246
+ ],
247
+ dim=0,
248
+ )
249
+ frame_idx = torch.cat([frame_idx, frame_idx.new_zeros(padded_seq_len - real_seq_len)], dim=0)
250
+
251
+ def mask_mod(b, h, q_idx, kv_idx):
252
+ is_padding = (q_idx >= real_seq_len) | (kv_idx >= real_seq_len)
253
+ return (frame_idx[q_idx] >= frame_idx[kv_idx]) & ~is_padding
254
+
255
+ return build_block_mask(mask_mod, padded_seq_len, device)
256
+
257
+ @apply_lora_scale('attention_kwargs')
258
+ def _denoise(
259
+ self,
260
+ hidden_states: torch.Tensor,
261
+ chunk_partition: list[int] | None = None,
262
+ timestep: torch.LongTensor | None = None,
263
+ encoder_hidden_states: torch.Tensor | None = None,
264
+ r_timestep: torch.LongTensor | None = None,
265
+ encoder_hidden_states_image: torch.Tensor | None = None,
266
+ return_dict: bool = True,
267
+ attention_kwargs: dict[str, Any] | None = None,
268
+ temb_bias: torch.Tensor | None = None,
269
+ ) -> torch.Tensor | SimpleNamespace:
270
+ # `r_timestep` is accepted for call-site symmetry with the scheduler's
271
+ # (t, r) step and is not used by plain flow matching.
272
+ del r_timestep, attention_kwargs
273
+ if chunk_partition is None:
274
+ chunk_partition = list(self.config.chunk_partition)
275
+ causal = self.causal
276
+
277
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
278
+ p_t, p_h, p_w = self.config.patch_size
279
+ post_patch_num_frames = num_frames // p_t
280
+ post_patch_height = height // p_h
281
+ post_patch_width = width // p_w
282
+
283
+ rotary_emb = self.rope(hidden_states)
284
+
285
+ hidden_states = self.patch_embedding(hidden_states)
286
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
287
+ hidden_states = hidden_states.contiguous()
288
+ sequence_length = hidden_states.shape[1]
289
+
290
+ if timestep.ndim == 2:
291
+ ts_seq_len = timestep.shape[1]
292
+ timestep = timestep.flatten()
293
+ else:
294
+ ts_seq_len = None
295
+
296
+ temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
297
+ timestep, encoder_hidden_states, encoder_hidden_states_image, timestep_seq_len=ts_seq_len
298
+ )
299
+ if temb_bias is not None:
300
+ temb, timestep_proj = self._inject_action_bias(
301
+ temb,
302
+ temb_bias,
303
+ ts_seq_len=ts_seq_len,
304
+ num_frames=post_patch_num_frames,
305
+ chunk_frames=sum(chunk_partition),
306
+ )
307
+ if ts_seq_len is not None:
308
+ condition_seq_len = temb.shape[1]
309
+ if condition_seq_len != sequence_length:
310
+ repeat = sequence_length // condition_seq_len
311
+ temb = temb.repeat_interleave(repeat, dim=1)
312
+ timestep_proj = timestep_proj.repeat_interleave(repeat, dim=1)
313
+ timestep_proj = timestep_proj.unflatten(2, (6, -1))
314
+ else:
315
+ timestep_proj = timestep_proj.unflatten(1, (6, -1))
316
+
317
+ token_per_frame = post_patch_height * post_patch_width
318
+ real_seq_len = sum(chunk_partition) * token_per_frame
319
+ if causal:
320
+ padded_seq_len = padded_length(real_seq_len)
321
+ attention_mask = self._causal_block_mask(
322
+ chunk_partition, token_per_frame, real_seq_len, padded_seq_len, hidden_states.device
323
+ )
324
+ hidden_states = pad_sequence_dim(hidden_states, padded_seq_len, dim=1)
325
+ if timestep_proj.ndim == 4:
326
+ timestep_proj = pad_sequence_dim(timestep_proj, padded_seq_len, dim=1)
327
+ rotary_emb = tuple(pad_sequence_dim(freqs, padded_seq_len, dim=1) for freqs in rotary_emb)
328
+
329
+ if encoder_hidden_states_image is not None:
330
+ encoder_hidden_states = torch.concat([encoder_hidden_states_image, encoder_hidden_states], dim=1)
331
+
332
+ # The mask is left installed on return: under gradient checkpointing the
333
+ # blocks are re-run during backward and must see the same mask.
334
+ checkpointing = torch.is_grad_enabled() and self.gradient_checkpointing
335
+ for block in self.blocks:
336
+ if causal:
337
+ block.attn1.processor.block_mask = attention_mask
338
+ if checkpointing:
339
+ hidden_states = self._gradient_checkpointing_func(
340
+ block, hidden_states, encoder_hidden_states, timestep_proj, rotary_emb
341
+ )
342
+ else:
343
+ hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb)
344
+
345
+ hidden_states = hidden_states[:, :sequence_length]
346
+
347
+ if temb.ndim == 3:
348
+ shift, scale = (self.scale_shift_table.unsqueeze(0).to(temb.device) + temb.unsqueeze(2)).chunk(2, dim=2)
349
+ shift = shift.squeeze(2)
350
+ scale = scale.squeeze(2)
351
+ else:
352
+ shift, scale = (self.scale_shift_table.to(temb.device) + temb.unsqueeze(1)).chunk(2, dim=1)
353
+
354
+ shift = shift.to(hidden_states.device)
355
+ scale = scale.to(hidden_states.device)
356
+
357
+ hidden_states = (self.norm_out(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
358
+ hidden_states = self.proj_out(hidden_states)
359
+
360
+ hidden_states = hidden_states.reshape(
361
+ batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
362
+ )
363
+ hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
364
+ output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3).contiguous()
365
+
366
+ if not return_dict:
367
+ return output
368
+ return SimpleNamespace(sample=output)
O2LaF/pyproject.toml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ # Inference-only fork of https://github.com/showlab/O2LaF for the O2LaF demo
6
+ # Space: wan_dit action encoder + bidirectional/causal world model, no training.
7
+ [project]
8
+ name = "o2laf"
9
+ version = "0.1.0+demo"
10
+ description = "O2LaF inference: latent actions and action-conditioned world models on Wan 2.2"
11
+ readme = "README.md"
12
+ license = "MIT AND Apache-2.0"
13
+ license-files = ["LICENSE"]
14
+ requires-python = ">=3.10"
15
+ dependencies = [
16
+ "torch>=2.8",
17
+ "av",
18
+ "diffusers==0.39.0",
19
+ "huggingface_hub",
20
+ "imageio",
21
+ "imageio-ffmpeg",
22
+ "numpy",
23
+ "opencv-python-headless",
24
+ "peft==0.17.0",
25
+ "Pillow",
26
+ "safetensors",
27
+ "transformers==4.49.0",
28
+ ]
29
+
30
+ [tool.setuptools.packages.find]
31
+ include = ["o2laf*"]
32
+
33
+ [tool.setuptools.package-data]
34
+ "o2laf" = ["assets/prompt_embeds/*.safetensors"]
app.py CHANGED
@@ -1,57 +1,56 @@
1
  """O2LaF — interactive demo on Hugging Face ZeroGPU.
2
 
3
- Three live panels on top of the `o2laf` package:
4
-
5
- * **Actions from video (IDM)** — the latent action encoder reads a video and
6
- emits one 32-d action token per transition (t -> t+1). Shows the action-token
7
- heatmap, a PCA view of the latent action space and the paper's action-query
8
- attention overlay (which queries attend to hands and motion).
9
- * **Replay on a new scene (FDM)** — transfer: the encoder's actions drive the
10
- bidirectional world model to replay the motion from any first frame.
11
- * **Atomic actions (FDM)** — steer the world model directly with the shipped
12
- atomic action library (idle / w / a / s / d / camera moves).
13
  """
14
 
15
  from __future__ import annotations
16
 
17
- import gc
18
- import os
19
  import sys
20
  import tempfile
21
- import threading
22
  import traceback
23
  from pathlib import Path
24
 
25
- import spaces # must precede torch/gradio on ZeroGPU
26
 
27
  import gradio as gr
28
  import matplotlib
 
 
29
  import matplotlib.pyplot as plt
30
  import numpy as np
31
  import torch
 
32
 
33
- matplotlib.use("Agg")
 
34
 
35
- REPO_ID = "YuxinJ/O2LaF"
36
- EXAMPLES_DIR = Path(__file__).parent / "examples"
 
37
 
 
38
  MODELS = {
39
- "ego": {"path": f"{REPO_ID}/o2laf_dit_egodexmix", "label": "Egocentric (egodexmix, 24 fps)"},
40
- "mixed": {"path": f"{REPO_ID}/o2laf_dit_mixed", "label": "Third-person (mixed, 16 fps)"},
41
  }
42
  ATOMIC_ACTIONS = ["idle", "w", "s", "a", "d", "camera_up", "camera_down", "camera_left", "camera_right"]
43
 
44
- # (source video, first frame or None, model key, caption)
45
  TRANSFER_EXAMPLES = [
46
- ("ego_wash_fruit.mp4", None, "ego", "Wash fruit -> own first frame"),
47
- ("ego_fry_bread.mp4", None, "ego", "Fry bread -> own first frame"),
48
- ("ego_fry_egg.mp4", None, "ego", "Fry egg -> own first frame"),
49
- ("ego_wash_kitchen_dishes.mp4", None, "ego", "Wash dishes -> own first frame"),
50
- ("ego_wash_fruit.mp4", "first_gr1.png", "ego", "Wash fruit -> GR-1 robot"),
51
- ("ego_knit_scarf.mp4", "first_gr1.png", "ego", "Knit scarf -> GR-1 robot"),
52
- ("ego_fry_bread.mp4", "first_gr1.png", "ego", "Fry bread -> GR-1 robot"),
53
- ("ego_knit_scarf.mp4", "first_west.png", "mixed", "Knit scarf -> wild west"),
54
- ("gta5.mp4", "first_west.png", "mixed", "GTA5 walk -> wild west"),
55
  ]
56
  IDM_EXAMPLES = [
57
  ("ego_wash_fruit.mp4", "ego"),
@@ -74,333 +73,178 @@ SHOWCASE = [
74
  ("gta5.mp4", "out_gta5_to_west.mp4", "GTA5 walk -> wild west (mixed)"),
75
  ]
76
 
77
- _gpu_objects: list[tuple[str, object]] = [] # LRU: (key, pipeline/extractor)
 
 
 
78
 
 
 
 
 
 
 
 
79
 
80
- def _evict_if_full():
81
- while len(_gpu_objects) >= 2:
82
- _, obj = _gpu_objects.pop(0)
83
- del obj
84
- gc.collect()
85
- torch.cuda.empty_cache()
86
 
 
87
 
88
- def _touch(key, obj):
89
- _gpu_objects.append((key, obj))
90
 
 
 
91
 
92
- def get_pipe(model_key: str):
93
- key = f"pipe:{model_key}"
94
- for i, (k, obj) in enumerate(_gpu_objects):
95
- if k == key:
96
- _gpu_objects.pop(i)
97
- _gpu_objects.append((key, obj))
98
- return obj
99
- _evict_if_full()
100
- from o2laf import LatentActionPipeline
 
101
 
102
- pipe = LatentActionPipeline.from_pretrained(
103
- MODELS[model_key]["path"], mode="bidirectional", device="cuda", dtype=torch.bfloat16
104
- )
105
- _touch(key, pipe)
106
- return pipe
107
-
108
-
109
- def get_extractor(model_key: str):
110
- key = f"attn:{model_key}"
111
- for i, (k, obj) in enumerate(_gpu_objects):
112
- if k == key:
113
- _gpu_objects.pop(i)
114
- _gpu_objects.append((key, obj))
115
- return obj
116
- _evict_if_full()
117
- from o2laf.inference.attention import ActionAttentionExtractor
118
-
119
- extractor = ActionAttentionExtractor.from_pretrained(
120
- MODELS[model_key]["path"], device="cuda", dtype=torch.bfloat16
121
- )
122
- _touch(key, extractor)
123
- return extractor
124
-
125
-
126
- def _report(exc: Exception):
127
- """Print + persist the full traceback (run logs are hard to read), then surface it."""
128
- tb = traceback.format_exc()
129
- print(tb, flush=True)
130
- try:
131
- import time as _time
132
-
133
- from huggingface_hub import HfApi
134
-
135
- path = tempfile.mktemp(suffix=".txt")
136
- with open(path, "w") as f:
137
- f.write(tb)
138
- HfApi().upload_file(
139
- path_or_fileobj=path,
140
- path_in_repo=f"err/{int(_time.time())}.txt",
141
- repo_id="blanchon/o2laf-debug",
142
- repo_type="dataset",
143
- )
144
- except Exception:
145
- traceback.print_exc()
146
- return gr.Error(f"O2LaF failed: {type(exc).__name__}: {exc}")
147
-
148
-
149
- def repair_unpatched_torch() -> None:
150
- """Undo what ZeroGPU's unpatch() misses in the GPU worker, before torch.compile.
151
-
152
- - spaces restores torch.cuda._maybe_exchange_device with _exchange_device, so
153
- Dynamo's handler table sees one builtin twice and flex_attention's first trace
154
- fails with "Handler already registered for _cuda_exchangeDevice".
155
- - torch._dynamo's CudaInterface copies torch.cuda functions when it is imported;
156
- if that happened while ZeroGPU's stand-ins were installed (synchronize is a
157
- no-op), kernel autotuning fails ("Both events must be completed").
158
- """
159
- maybe = getattr(torch._C, "_cuda_maybeExchangeDevice", None)
160
- if maybe is not None and torch.cuda._maybe_exchange_device is torch.cuda._exchange_device:
161
- torch.cuda._maybe_exchange_device = maybe
162
- interface = sys.modules.get("torch._dynamo.device_interface")
163
- if interface is not None:
164
- cuda = interface.CudaInterface
165
- for name, attr in (
166
- ("current_device", "current_device"),
167
- ("set_device", "set_device"),
168
- ("device_count", "device_count"),
169
- ("synchronize", "synchronize"),
170
- ("get_device_properties", "get_device_properties"),
171
- ("exchange_device", "_exchange_device"),
172
- ("maybe_exchange_device", "_maybe_exchange_device"),
173
- ):
174
- function = getattr(torch.cuda, attr, None)
175
- if function is not None and hasattr(cuda, name):
176
- setattr(cuda, name, staticmethod(function))
177
-
178
-
179
- def _video_to_tmp_path(video_file) -> str:
180
- """gradio video input -> local path on disk (str in gradio 3, VideoData in 4/5)."""
181
- if isinstance(video_file, str):
182
- return video_file
183
- if hasattr(video_file, "video"):
184
- return video_file.video.path
185
- if isinstance(video_file, dict):
186
- v = video_file.get("video", video_file)
187
- return v["path"] if isinstance(v, dict) else v.path
188
- return video_file.name
189
-
190
-
191
- def export_video(frames: torch.Tensor, fps: float) -> str:
192
  from diffusers.utils import export_to_video
193
 
194
- path = tempfile.mktemp(suffix=".mp4")
195
- out = frames.permute(0, 2, 3, 1).float().clamp(0, 1).cpu().numpy()
196
- export_to_video(list(out), path, fps=fps)
197
  return path
198
 
199
 
200
- def fig_to_png(fig):
201
- path = tempfile.mktemp(suffix=".png")
202
  fig.savefig(path, dpi=110, bbox_inches="tight")
203
  plt.close(fig)
204
  return path
205
 
206
 
207
- def actions_heatmap(actions: torch.Tensor, title: str):
208
  a = actions[0].float().cpu().numpy()
209
  fig, ax = plt.subplots(figsize=(9, 3.2))
210
  im = ax.imshow(a.T, aspect="auto", cmap="viridis", interpolation="nearest", origin="lower")
211
- ax.set_xlabel("transition t -> t+1")
212
- ax.set_ylabel("action dim")
213
- ax.set_title(title)
214
  fig.colorbar(im, ax=ax, fraction=0.025, pad=0.01)
215
  fig.tight_layout()
216
- return fig
217
 
218
 
219
- def actions_pca(actions: torch.Tensor, anchors: dict[str, np.ndarray] | None = None):
220
  from sklearn.decomposition import PCA
221
 
222
  X = actions[0].float().cpu().numpy()
223
- points = [X]
224
- names = []
225
- if anchors:
226
- A = np.stack(list(anchors.values()))
227
- points.append(A)
228
- names = list(anchors.keys())
229
- pca = PCA(n_components=2).fit(np.concatenate(points, axis=0))
230
  fig, ax = plt.subplots(figsize=(5, 4.4))
231
  z = pca.transform(X)
232
  sc = ax.scatter(z[:, 0], z[:, 1], c=np.arange(len(z)), cmap="viridis", s=28)
233
  if anchors:
234
  za = pca.transform(A)
235
  ax.scatter(za[:, 0], za[:, 1], marker="D", s=70, color="crimson", zorder=3)
236
- for name, (x, y) in zip(names, za):
237
  ax.annotate(name, (x, y), fontsize=7, xytext=(3, 3), textcoords="offset points", color="crimson")
238
  fig.colorbar(sc, ax=ax, fraction=0.04, pad=0.02, label="time")
239
- ax.set_title("Latent action space (PCA)")
240
- ax.set_xlabel("PC 1")
241
- ax.set_ylabel("PC 2")
242
  fig.tight_layout()
243
- return fig
244
-
245
 
246
- def _atomic_anchors(pipe) -> dict[str, np.ndarray] | None:
247
- """Atomic action centroids as anchors for the PCA plot (mixed model only)."""
248
- try:
249
- from o2laf.inference.action_library import AtomicActionLibrary
250
 
251
- library = AtomicActionLibrary.from_pipeline(pipe)
252
- groups = pipe.num_latent_frames_for(pipe.num_rgb_frames) - pipe.num_context_frames
253
- return {
254
- name: library.tensor(name, groups=groups, device="cpu", dtype=torch.float32)
255
- .reshape(-1)
256
- .numpy()
257
- for name in ATOMIC_ACTIONS
258
- }
259
- except Exception:
260
- return None
261
 
262
 
263
  # ---------------------------------------------------------------- GPU entry points
264
 
265
 
266
- @spaces.GPU(duration=240)
267
  def run_transfer(source_video, first_frame, model_key, guidance, steps, seed):
268
- try:
269
- return _run_transfer(source_video, first_frame, model_key, guidance, steps, seed)
270
- except Exception as exc:
271
- raise _report(exc) from None
272
-
273
-
274
- def _run_transfer(source_video, first_frame, model_key, guidance, steps, seed):
275
- repair_unpatched_torch()
276
  if not source_video:
277
  raise gr.Error("Pick or upload a source video first.")
278
- from o2laf import ActionGuidance
279
- from o2laf.inference.cli.common import load_source_video
280
-
281
- pipe = get_pipe(model_key)
282
- path = _video_to_tmp_path(source_video)
283
- source = load_source_video(Path(path), pipe.fps)
284
  actions = pipe.encode_source_actions(source)
285
- if first_frame is None:
286
- first_pixels = source[:1]
287
- else:
288
- from PIL import Image
289
-
290
- first_pixels = np.asarray(Image.open(first_frame).convert("RGB"), dtype=np.uint8)[None]
291
- first = pipe.encode_latents(pipe.preprocess_frames(first_pixels))[:, :1]
292
  latents = pipe.generate_latents(
293
  actions=actions,
294
- first_frame_latents=first,
295
  num_steps=int(steps),
296
  seed=int(seed),
297
  guidance=ActionGuidance(scale=float(guidance)),
298
  )
299
- video = pipe.decode_latents(latents)[0]
300
- return export_video(video, pipe.fps), fig_to_png(actions_heatmap(actions, "Latent actions driving the replay"))
301
 
302
 
303
- @spaces.GPU(duration=240)
304
  def run_idm(source_video, model_key, block, head):
305
- try:
306
- return _run_idm(source_video, model_key, block, head)
307
- except Exception as exc:
308
- raise _report(exc) from None
309
-
310
-
311
- def _run_idm(source_video, model_key, block, head):
312
- repair_unpatched_torch()
313
  if not source_video:
314
  raise gr.Error("Pick or upload a video first.")
315
- pipe = get_pipe(model_key)
316
- path = _video_to_tmp_path(source_video)
317
- from o2laf.inference.cli.common import load_source_video
318
-
319
- source = load_source_video(Path(path), pipe.fps)
320
- actions = pipe.encode_source_actions(source)
321
- fig_heat = actions_heatmap(actions, "Action tokens: 32 dims per transition")
322
- fig_pca = actions_pca(actions, _atomic_anchors(pipe) if model_key == "mixed" else None)
323
- extractor = get_extractor(model_key)
324
- out_path = tempfile.mktemp(suffix=".mp4")
325
- extractor.visualize(Path(path), Path(out_path), block=int(block), head=int(head))
326
- return out_path, fig_to_png(fig_heat), fig_to_png(fig_pca)
327
 
328
 
329
- @spaces.GPU(duration=240)
330
  def run_atomic(first_frame, action, num_frames, steps, seed):
331
- try:
332
- return _run_atomic(first_frame, action, num_frames, steps, seed)
333
- except Exception as exc:
334
- raise _report(exc) from None
335
-
336
-
337
- def _run_atomic(first_frame, action, num_frames, steps, seed):
338
- repair_unpatched_torch()
339
  if first_frame is None:
340
  raise gr.Error("Pick or upload a first frame first.")
341
- from o2laf import ActionGuidance
342
- from o2laf.inference.action_library import AtomicActionLibrary
343
- from o2laf.inference.cli.common import load_first_frame
344
- from PIL import Image
345
-
346
- if isinstance(first_frame, dict):
347
- raise gr.Error("Unexpected first-frame input.")
348
- frame = np.asarray(Image.open(first_frame).convert("RGB"), dtype=np.uint8)
349
- pipe = get_pipe("mixed")
350
- library = AtomicActionLibrary.from_pipeline(pipe)
351
- num_frames = int(num_frames)
352
- groups = pipe.num_latent_frames_for(num_frames) - pipe.num_context_frames
353
- actions = library.tensor(action, groups=groups, device=pipe.device, dtype=pipe.dtype)
354
- first = pipe.encode_latents(pipe.preprocess_frames(frame))
355
- first = first[:, :1]
356
  latents = pipe.generate_latents(
357
- actions=actions,
358
- first_frame_latents=first,
359
  num_steps=int(steps),
360
  seed=int(seed),
361
  guidance=ActionGuidance(scale=3.0),
362
  )
363
- video = pipe.decode_latents(latents)[0]
364
- vec = library.tensor(action, groups=1, device="cpu", dtype=torch.float32).reshape(-1).numpy()
365
  fig, ax = plt.subplots(figsize=(9, 2.6))
366
  ax.bar(np.arange(len(vec)), vec, color="teal")
367
- ax.set_title(f"Atomic action token: {action} (32 dims)")
368
- ax.set_xlabel("action dim")
369
  fig.tight_layout()
370
- return export_video(video, pipe.fps), fig_to_png(fig)
371
-
372
-
373
- # ---------------------------------------------------------------- startup prefetch
374
-
375
-
376
- def _prefetch():
377
- try:
378
- from huggingface_hub import snapshot_download
379
-
380
- snapshot_download(REPO_ID, allow_patterns=["o2laf_dit_egodexmix/*", "o2laf_dit_mixed/*"])
381
- snapshot_download("Wan-AI/Wan2.2-TI2V-5B-Diffusers")
382
- except Exception as exc: # never block the UI on prefetch
383
- print(f"prefetch failed: {exc}")
384
-
385
-
386
- threading.Thread(target=_prefetch, daemon=True).start()
387
 
388
 
389
  # ---------------------------------------------------------------- UI
390
 
391
 
392
- def ex_path(name: str) -> str:
393
- return str(EXAMPLES_DIR / name)
394
-
395
-
396
- def transfer_rows():
397
- return [[ex_path(v), ex_path(f) if f else None, m] for v, f, m, _ in TRANSFER_EXAMPLES]
398
-
399
-
400
- def idm_rows():
401
- return [[ex_path(v), m] for v, m in IDM_EXAMPLES]
402
 
403
 
 
404
  css = """
405
  .gradio-container {max-width: 1100px !important; margin: 0 auto;}
406
  h1 {font-size: 1.6rem !important;}
@@ -418,7 +262,6 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css, title="O2LaF") as demo:
418
  "<a href='https://showlab.github.io/o2laf/' target='_blank'>Project page</a> · "
419
  "<a href='https://huggingface.co/YuxinJ/O2LaF' target='_blank'>Checkpoints</a></p>"
420
  "<p style='margin:0 0 8px;font-size:0.9em;color:var(--body-text-color-subdued)'>"
421
- "First generation per model builds it (~1 min extra); later runs are ~20-45 s. "
422
  "The egocentric checkpoint fits hand manipulation; the mixed one adds third-person camera motion.</p>"
423
  )
424
 
@@ -426,32 +269,24 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css, title="O2LaF") as demo:
426
  with gr.Tab("Replay on a new scene"):
427
  gr.Markdown("Actions are read from the **source video** and replayed starting from the **first frame**.")
428
  with gr.Row():
429
- with gr.Column(scale=1):
430
  src = gr.Video(label="Source video", sources=["upload"])
431
  first = gr.Image(label="First frame (optional — own first frame)", sources=["upload"], type="filepath")
432
- model_radio = gr.Radio(
433
- [(v["label"], k) for k, v in MODELS.items()],
434
- value="ego",
435
- label="Checkpoint",
436
- )
437
  with gr.Accordion("Advanced", open=False):
438
  guidance = gr.Slider(1.0, 6.0, value=3.0, step=0.5, label="Action guidance")
439
  steps = gr.Slider(8, 30, value=20, step=1, label="Steps")
440
  seed = gr.Slider(0, 999, value=0, step=1, label="Seed")
441
  go = gr.Button("Generate", variant="primary")
442
- with gr.Column(scale=1):
443
  out_video = gr.Video(label="Generated video")
444
  out_heat = gr.Image(label="Latent actions used")
445
  gr.Examples(
446
- examples=transfer_rows(),
447
  inputs=[src, first, model_radio],
448
  examples_per_page=12,
449
  )
450
- go.click(
451
- run_transfer,
452
- inputs=[src, first, model_radio, guidance, steps, seed],
453
- outputs=[out_video, out_heat],
454
- )
455
 
456
  with gr.Tab("Actions from video (IDM)"):
457
  gr.Markdown(
@@ -459,27 +294,19 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css, title="O2LaF") as demo:
459
  "action query attends (hands, motion); tune the DiT block/head to inspect other layers."
460
  )
461
  with gr.Row():
462
- with gr.Column(scale=1):
463
  vid_in = gr.Video(label="Video", sources=["upload"])
464
- model_radio2 = gr.Radio(
465
- [(v["label"], k) for k, v in MODELS.items()],
466
- value="ego",
467
- label="Checkpoint",
468
- )
469
  with gr.Accordion("Attention layer", open=False):
470
  block = gr.Slider(1, 30, value=30, step=1, label="DiT block")
471
  head = gr.Slider(0, 23, value=11, step=1, label="Head")
472
  go2 = gr.Button("Extract actions", variant="primary")
473
- with gr.Column(scale=1):
474
  attn_video = gr.Video(label="Action-query attention overlay")
475
  heat2 = gr.Image(label="Action tokens")
476
  pca2 = gr.Image(label="Latent action space")
477
- gr.Examples(
478
- examples=idm_rows(),
479
- inputs=[vid_in, model_radio2],
480
- examples_per_page=12,
481
- )
482
- go2.click(run_idm, inputs=[vid_in, model_radio2, block, head], outputs=[attn_video, heat2, pca2])
483
 
484
  with gr.Tab("Atomic actions"):
485
  gr.Markdown(
@@ -487,7 +314,7 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css, title="O2LaF") as demo:
487
  "(third-person checkpoint only): pick an action and a starting frame."
488
  )
489
  with gr.Row():
490
- with gr.Column(scale=1):
491
  atomic_frame = gr.Image(label="First frame", sources=["upload"], type="filepath")
492
  action = gr.Dropdown(ATOMIC_ACTIONS, value="w", label="Atomic action")
493
  n_frames = gr.Slider(21, 121, value=81, step=4, label="Frames")
@@ -495,18 +322,14 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css, title="O2LaF") as demo:
495
  a_steps = gr.Slider(8, 30, value=20, step=1, label="Steps")
496
  a_seed = gr.Slider(0, 999, value=0, step=1, label="Seed")
497
  go3 = gr.Button("Generate", variant="primary")
498
- with gr.Column(scale=1):
499
  a_video = gr.Video(label="Generated video")
500
  a_plot = gr.Image(label="Action token")
501
  gr.Examples(
502
- examples=[[ex_path("first_west.png")], [ex_path("first_gta5.png")], [ex_path("first_gr1.png")]],
503
  inputs=[atomic_frame],
504
  )
505
- go3.click(
506
- run_atomic,
507
- inputs=[atomic_frame, action, n_frames, a_steps, a_seed],
508
- outputs=[a_video, a_plot],
509
- )
510
 
511
  with gr.Tab("Showcase"):
512
  gr.Markdown("Precomputed egocentric results (no GPU needed to browse).")
@@ -516,8 +339,8 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css, title="O2LaF") as demo:
516
  with gr.Column():
517
  gr.Markdown(f"**{caption}**")
518
  with gr.Row():
519
- gr.Video(ex_path(src_name), label="Source")
520
- gr.Video(ex_path(out_name), label="O2LaF replay")
521
 
522
  gr.HTML(
523
  "<p style='font-size:0.85em;color:var(--body-text-color-subdued)'>O2LaF: One for All — a single latent action "
 
1
  """O2LaF — interactive demo on Hugging Face ZeroGPU.
2
 
3
+ * **Replay on a new scene** — the action encoder reads a source video and its
4
+ latent actions drive the bidirectional world model from any first frame.
5
+ * **Actions from video (IDM)** — the action tokens, a PCA view of the latent
6
+ action space and the paper's action-query attention overlay.
7
+ * **Atomic actions** — steer the world model with the shipped atomic actions.
 
 
 
 
 
8
  """
9
 
10
  from __future__ import annotations
11
 
12
+ import functools
 
13
  import sys
14
  import tempfile
 
15
  import traceback
16
  from pathlib import Path
17
 
18
+ import spaces # must precede torch on ZeroGPU
19
 
20
  import gradio as gr
21
  import matplotlib
22
+
23
+ matplotlib.use("Agg")
24
  import matplotlib.pyplot as plt
25
  import numpy as np
26
  import torch
27
+ from PIL import Image
28
 
29
+ ROOT = Path(__file__).parent
30
+ sys.path.insert(0, str(ROOT / "O2LaF")) # vendored inference-only fork of showlab/O2LaF
31
 
32
+ from o2laf import ActionAttentionExtractor, ActionGuidance, LatentActionPipeline # noqa: E402
33
+ from o2laf.inference.action_library import AtomicActionLibrary # noqa: E402
34
+ from o2laf.inference.video import load_source_video # noqa: E402
35
 
36
+ EXAMPLES_DIR = ROOT / "examples"
37
  MODELS = {
38
+ "ego": ("YuxinJ/O2LaF/o2laf_dit_egodexmix", "Egocentric (egodexmix, 24 fps)"),
39
+ "mixed": ("YuxinJ/O2LaF/o2laf_dit_mixed", "Third-person (mixed, 16 fps)"),
40
  }
41
  ATOMIC_ACTIONS = ["idle", "w", "s", "a", "d", "camera_up", "camera_down", "camera_left", "camera_right"]
42
 
43
+ # (source video, first frame or None, model key)
44
  TRANSFER_EXAMPLES = [
45
+ ("ego_wash_fruit.mp4", None, "ego"),
46
+ ("ego_fry_bread.mp4", None, "ego"),
47
+ ("ego_fry_egg.mp4", None, "ego"),
48
+ ("ego_wash_kitchen_dishes.mp4", None, "ego"),
49
+ ("ego_wash_fruit.mp4", "first_gr1.png", "ego"),
50
+ ("ego_knit_scarf.mp4", "first_gr1.png", "ego"),
51
+ ("ego_fry_bread.mp4", "first_gr1.png", "ego"),
52
+ ("ego_knit_scarf.mp4", "first_west.png", "mixed"),
53
+ ("gta5.mp4", "first_west.png", "mixed"),
54
  ]
55
  IDM_EXAMPLES = [
56
  ("ego_wash_fruit.mp4", "ego"),
 
73
  ("gta5.mp4", "out_gta5_to_west.mp4", "GTA5 walk -> wild west (mixed)"),
74
  ]
75
 
76
+ # ---------------------------------------------------------------- models
77
+ # Loaded once at startup. On ZeroGPU, weights placed on "cuda" here stay in host
78
+ # memory and are moved to the GPU at the start of each call, which takes seconds;
79
+ # loading inside the @spaces.GPU function instead cost ~35 s on every call.
80
 
81
+ PIPES = {
82
+ key: LatentActionPipeline.from_pretrained(path, mode="bidirectional", device="cuda", dtype=torch.bfloat16)
83
+ for key, (path, _) in MODELS.items()
84
+ }
85
+ PIPES["mixed"].vae = PIPES["ego"].vae # same Wan 2.2 VAE; keep one copy
86
+ EXTRACTORS = {key: ActionAttentionExtractor.from_pipeline(pipe) for key, pipe in PIPES.items()}
87
+ ATOMIC_LIBRARY = AtomicActionLibrary.from_pipeline(PIPES["mixed"])
88
 
 
 
 
 
 
 
89
 
90
+ # ---------------------------------------------------------------- helpers
91
 
 
 
92
 
93
+ def gpu_task(fn):
94
+ """Run on ZeroGPU and surface failures as a readable gr.Error (picklable across the worker boundary)."""
95
 
96
+ @spaces.GPU(duration=120)
97
+ @functools.wraps(fn)
98
+ def wrapper(*args):
99
+ try:
100
+ return fn(*args)
101
+ except gr.Error:
102
+ raise
103
+ except Exception as exc:
104
+ traceback.print_exc()
105
+ raise gr.Error(f"{type(exc).__name__}: {exc}") from None
106
 
107
+ return wrapper
108
+
109
+
110
+ def video_path(value) -> str:
111
+ """Gradio video input -> local path (a str, or a VideoData-like object/dict)."""
112
+ if isinstance(value, str):
113
+ return value
114
+ if isinstance(value, dict):
115
+ value = value.get("video", value)
116
+ return value["path"] if isinstance(value, dict) else value.path
117
+ return value.video.path if hasattr(value, "video") else value.path
118
+
119
+
120
+ def read_image(path: str) -> np.ndarray:
121
+ """An image file as one uint8 frame ``[1, H, W, 3]``."""
122
+ return np.asarray(Image.open(path).convert("RGB"), dtype=np.uint8)[None]
123
+
124
+
125
+ def first_frame_latents(pipe, frame: np.ndarray) -> torch.Tensor:
126
+ """Latents ``[1, C, 1, h, w]`` of one uint8 frame ``[1, H, W, 3]``."""
127
+ return pipe.encode_latents(pipe.preprocess_frames(frame))
128
+
129
+
130
+ def tmp_path(suffix: str) -> str:
131
+ with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as f:
132
+ return f.name
133
+
134
+
135
+ def render(pipe, latents) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  from diffusers.utils import export_to_video
137
 
138
+ video = pipe.decode_latents(latents)[0].permute(0, 2, 3, 1).float().cpu().numpy()
139
+ path = tmp_path(".mp4")
140
+ export_to_video(list(video), path, fps=pipe.fps)
141
  return path
142
 
143
 
144
+ def save_fig(fig) -> str:
145
+ path = tmp_path(".png")
146
  fig.savefig(path, dpi=110, bbox_inches="tight")
147
  plt.close(fig)
148
  return path
149
 
150
 
151
+ def actions_heatmap(actions: torch.Tensor, title: str) -> str:
152
  a = actions[0].float().cpu().numpy()
153
  fig, ax = plt.subplots(figsize=(9, 3.2))
154
  im = ax.imshow(a.T, aspect="auto", cmap="viridis", interpolation="nearest", origin="lower")
155
+ ax.set(xlabel="transition t -> t+1", ylabel="action dim", title=title)
 
 
156
  fig.colorbar(im, ax=ax, fraction=0.025, pad=0.01)
157
  fig.tight_layout()
158
+ return save_fig(fig)
159
 
160
 
161
+ def actions_pca(actions: torch.Tensor, anchors: dict[str, np.ndarray] | None) -> str:
162
  from sklearn.decomposition import PCA
163
 
164
  X = actions[0].float().cpu().numpy()
165
+ A = np.stack(list(anchors.values())) if anchors else np.empty((0, X.shape[1]))
166
+ pca = PCA(n_components=2).fit(np.concatenate([X, A]))
 
 
 
 
 
167
  fig, ax = plt.subplots(figsize=(5, 4.4))
168
  z = pca.transform(X)
169
  sc = ax.scatter(z[:, 0], z[:, 1], c=np.arange(len(z)), cmap="viridis", s=28)
170
  if anchors:
171
  za = pca.transform(A)
172
  ax.scatter(za[:, 0], za[:, 1], marker="D", s=70, color="crimson", zorder=3)
173
+ for name, (x, y) in zip(anchors, za):
174
  ax.annotate(name, (x, y), fontsize=7, xytext=(3, 3), textcoords="offset points", color="crimson")
175
  fig.colorbar(sc, ax=ax, fraction=0.04, pad=0.02, label="time")
176
+ ax.set(title="Latent action space (PCA)", xlabel="PC 1", ylabel="PC 2")
 
 
177
  fig.tight_layout()
178
+ return save_fig(fig)
 
179
 
 
 
 
 
180
 
181
+ def atomic_vector(name: str) -> np.ndarray:
182
+ return ATOMIC_LIBRARY.tensor(name, groups=1, device="cpu", dtype=torch.float32).reshape(-1).numpy()
 
 
 
 
 
 
 
 
183
 
184
 
185
  # ---------------------------------------------------------------- GPU entry points
186
 
187
 
188
+ @gpu_task
189
  def run_transfer(source_video, first_frame, model_key, guidance, steps, seed):
 
 
 
 
 
 
 
 
190
  if not source_video:
191
  raise gr.Error("Pick or upload a source video first.")
192
+ pipe = PIPES[model_key]
193
+ source = load_source_video(video_path(source_video), pipe.fps)
 
 
 
 
194
  actions = pipe.encode_source_actions(source)
195
+ frame = source[:1] if first_frame is None else read_image(first_frame)
 
 
 
 
 
 
196
  latents = pipe.generate_latents(
197
  actions=actions,
198
+ first_frame_latents=first_frame_latents(pipe, frame),
199
  num_steps=int(steps),
200
  seed=int(seed),
201
  guidance=ActionGuidance(scale=float(guidance)),
202
  )
203
+ return render(pipe, latents), actions_heatmap(actions, "Latent actions driving the replay")
 
204
 
205
 
206
+ @gpu_task
207
  def run_idm(source_video, model_key, block, head):
 
 
 
 
 
 
 
 
208
  if not source_video:
209
  raise gr.Error("Pick or upload a video first.")
210
+ pipe = PIPES[model_key]
211
+ path = video_path(source_video)
212
+ actions = pipe.encode_source_actions(load_source_video(path, pipe.fps))
213
+ anchors = {name: atomic_vector(name) for name in ATOMIC_ACTIONS} if model_key == "mixed" else None
214
+ overlay = tmp_path(".mp4")
215
+ EXTRACTORS[model_key].visualize(Path(path), Path(overlay), block=int(block), head=int(head))
216
+ return overlay, actions_heatmap(actions, "Action tokens: 32 dims per transition"), actions_pca(actions, anchors)
 
 
 
 
 
217
 
218
 
219
+ @gpu_task
220
  def run_atomic(first_frame, action, num_frames, steps, seed):
 
 
 
 
 
 
 
 
221
  if first_frame is None:
222
  raise gr.Error("Pick or upload a first frame first.")
223
+ pipe = PIPES["mixed"]
224
+ groups = pipe.num_latent_frames_for(int(num_frames)) - pipe.num_context_frames
 
 
 
 
 
 
 
 
 
 
 
 
 
225
  latents = pipe.generate_latents(
226
+ actions=ATOMIC_LIBRARY.tensor(action, groups=groups, device=pipe.device, dtype=pipe.dtype),
227
+ first_frame_latents=first_frame_latents(pipe, read_image(first_frame)),
228
  num_steps=int(steps),
229
  seed=int(seed),
230
  guidance=ActionGuidance(scale=3.0),
231
  )
232
+ vec = atomic_vector(action)
 
233
  fig, ax = plt.subplots(figsize=(9, 2.6))
234
  ax.bar(np.arange(len(vec)), vec, color="teal")
235
+ ax.set(title=f"Atomic action token: {action} (32 dims)", xlabel="action dim")
 
236
  fig.tight_layout()
237
+ return render(pipe, latents), save_fig(fig)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
 
239
 
240
  # ---------------------------------------------------------------- UI
241
 
242
 
243
+ def ex(name: str | None) -> str | None:
244
+ return str(EXAMPLES_DIR / name) if name else None
 
 
 
 
 
 
 
 
245
 
246
 
247
+ MODEL_CHOICES = [(label, key) for key, (_, label) in MODELS.items()]
248
  css = """
249
  .gradio-container {max-width: 1100px !important; margin: 0 auto;}
250
  h1 {font-size: 1.6rem !important;}
 
262
  "<a href='https://showlab.github.io/o2laf/' target='_blank'>Project page</a> · "
263
  "<a href='https://huggingface.co/YuxinJ/O2LaF' target='_blank'>Checkpoints</a></p>"
264
  "<p style='margin:0 0 8px;font-size:0.9em;color:var(--body-text-color-subdued)'>"
 
265
  "The egocentric checkpoint fits hand manipulation; the mixed one adds third-person camera motion.</p>"
266
  )
267
 
 
269
  with gr.Tab("Replay on a new scene"):
270
  gr.Markdown("Actions are read from the **source video** and replayed starting from the **first frame**.")
271
  with gr.Row():
272
+ with gr.Column():
273
  src = gr.Video(label="Source video", sources=["upload"])
274
  first = gr.Image(label="First frame (optional — own first frame)", sources=["upload"], type="filepath")
275
+ model_radio = gr.Radio(MODEL_CHOICES, value="ego", label="Checkpoint")
 
 
 
 
276
  with gr.Accordion("Advanced", open=False):
277
  guidance = gr.Slider(1.0, 6.0, value=3.0, step=0.5, label="Action guidance")
278
  steps = gr.Slider(8, 30, value=20, step=1, label="Steps")
279
  seed = gr.Slider(0, 999, value=0, step=1, label="Seed")
280
  go = gr.Button("Generate", variant="primary")
281
+ with gr.Column():
282
  out_video = gr.Video(label="Generated video")
283
  out_heat = gr.Image(label="Latent actions used")
284
  gr.Examples(
285
+ examples=[[ex(v), ex(f), m] for v, f, m in TRANSFER_EXAMPLES],
286
  inputs=[src, first, model_radio],
287
  examples_per_page=12,
288
  )
289
+ go.click(run_transfer, [src, first, model_radio, guidance, steps, seed], [out_video, out_heat])
 
 
 
 
290
 
291
  with gr.Tab("Actions from video (IDM)"):
292
  gr.Markdown(
 
294
  "action query attends (hands, motion); tune the DiT block/head to inspect other layers."
295
  )
296
  with gr.Row():
297
+ with gr.Column():
298
  vid_in = gr.Video(label="Video", sources=["upload"])
299
+ model_radio2 = gr.Radio(MODEL_CHOICES, value="ego", label="Checkpoint")
 
 
 
 
300
  with gr.Accordion("Attention layer", open=False):
301
  block = gr.Slider(1, 30, value=30, step=1, label="DiT block")
302
  head = gr.Slider(0, 23, value=11, step=1, label="Head")
303
  go2 = gr.Button("Extract actions", variant="primary")
304
+ with gr.Column():
305
  attn_video = gr.Video(label="Action-query attention overlay")
306
  heat2 = gr.Image(label="Action tokens")
307
  pca2 = gr.Image(label="Latent action space")
308
+ gr.Examples(examples=[[ex(v), m] for v, m in IDM_EXAMPLES], inputs=[vid_in, model_radio2])
309
+ go2.click(run_idm, [vid_in, model_radio2, block, head], [attn_video, heat2, pca2])
 
 
 
 
310
 
311
  with gr.Tab("Atomic actions"):
312
  gr.Markdown(
 
314
  "(third-person checkpoint only): pick an action and a starting frame."
315
  )
316
  with gr.Row():
317
+ with gr.Column():
318
  atomic_frame = gr.Image(label="First frame", sources=["upload"], type="filepath")
319
  action = gr.Dropdown(ATOMIC_ACTIONS, value="w", label="Atomic action")
320
  n_frames = gr.Slider(21, 121, value=81, step=4, label="Frames")
 
322
  a_steps = gr.Slider(8, 30, value=20, step=1, label="Steps")
323
  a_seed = gr.Slider(0, 999, value=0, step=1, label="Seed")
324
  go3 = gr.Button("Generate", variant="primary")
325
+ with gr.Column():
326
  a_video = gr.Video(label="Generated video")
327
  a_plot = gr.Image(label="Action token")
328
  gr.Examples(
329
+ examples=[[ex("first_west.png")], [ex("first_gta5.png")], [ex("first_gr1.png")]],
330
  inputs=[atomic_frame],
331
  )
332
+ go3.click(run_atomic, [atomic_frame, action, n_frames, a_steps, a_seed], [a_video, a_plot])
 
 
 
 
333
 
334
  with gr.Tab("Showcase"):
335
  gr.Markdown("Precomputed egocentric results (no GPU needed to browse).")
 
339
  with gr.Column():
340
  gr.Markdown(f"**{caption}**")
341
  with gr.Row():
342
+ gr.Video(ex(src_name), label="Source")
343
+ gr.Video(ex(out_name), label="O2LaF replay")
344
 
345
  gr.HTML(
346
  "<p style='font-size:0.85em;color:var(--body-text-color-subdued)'>O2LaF: One for All — a single latent action "
requirements.txt CHANGED
@@ -1,8 +1,13 @@
1
- o2laf @ git+https://github.com/showlab/O2LaF.git
2
  spaces
3
- gradio
4
- matplotlib
5
- scikit-learn
 
 
 
6
  imageio
7
  imageio-ffmpeg
8
  hf_transfer
 
 
 
1
+ # o2laf itself is vendored in ./O2LaF (inference-only fork) and put on sys.path by app.py.
2
  spaces
3
+ av
4
+ diffusers==0.39.0
5
+ peft==0.17.0
6
+ transformers==4.49.0
7
+ safetensors
8
+ opencv-python-headless
9
  imageio
10
  imageio-ffmpeg
11
  hf_transfer
12
+ matplotlib
13
+ scikit-learn