| |
| """Read LocateAnything records and image bytes with Megatron-Energon 7.4.""" |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| from pathlib import Path |
| from typing import Any, Mapping, Sequence |
|
|
| from megatron.energon import ( |
| Cooker, |
| DefaultTaskEncoder, |
| FileStore, |
| Sample, |
| WorkerConfig, |
| basic_sample_keys, |
| cooker, |
| edataclass, |
| get_savable_loader, |
| get_train_dataset, |
| stateless, |
| ) |
|
|
|
|
| @edataclass |
| class LocateAnythingSample(Sample): |
| """One spatial annotation and its encoded image bytes.""" |
|
|
| record: dict[str, Any] |
| image: bytes |
|
|
|
|
| def _record(sample: Mapping[str, Any]) -> dict[str, Any]: |
| payload = sample.get("json") |
| if isinstance(payload, Mapping): |
| record = dict(payload) |
| elif isinstance(payload, (bytes, bytearray, str)): |
| record = json.loads(payload) |
| else: |
| raise ValueError( |
| "Energon sample does not contain a mapping- or JSON-valued 'json' field" |
| ) |
| if not isinstance(record, dict): |
| raise ValueError("LocateAnything record must be a JSON object") |
| if set(record) != {"_source", "image", "query", "task_type"}: |
| raise ValueError("LocateAnything record schema mismatch") |
| return record |
|
|
|
|
| @stateless |
| def cook_locate_anything( |
| sample: dict[str, Any], **aux: FileStore |
| ) -> LocateAnythingSample: |
| record = _record(sample) |
| image = record["image"] |
| source = image["source"] |
| member_name = image["path"] |
| try: |
| store = aux[source] |
| except KeyError as error: |
| raise ValueError(f"annotation names unknown auxiliary source {source!r}") from error |
| encoded = store.get(member_name, sample) |
| return LocateAnythingSample( |
| **basic_sample_keys(sample), |
| record=record, |
| image=encoded, |
| ) |
|
|
|
|
| class LocateAnythingTaskEncoder( |
| DefaultTaskEncoder[ |
| LocateAnythingSample, |
| LocateAnythingSample, |
| LocateAnythingSample, |
| LocateAnythingSample, |
| ] |
| ): |
| """Minimal encoder; subclass its packing methods for model token budgets.""" |
|
|
| decoder = None |
|
|
| def __init__(self) -> None: |
| self.cookers = [Cooker(cook_locate_anything)] |
| super().__init__() |
|
|
| @stateless |
| def select_samples_to_pack( |
| self, samples: list[LocateAnythingSample] |
| ) -> list[list[LocateAnythingSample]]: |
| return [[sample] for sample in samples] |
|
|
| @stateless |
| def pack_selected_samples( |
| self, samples: list[LocateAnythingSample] |
| ) -> LocateAnythingSample: |
| if len(samples) != 1: |
| raise ValueError("the example encoder only supports singleton packs") |
| return samples[0] |
|
|
|
|
| def _parser() -> argparse.ArgumentParser: |
| parser = argparse.ArgumentParser(description=__doc__) |
| parser.add_argument( |
| "metadataset", |
| type=Path, |
| help="Root, dataset, or view-level metadataset.yaml.", |
| ) |
| parser.add_argument("--samples", type=int, default=3) |
| parser.add_argument("--workers", type=int, default=0) |
| parser.add_argument("--rank", type=int, default=0) |
| parser.add_argument("--world-size", type=int, default=1) |
| return parser |
|
|
|
|
| def main(argv: Sequence[str] | None = None) -> int: |
| args = _parser().parse_args(argv) |
| worker_config = WorkerConfig( |
| rank=args.rank, |
| world_size=args.world_size, |
| num_workers=args.workers, |
| ) |
| dataset = get_train_dataset( |
| args.metadataset, |
| split_part="train", |
| worker_config=worker_config, |
| batch_size=None, |
| max_samples_per_sequence=1, |
| shuffle_over_epochs_multiplier=1, |
| shuffle_buffer_size=None, |
| task_encoder=LocateAnythingTaskEncoder(), |
| repeat=False, |
| ) |
| loader = get_savable_loader(dataset) |
| for index, sample in enumerate(loader): |
| print( |
| json.dumps( |
| { |
| "sample": index, |
| "sample_id": sample.record["_source"]["sample_id"], |
| "task_type": sample.record["task_type"], |
| "image_bytes": len(sample.image), |
| }, |
| ensure_ascii=False, |
| sort_keys=True, |
| ) |
| ) |
| if index + 1 >= args.samples: |
| break |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| raise SystemExit(main()) |
|
|