Spaces:
Running on Zero

File size: 7,709 Bytes
a1833c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: OpenMDW-1.1

"""
Hydra ConfigStore registration for the open-source SFT dataloader.

This mirrors the inline ``dataloader_train`` block in
``configs/experiment/mixed_modality_sft_8b.yaml`` (cosmos-inference) so users
can pick it up via the Hydra defaults group::

    defaults:
      - data_train: open_source_sft_video_256p

or as a base to override in their own experiment configs::

    L(get_open_source_sft_dataloader)(
        jsonl_paths=["/path/to/data.jsonl"],
        resolution="256",
        max_sequence_length=45056,
    )

Original YAML reference target paths use the ``cosmos3._src.vfm.*`` namespace
(the OSS-release form of ``projects.cosmos3.vfm.*``); inside this released
tree the same modules live under ``cosmos_framework.data.generator.*``.
"""

from hydra.core.config_store import ConfigStore

from cosmos_framework.configs.base.defaults.reasoner import create_qwen2_tokenizer_with_download
from cosmos_framework.data.generator.joint_dataloader import (
    PackingDataLoader,
    RankPartitionedDataLoader,
)
from cosmos_framework.data.generator.local_datasets.sft_dataset import get_sft_dataset
from cosmos_framework.utils.lazy_config import LazyCall as L

# ---------------------------------------------------------------------------
# Inner: SFT video dataset (matches the inline ``get_sft_dataset`` call in the
# reference YAML).
# ---------------------------------------------------------------------------


def get_sft_video_dataset(
    *,
    jsonl_paths: list[str],
    resolution: str = "256",
    pretrained_model_name: str = "Qwen/Qwen3-VL-8B-Instruct",
    tokenizer_config_variant: str = "hf",
    num_video_frames: int = -1,
    temporal_compression_factor: int = 4,
    temporal_interval_mode: str = "max_30fps",
    min_short_edge: int = 0,
    frame_selection_mode: str = "first",
    sample_by_window: bool = False,
    append_duration_fps_timestamps: bool = True,
    append_resolution_info: bool = True,
    use_system_prompt: bool = False,
    # Structured-JSON captions are far longer than dense prose; raise the token
    # budget so the loader does not truncate them mid-JSON (see sft_dataset.py
    # _MAX_CAPTION_TOKENS). 2048 covers the example dataset (measured max ~1790 Qwen
    # tokens) with margin; keep consistent with the inference prompt budget.
    max_caption_tokens: int = 2048,
    caption_suffix: str = "",
    cfg_dropout_rate: float = 0.1,
    cfg_dropout_keep_metadata: bool = False,
    conditioning_config: dict[int, float] | None = None,
    conditioning_fps: int = -1,
    conditioning_fps_noise_std: float = 0.0,
):
    """LazyCall'd version of ``get_sft_dataset`` matching the reference YAML.

    Defaults reproduce ``mixed_modality_sft_8b.yaml``: 70% T2V / 20% I2V /
    10% V2V conditioning mix at 256p with the Qwen3-VL-8B tokenizer.
    """
    if conditioning_config is None:
        # 0: T2V (text-to-video) β€” 70%
        # 1: I2V (first-frame conditioning) β€” 20%
        # 2: V2V (first 5 frames β†’ 2 latent frames) β€” 10%
        conditioning_config = {0: 0.7, 1: 0.2, 2: 0.1}

    return L(get_sft_dataset)(
        jsonl_paths=jsonl_paths,
        resolution=resolution,
        num_video_frames=num_video_frames,
        temporal_compression_factor=temporal_compression_factor,
        temporal_interval_mode=temporal_interval_mode,
        min_short_edge=min_short_edge,
        frame_selection_mode=frame_selection_mode,
        sample_by_window=sample_by_window,
        append_duration_fps_timestamps=append_duration_fps_timestamps,
        append_resolution_info=append_resolution_info,
        use_system_prompt=use_system_prompt,
        max_caption_tokens=max_caption_tokens,
        caption_suffix=caption_suffix,
        cfg_dropout_rate=cfg_dropout_rate,
        cfg_dropout_keep_metadata=cfg_dropout_keep_metadata,
        conditioning_config=conditioning_config,
        conditioning_fps=conditioning_fps,
        conditioning_fps_noise_std=conditioning_fps_noise_std,
        tokenizer_config=L(create_qwen2_tokenizer_with_download)(
            pretrained_model_name=pretrained_model_name,
            config_variant=tokenizer_config_variant,
        ),
    )


# ---------------------------------------------------------------------------
# Outer: full PackingDataLoader β†’ RankPartitionedDataLoader β†’ SFT dataset
# pipeline. This is the registered config_store node.
# ---------------------------------------------------------------------------


def get_open_source_sft_dataloader(
    *,
    jsonl_paths: list[str] | None = None,
    resolution: str = "256",
    batch_size: int = 1,
    max_sequence_length: int = 45056,
    max_samples_per_batch: int | None = None,
    num_workers: int = 4,
    prefetch_factor: int = 4,
    audio_sample_rate: int = 48000,
    patch_spatial: int = 2,
    tokenizer_spatial_compression_factor: int = 16,
    tokenizer_temporal_compression_factor: int = 4,
    sound_latent_fps: int = 0,
    dataset_name: str = "default",
    video_stream_ratio: float = 1.0,
):
    """Build the full open-source SFT dataloader (PackingDataLoader at top).

    ``jsonl_paths`` defaults to a Hydra-MISSING marker (``"???"``) so the
    user MUST override it at experiment time::

        ... dataloader_train.dataloader.datasets.video.dataset.jsonl_paths='[".../data.jsonl"]'
    """
    if jsonl_paths is None:
        # Hydra/OmegaConf "mandatory" sentinel β€” must be overridden.
        jsonl_paths = "???"  # type: ignore[assignment]

    return L(PackingDataLoader)(
        dataloader=L(RankPartitionedDataLoader)(
            batch_size=batch_size,
            datasets=dict(
                video=dict(
                    dataset=get_sft_video_dataset(
                        jsonl_paths=jsonl_paths,
                        resolution=resolution,
                    ),
                    ratio=video_stream_ratio,
                ),
            ),
            in_order=True,
            num_workers=num_workers,
            persistent_workers=True,
            pin_memory=True,
            prefetch_factor=prefetch_factor,
            sampler=None,
        ),
        audio_sample_rate=audio_sample_rate,
        dataset_name=dataset_name,
        max_samples_per_batch=max_samples_per_batch,
        max_sequence_length=max_sequence_length,
        patch_spatial=patch_spatial,
        sound_latent_fps=sound_latent_fps,
        tokenizer_spatial_compression_factor=tokenizer_spatial_compression_factor,
        tokenizer_temporal_compression_factor=tokenizer_temporal_compression_factor,
    )


# ---------------------------------------------------------------------------
# ConfigStore registration.
# ---------------------------------------------------------------------------


def register_open_source_dataloaders() -> None:
    """Register named dataloader configs under the ``data_train`` Hydra group.

    Pick them via experiment config::

        defaults:
          - data_train: open_source_sft_video_256p
          - data_train: open_source_sft_video_480p
          - data_train: open_source_sft_video_720p
    """
    cs = ConfigStore.instance()

    for res_str, max_seq in [
        ("256", 45056),
        ("480", 45056),
        ("720", 45056),
    ]:
        cs.store(
            group="data_train",
            package="dataloader_train",
            name=f"open_source_sft_video_{res_str}p",
            node=get_open_source_sft_dataloader(
                resolution=res_str,
                max_sequence_length=max_seq,
            ),
        )


# Auto-register on import.
register_open_source_dataloaders()