Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
17 changes: 17 additions & 0 deletions config/validation/selection.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1585,6 +1585,23 @@ reviewed_transitions:
after_sha256: 41b40f8e339f296e1d6eafa2ed7413ce80742cb5b36b9536b3d40e0ee2274318

focused_owners:
- paths: [src/flow_factory/data_utils/dataset.py]
symbols: [GeneralDataset.collate_fn, collate_model_inputs]
requires: [evaluation.contracts, sft.dropout.core_contracts, algorithm.offline_dpo.raw_cache]
reason: General and supervised batches share tensor stacking, ragged columns and Python media. Exercise both dataset callers and a native preference update.
- paths: [src/flow_factory/data_utils/offline_dataset.py]
symbols: ['<import:flow_factory.data_utils.dataset.collate_model_inputs>', '<definition_order>', _collate_condition_mappings,
_require_supervision_decoder_coverage, require_supervision_decoders, resolve_media_decoders, supervision_candidates]
requires: [evaluation.contracts, sft.dropout.core_contracts, algorithm.offline_dpo.raw_cache]
reason: Verify finite manifest identity, target and preference arm decoding, worker safety and raw/cached collation.
- paths: [src/flow_factory/data_utils/offline_train_data.py]
symbols: [_available_decoder_types, _iter_supervision_assets, _require_decoder_coverage, _validate_pipeline_outputs]
requires: [evaluation.contracts, sft.dropout.core_contracts, algorithm.offline_dpo.raw_cache]
reason: Both preference arms and demonstration targets must satisfy the pipeline contract and have a worker-safe decoder before preprocessing.
- paths: [src/flow_factory/data_utils/offline_train_data.py]
symbols: ['<module>']
requires: [evaluation.contracts, sft.dropout.core_contracts, algorithm.offline_dpo.raw_cache, sft.dropout.klein_fsdp2, sft.dropout.wan_continuation]
reason: Module-wide binding changes in the offline loader exercise its full SFT and preference input paths, including distributed continuation.
- paths:
- src/flow_factory/data_utils/offline_dataset.py
- src/flow_factory/data_utils/offline_loader.py
Expand Down
6 changes: 4 additions & 2 deletions guidance/training/sft-conditioning.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,10 @@ Native recipes are qualified for `ByteDance-Seed/BAGEL-7B-MoT`, `sensenova/Sense

### Cache, resume and diagnostics

With `data.enable_preprocess: true`, positive inputs stay in the usual input cache. For independent text encoders such as Klein, one deterministic absent-text entry can serve different references within a source. The cached reference tokens stay on their positive rows. For joint encoders such as Qwen Edit, the alternate includes the original references, order and template. Packed models assemble the selected prefix during training. Set `data.force_reprocess: false` to reuse existing compatible caches.
With `data.enable_preprocess: true`, the loader builds the positive cache and any required alternate caption cache before training. A cache miss loads the adapter's preprocessing components onto the execution device once for that preparation phase. Set `data.force_reprocess: false` to reuse compatible caches. Hits across all splits skip that device load. The default `true` rebuilds the caches. A training-time dropout draw reads the selected row. It does not trigger a text-encoder reload. Components needed for other model roles follow their own loading policy.

With `data.enable_preprocess: false`, workers load condition media and targets. The training rank encodes only the selected condition with frozen preprocessing components. Offline DPO supports the same cached and on-demand paths. Both preference arms share one complete input condition. Condition dropout applies only to SFT.
Empty captions are deduplicated **within each source** using the retained input. For text-only records, different positive prompts can share the same empty-caption encoding when their negative prompt matches. Separable encoders such as Klein can also share it across different reference images: their visual tokens stay on the positive row. Joint encoders such as Qwen Edit retain the ordered references in the alternate input. Model, checkpoint, preprocessing settings and policy revision participate in the alternate cache identity. Packed models assemble the selected prefix during training.

With `data.enable_preprocess: false`, workers load condition media and targets. The training rank makes the preprocessing components available for optimization and encodes the selected input for each record as it is consumed. Repeated empty captions on this path are encoded again. Offline DPO supports the same cached and on-demand paths. Both preference arms share one complete input condition. Condition dropout applies only to SFT.

A fixed training seed, data epoch and record identity reproduce each draw across workers and model-parallel peers. Changing the probability or policy revision changes exact-resume identity. Metrics under `condition_dropout/prompt/` and `condition_dropout/reference/` report observed records, eligible records, dropped records and segment counts per optimizer window. Divide `dropped` by `eligible` to inspect the realized rate. Evaluation uses its configured conditions.
63 changes: 23 additions & 40 deletions src/flow_factory/data_utils/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -987,7 +987,7 @@ def __getitem__(self, idx):
return self.processed_dataset[idx]

@staticmethod
def collate_fn(batch: List[Dict[str, Any]]) -> Dict[str, Any]:
def collate_fn(batch: Sequence[Mapping[str, Any]]) -> Dict[str, Any]:
"""Collate function for DataLoader.

Stacks tensors with same shape, keeps ragged tensors as lists. Image
Expand All @@ -1003,52 +1003,35 @@ def collate_fn(batch: List[Dict[str, Any]]) -> Dict[str, Any]:
Returns:
Collated batch dictionary
"""
if not batch:
return {}

collated_batch = {}
for key in batch[0].keys():
values = [sample[key] for sample in batch]
# Classify value types
is_tensor = [isinstance(v, torch.Tensor) for v in values]
is_list = [isinstance(v, list) for v in values]

if all(is_tensor):
# Case 1: All elements are tensors
shapes = [v.shape for v in values]
if all(s == shapes[0] for s in shapes):
# Same shape → stack into batch tensor
collated_batch[key] = torch.stack(values, dim=0)
else:
# Different shapes → keep as List[Tensor]
collated_batch[key] = values

elif any(is_tensor) and any(is_list):
# Case 2: Mixed tensor/list → normalize to List[List[Tensor]].
# Handles ragged tensor columns (e.g. image latents) where the
# dataset auto-stacks same-shape samples into a Tensor but keeps
# variable-shape samples as List[Tensor]; unbind the stacked ones
# so the whole column is a consistent List[List[Tensor]].
collated_batch[key] = [
list(torch.unbind(v, dim=0)) if isinstance(v, torch.Tensor) else v
for v in values
]

else:
# Case 3: Other types (lists, ints, strs, and python-format
# columns: metadata dicts and PIL image columns).
# Image columns arrive here as per-sample List[PIL.Image]; keeping
# `values` yields a List[List[PIL.Image]] MultiImageBatch.
collated_batch[key] = values

return collated_batch
return collate_model_inputs(batch)


# ========================================================================================
# Utility Functions
# ========================================================================================


def collate_model_inputs(batch: Sequence[Mapping[str, Any]]) -> Dict[str, Any]:
"""Stack equal-shaped tensors and preserve per-record structure for ragged or Python fields."""
if not batch:
return {}
columns = {}
for key in batch[0]:
values = [row[key] for row in batch]
tensors = [isinstance(value, torch.Tensor) for value in values]
if all(tensors) and all(value.shape == values[0].shape for value in values):
columns[key] = torch.stack(values)
elif any(tensors) and any(isinstance(value, list) for value in values):
# Arrow can return a stacked tensor for one record and a ragged list for another.
columns[key] = [
list(value.unbind(0)) if isinstance(value, torch.Tensor) else value
for value in values
]
else:
columns[key] = values
return columns


def _validate_source_hash_override(value: Optional[str]) -> Optional[str]:
"""Validate an optional caller-owned source-content identity."""
if value is None:
Expand Down
76 changes: 33 additions & 43 deletions src/flow_factory/data_utils/offline_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
except ImportError:
av = None

from .dataset import collate_model_inputs
from .schema import (
DatasetRecordV2,
DemonstrationSupervision,
Expand Down Expand Up @@ -255,14 +256,8 @@ def __init__(
context=f"offline dataset index {index}",
)

decoders: Dict[MediaType, MediaDecoder] = dict(DEFAULT_MEDIA_DECODERS)
if media_decoders is not None:
for media_type, decoder in media_decoders.items():
if media_type not in ("image", "video", "audio"):
raise ValueError(f"unsupported media decoder type: {media_type!r}")
_require_picklable_unbound_decoder(media_type, decoder)
decoders[media_type] = decoder
_require_supervision_decoder_coverage(
decoders = resolve_media_decoders(media_decoders)
require_supervision_decoders(
normalized_records,
decoders,
source_name=source_name,
Expand Down Expand Up @@ -771,25 +766,40 @@ def _extract_condition(
return {key: value for key, value in row.items() if key != OFFLINE_CONDITION_ID_COLUMN}


def _require_supervision_decoder_coverage(
def resolve_media_decoders(
overrides: Mapping[MediaType, MediaDecoder] | None,
) -> dict[MediaType, MediaDecoder]:
"""Resolve the decoder registry and validate overrides before workers or caches start."""
decoders = dict(DEFAULT_MEDIA_DECODERS)
for media_type, decoder in (overrides or {}).items():
if media_type not in ("image", "video", "audio"):
raise ValueError(f"unsupported media decoder type: {media_type!r}")
_require_picklable_unbound_decoder(media_type, decoder)
decoders[media_type] = decoder
return decoders


def supervision_candidates(
record: NormalizedDatasetRecord,
) -> tuple[tuple[str, NormalizedOutputCandidate], ...]:
"""Return supervised output arms in manifest order for offline input checks."""
supervision = record.supervision
if isinstance(supervision, DemonstrationSupervision):
return (("target", supervision.target),)
if isinstance(supervision, PreferenceSupervision):
return (("chosen", supervision.chosen), ("rejected", supervision.rejected))
raise ValueError("offline supervision requires a demonstration or preference pair")


def require_supervision_decoders(
records: Sequence[NormalizedDatasetRecord],
decoders: Mapping[MediaType, MediaDecoder],
*,
source_name: str,
) -> None:
"""Require a decoder for every target asset before any inputs are preprocessed."""
for record_index, record in enumerate(records):
supervision = record.supervision
candidates: tuple[tuple[str, NormalizedOutputCandidate], ...]
if isinstance(supervision, DemonstrationSupervision):
candidates = (("target", supervision.target),)
elif isinstance(supervision, PreferenceSupervision):
candidates = (
("chosen", supervision.chosen),
("rejected", supervision.rejected),
)
else:
continue
for candidate_name, candidate in candidates:
for candidate_name, candidate in supervision_candidates(record):
for media_index, asset in enumerate(candidate.media):
if asset.type not in decoders:
raise NotImplementedError(
Expand All @@ -803,8 +813,7 @@ def _require_supervision_decoder_coverage(
def _collate_condition_mappings(
conditions: Sequence[Mapping[str, Any]],
) -> Dict[str, Any]:
expected_keys = tuple(conditions[0].keys())
expected_key_set = set(expected_keys)
expected_key_set = set(conditions[0])
for index, condition in enumerate(conditions):
if set(condition.keys()) != expected_key_set:
raise ValueError(
Expand All @@ -813,26 +822,7 @@ def _collate_condition_mappings(
f"{sorted(condition.keys())!r} at batch index {index}"
)

collated: Dict[str, Any] = {}
for key in expected_keys:
values = [condition[key] for condition in conditions]
if all(isinstance(value, torch.Tensor) for value in values):
shapes = [value.shape for value in values]
collated[key] = (
torch.stack(values, dim=0)
if all(shape == shapes[0] for shape in shapes)
else values
)
elif any(isinstance(value, torch.Tensor) for value in values) and any(
isinstance(value, list) for value in values
):
collated[key] = [
list(torch.unbind(value, dim=0)) if isinstance(value, torch.Tensor) else value
for value in values
]
else:
collated[key] = values
return collated
return collate_model_inputs(conditions)


def _validate_supervision_type(supervision_type: str) -> None:
Expand Down
74 changes: 9 additions & 65 deletions src/flow_factory/data_utils/offline_train_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,22 +51,18 @@
)
from .offline_conditions import RawOfflineConditionSource
from .offline_dataset import (
DEFAULT_MEDIA_DECODERS,
OFFLINE_CONDITION_ID_COLUMN,
MediaDecoder,
OfflineDataset,
OfflineSupervisionType,
compute_offline_condition_id,
load_offline_manifest,
require_supervision_decoders,
resolve_media_decoders,
supervision_candidates,
)
from .offline_loader import build_offline_dataloader
from .schema import (
DemonstrationSupervision,
MediaAsset,
MediaType,
NormalizedDatasetRecord,
PreferenceSupervision,
)
from .schema import MediaType, NormalizedDatasetRecord
from .sft_conditions import SFTConditionSource, absent_caption_records


Expand Down Expand Up @@ -179,7 +175,7 @@ def build_offline_train_dataloader(
preprocess_func,
preprocess_kwargs,
)
available_decoder_types = _available_decoder_types(media_decoders)
decoders = resolve_media_decoders(media_decoders)

source_records = []
for source in training_sources:
Expand Down Expand Up @@ -211,9 +207,9 @@ def build_offline_train_dataloader(
contract=pipeline_io_contract,
source_name=source.name,
)
_require_decoder_coverage(
require_supervision_decoders(
records,
available_decoder_types,
decoders,
source_name=source.name,
)
source_records.append((source, dataset_dir, records))
Expand Down Expand Up @@ -351,19 +347,9 @@ def _validate_pipeline_outputs(
) -> None:
"""Validate every supervision candidate before condition preprocessing."""
for row_index, record in enumerate(records):
supervision = record.supervision
if isinstance(supervision, DemonstrationSupervision):
candidates = (("target", supervision.target.media),)
elif isinstance(supervision, PreferenceSupervision):
candidates = (
("chosen", supervision.chosen.media),
("rejected", supervision.rejected.media),
)
else:
raise RuntimeError("normalized offline record unexpectedly lacks supervision")
for candidate_name, media in candidates:
for candidate_name, candidate in supervision_candidates(record):
try:
validate_pipeline_output_candidate(media, contract)
validate_pipeline_output_candidate(candidate.media, contract)
except (TypeError, ValueError) as exc:
error_type = type(exc)
raise error_type(
Expand Down Expand Up @@ -563,46 +549,4 @@ def _slice_records(
return tuple(records[:max_dataset_size])


def _available_decoder_types(
media_decoders: Optional[Mapping[MediaType, MediaDecoder]],
) -> frozenset[MediaType]:
available = set(DEFAULT_MEDIA_DECODERS)
if media_decoders is not None:
for media_type in media_decoders:
if media_type not in ("image", "video", "audio"):
raise ValueError(f"unsupported offline media decoder type: {media_type!r}")
available.add(media_type)
return frozenset(available)


def _require_decoder_coverage(
records: Sequence[NormalizedDatasetRecord],
available_decoder_types: frozenset[MediaType],
*,
source_name: str,
) -> None:
for asset in _iter_supervision_assets(records):
if asset.type not in available_decoder_types:
raise NotImplementedError(
f"offline source {source_name!r} has no decoder for target media type "
f"{asset.type!r} at {asset.path!r}"
)


def _iter_supervision_assets(
records: Sequence[NormalizedDatasetRecord],
) -> Sequence[MediaAsset]:
assets = []
for record in records:
supervision = record.supervision
if isinstance(supervision, DemonstrationSupervision):
assets.extend(supervision.target.media)
elif isinstance(supervision, PreferenceSupervision):
assets.extend(supervision.chosen.media)
assets.extend(supervision.rejected.media)
else:
raise RuntimeError("normalized offline record unexpectedly lacks supervision")
return tuple(assets)


__all__ = ["build_offline_train_dataloader"]
23 changes: 21 additions & 2 deletions tests/data_utils/test_offline_train_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -649,7 +649,7 @@ def test_builder_rejects_missing_target_decoder_before_condition_preprocessing(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(
offline_train_data,
offline_dataset_module,
"DEFAULT_MEDIA_DECODERS",
{
media_type: decoder
Expand Down Expand Up @@ -683,7 +683,7 @@ def test_builder_rejects_missing_target_decoder_before_condition_preprocessing(

with pytest.raises(
NotImplementedError,
match=r"source 'audio'.*type 'audio'.*target\.wav",
match=r"source 'audio'.*target media 0.*target\.wav.*type 'audio' with no decoder",
):
build_offline_train_dataloader(
_config(tmp_path, [_source("audio", dataset_dir, 0)]),
Expand Down Expand Up @@ -1022,3 +1022,22 @@ def build(encoder):
raw.output.chosen_media[0][0].payload.tobytes()
!= raw.output.rejected_media[0][0].payload.tobytes()
)


def test_builder_rejects_worker_decoder_before_encoding_preferences(tmp_path):
source = tmp_path / "pairs"
source.mkdir()
_write_image(source / "chosen.png", 32)
_write_image(source / "rejected.png", 192)
_write_manifest(source, [_preference_row("edit", "chosen.png", "rejected.png")])
encoder = _CountingPreprocessor()
with pytest.raises(TypeError, match="module scope for spawn"):
build_offline_train_dataloader(
_config(tmp_path, [_source("pairs", source, 0)]),
_Accelerator(),
encoder.preprocess,
supervision_type="preference",
pipeline_io_contract=_TEXT_TO_IMAGE_CONTRACT,
media_decoders={"image": lambda asset: asset},
)
assert encoder.calls == 0
Loading
Loading