Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 76 additions & 67 deletions mstar/model/vjepa2/vjepa2_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@

Selected via ``model_kwargs={"skip_predictor": True}`` at request time.

Video preprocessing matches HF ``VJEPA2VideoProcessor`` semantics:
resize-shortest-edge to ``crop_size * 256 / 224``, center-crop to
``crop_size``, normalize with ImageNet mean/std. Implemented inline in
``process_prompt`` (no external dep). The AC model, whose checkpoint and
Video preprocessing runs in ``process_prompt`` on the uint8 frames
``load_video`` decodes. The HF checkpoints' frames go through their own
``VJEPA2VideoProcessor`` (``video_preprocessor_config.json``: resize the
shortest edge to ``crop_size * 256 / 224``, center-crop to ``crop_size``,
normalize with ImageNet mean/std). The AC model, whose checkpoint and
reference are the official repo's, takes that repo's central square crop
instead.
"""
Expand Down Expand Up @@ -131,58 +132,29 @@ def _sample_frames_uniform(frames: torch.Tensor, target_t: int) -> torch.Tensor:
return frames[indices]


def _preprocess_video(
frames: torch.Tensor,
crop_size: int,
target_frames: int,
central_square: bool = False,
) -> torch.Tensor:
"""Apply the HF VJEPA2VideoProcessor transform inline.
def _central_square(frames: torch.Tensor, crop_size: int) -> torch.Tensor:
"""The official repo's V-JEPA 2-AC transform of uint8 ``[T, 3, H, W]``
frames: the central square of the short side, resized to ``crop_size``
(bilinear, no antialiasing) and ImageNet-normalized, as float32.

Input: ``[T, C, H, W]`` float in ``[0, 1]`` (matches ``Model.load_video``).
Output: ``[target_frames, C, crop_size, crop_size]``, ImageNet-normalized.

Pipeline: temporal subsample → spatial resize (shortest edge) → center
crop → normalize. Sampling first keeps intermediate memory small.

``central_square`` takes the official repo's V-JEPA 2-AC transform instead:
the central square of the short side, resized to ``crop_size`` (bilinear,
no antialiasing). That is what its ``app/vjepa_droid`` ``make_transforms``
does at scale and aspect ratio 1, where a full-area square never fits a
non-square frame and the random crop falls back to the central one.
That is what its ``app/vjepa_droid`` ``make_transforms`` does at scale and
aspect ratio 1, where a full-area square never fits a non-square frame and
the random crop falls back to the central one. Like upstream it resizes the
0-255 values as floats, but only one frame's square is in float at a time.
"""
if frames.dim() != 4:
raise ValueError(f"Expected [T,C,H,W] video; got {tuple(frames.shape)}")
_, c, h, w = frames.shape
if c != 3:
raise ValueError(f"Expected 3-channel RGB video; got {c} channels")

# Temporal subsample to the model's pretraining clip length.
frames = _sample_frames_uniform(frames, target_frames)

if central_square:
side = min(h, w)
top, left = (h - side) // 2, (w - side) // 2
frames = frames[:, :, top : top + side, left : left + side]
frames = nn.functional.interpolate(
frames, size=(crop_size, crop_size), mode="bilinear", align_corners=False
t, _, h, w = frames.shape
side = min(h, w)
top, left = (h - side) // 2, (w - side) // 2
square = frames[:, :, top : top + side, left : left + side]
mean = torch.tensor(_IMAGENET_MEAN, device=frames.device).view(1, 3, 1, 1) * 255.0
std = torch.tensor(_IMAGENET_STD, device=frames.device).view(1, 3, 1, 1) * 255.0
out = torch.empty(t, 3, crop_size, crop_size, device=frames.device)
for i in range(t):
pixels = nn.functional.interpolate(
square[i : i + 1].float(), size=(crop_size, crop_size), mode="bilinear", align_corners=False
)
else:
resize_short = int(crop_size * 256 / 224)
if h < w:
new_h, new_w = resize_short, int(round(w * resize_short / h))
else:
new_h, new_w = int(round(h * resize_short / w)), resize_short
frames = nn.functional.interpolate(frames, size=(new_h, new_w), mode="bilinear", align_corners=False)

# Center crop to crop_size x crop_size.
top = (new_h - crop_size) // 2
left = (new_w - crop_size) // 2
frames = frames[:, :, top : top + crop_size, left : left + crop_size]

mean = torch.tensor(_IMAGENET_MEAN, device=frames.device, dtype=frames.dtype).view(1, 3, 1, 1)
std = torch.tensor(_IMAGENET_STD, device=frames.device, dtype=frames.dtype).view(1, 3, 1, 1)
return (frames - mean) / std
out[i : i + 1] = (pixels - mean) / std
return out


class VJepa2Model(Model):
Expand Down Expand Up @@ -227,6 +199,7 @@ def __init__(
self.config = self._load_config(predictor_kind, ac_predictor_config)
self._repo_dir: Path | None = None
self._ac_pt_path: Path | None = None
self._video_processor = None
self._submodule_cache: dict[str, NodeSubmodule | None] = {}

# Lazily materialized components (populated in get_submodule).
Expand Down Expand Up @@ -321,6 +294,47 @@ def _ensure_ac_pt(self) -> Path:
)
return self._ac_pt_path

@property
def video_processor(self):
"""The checkpoint's own ``VJEPA2VideoProcessor``, loaded once: resize,
crop size, mean and std as its ``video_preprocessor_config.json`` sets
them. Its crop has to be the one the encoder was built for."""
if self._video_processor is None:
from transformers import AutoVideoProcessor

processor = AutoVideoProcessor.from_pretrained(self.model_path_hf, cache_dir=self.cache_dir)
crop = (processor.crop_size["height"], processor.crop_size["width"])
if crop != (self.config.crop_size, self.config.crop_size):
raise ValueError(
f"{self.model_path_hf}: the video processor crops {crop}, config.json says {self.config.crop_size}"
)
self._video_processor = processor
return self._video_processor

def warmup_preprocess(self) -> None:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A checkpoint without video_preprocessor_config.json hits a bug that main doesn't have: warm_up_model only logs what warmup_preprocess raises, so the server starts and then fails every video request. Loading the processor in __init__, beside _load_config, refuses such a checkpoint at startup, along with one whose processor crops another size.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 3be6ad4, thanks. The processor now loads in __init__ beside _load_config, so a checkpoint without video_preprocessor_config.json, or with another crop, is refused at startup (tests in 211215a).

# so the first video does not load the processor
if self.config.predictor_kind != "ac":
_ = self.video_processor

def _preprocess_video(self, frames: torch.Tensor, target_frames: int) -> torch.Tensor:
"""``target_frames`` of ``load_video``'s uint8 ``[T, 3, H, W]`` frames,
sampled uniformly, as the encoder takes them: float32
``[target_frames, 3, crop_size, crop_size]``.

The HF checkpoints' frames go through their processor, which resizes
the bytes and rounds. V-JEPA 2 is sensitive to that rounding: resizing
floats instead (one uint8 step at most per pixel) gave a cosine of
0.84-0.94 against HF in fp32. The AC model takes ``_central_square``.
"""
if frames.dtype != torch.uint8 or frames.dim() != 4 or frames.size(1) != 3:
raise ValueError(f"Expected uint8 [T, 3, H, W] RGB video; got {frames.dtype} {tuple(frames.shape)}")
frames = _sample_frames_uniform(frames, target_frames)
if self.config.predictor_kind == "ac":
return _central_square(frames, self.config.crop_size)
# already sampled
out = self.video_processor(videos=frames, do_sample_frames=False, return_tensors="pt")
return out["pixel_values_videos"][0]

# ------------------------------------------------------------------
# Model ABC: structure
# ------------------------------------------------------------------
Expand Down Expand Up @@ -591,7 +605,10 @@ def _build_rollout_encoder_node() -> GraphNode:
# ------------------------------------------------------------------

def load_video(self, filepath: str, device: str) -> TensorAndMetadata:
"""Decode a video file into ``[frames_per_clip, C, H, W]`` float in ``[0, 1]``.
"""Decode a video file into ``[frames_per_clip, C, H, W]`` uint8, as decoded.

``process_prompt`` resizes the bytes (``_preprocess_video``), so a float
copy of the full-size clip is never made.

Mirrors HuggingFace ``BaseVideoProcessor`` Path 2
(``video_processing_utils.py:294``): read metadata, compute the
Expand Down Expand Up @@ -665,15 +682,13 @@ def load_video(self, filepath: str, device: str) -> TensorAndMetadata:
frames = torch.stack([decoder[i] for i in indices])
logger.info("load_video: decoded frames shape=%s", tuple(frames.shape))

video = frames.float().div_(255.0)

try:
metadata = video_metadata_dict(metadata_obj) if metadata_obj is not None else {}
except TypeError:
metadata = {}
metadata["sampled_indices"] = indices
metadata["original_num_frames"] = total
return TensorAndMetadata(data=video, metadata=metadata)
return TensorAndMetadata(data=frames, metadata=metadata)

def process_prompt(
self,
Expand All @@ -686,10 +701,9 @@ def process_prompt(
"""Pre-process raw video (and optional AC inputs) for the first forward pass.

Expects the data worker to have populated ``tensors["video_inputs"]``
via :meth:`Model.load_video` (returns ``[T, C, H, W]`` float in
``[0, 1]``). We run HF-style resize + center crop (the official
repo's central square for AC) + ImageNet normalization to produce the
``video_frames`` edge the encoder wants.
via :meth:`load_video` (uint8 ``[T, C, H, W]``). The checkpoint's HF
processor (the official repo's central square for AC) turns them into
the ``video_frames`` edge the encoder wants.

For V-JEPA 2-AC, callers pass per-timestep ``actions``, ``states``
(and optionally ``extrinsics``) through ``**kwargs``.
Expand All @@ -708,12 +722,7 @@ def process_prompt(
# ship 8-frame clips).
target_frames = int(kwargs.get("num_frames", self.config.frames_per_clip))
target_frames = min(target_frames, int(raw.size(0)))
processed = _preprocess_video(
raw.to(torch.float32),
crop_size=self.config.crop_size,
target_frames=target_frames,
central_square=self.config.predictor_kind == "ac",
)
processed = self._preprocess_video(raw, target_frames)
out["video_frames"] = [processed]
logger.info("process_prompt: video_frames shape=%s", tuple(processed.shape))

Expand Down
Loading
Loading