File size: 7,468 Bytes
ce88b75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
207
208
209
210
211
212
213
214
215
216
217
218
219
"""
Convert one ground_olmo dataset to JSONL format with polygon coordinates.

Uses multiprocessing for RLE→polygon conversion on large datasets.

Usage:
    python scripts/convert_dataset.py \
        --dataset coconut_pos_neg \
        --split train \
        --output data/coconut_pos_neg_train.jsonl \
        --seed 42 \
        --max_examples 0 \
        --workers 8
"""

import argparse
import json
import logging
import sys
import time
from multiprocessing import Pool, cpu_count

import numpy as np

sys.path.insert(0, "/weka-mm/royg/ground_olmo")
sys.path.insert(0, "/weka-mm/royg/ft_qwen3_5")

from ft_qwen35.data.dataset import (
    GroundingSourceDataset,
    make_random_state,
    DATASET_REGISTRY,
)
from ft_qwen35.data.formatter import extract_instance_polygons

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)

# Global dataset reference for worker processes
_worker_dataset = None


def _init_worker(dataset_name, split):
    """Initialize dataset in each worker process."""
    global _worker_dataset
    _worker_dataset = GroundingSourceDataset(dataset_name, split=split)


def _convert_one(args):
    """Convert a single sample. Called in worker process."""
    idx, seed, split = args
    global _worker_dataset
    ds = _worker_dataset

    rng = make_random_state(seed, idx, 0, 1)
    try:
        example = ds.get(idx, rng)
    except Exception as e:
        return None, str(e)

    image_path = example.get("image", None)
    if image_path is None:
        return None, None

    category_name = example.get("category_name", "")
    instances = example.get("instances", [])
    instance_order = example.get("instance_order", list(range(len(instances))))
    char_spans = example.get("char_spans_per_instance", [])

    from PIL import Image
    try:
        with Image.open(image_path) as img:
            orig_w, orig_h = img.size
    except Exception as e:
        return None, str(e)

    instances_data = []
    for i, inst in enumerate(instances):
        try:
            polygons, source = extract_instance_polygons(inst)
        except Exception:
            polygons, source = [], "error"
        inst_char_spans = char_spans[i] if i < len(char_spans) else []
        instances_data.append({
            "polygons": polygons,
            "char_spans": inst_char_spans,
            "polygon_source": source,
            "category_name": inst.get("category_name", ""),
        })

    record = {
        "image": image_path,
        "grounding_text": category_name,
        "instances": instances_data,
        "instance_order": list(int(x) for x in instance_order),
        "orig_h": orig_h,
        "orig_w": orig_w,
        "dataset_name": ds.dataset_name,
        "split": split,
    }
    return record, None


def main():
    parser = argparse.ArgumentParser(description="Convert ground_olmo dataset to JSONL")
    parser.add_argument("--dataset", type=str, required=True,
                        choices=list(DATASET_REGISTRY.keys()))
    parser.add_argument("--split", type=str, default="train")
    parser.add_argument("--output", type=str, required=True)
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--max_examples", type=int, default=0,
                        help="Max examples to convert (0 = all)")
    parser.add_argument("--workers", type=int, default=0,
                        help="Number of worker processes (0 = auto based on dataset size)")
    args = parser.parse_args()

    logger.info(f"Loading dataset: {args.dataset} ({args.split})")
    ds = GroundingSourceDataset(args.dataset, split=args.split)
    n = len(ds)
    if args.max_examples > 0:
        n = min(n, args.max_examples)
    logger.info(f"Converting {n} samples...")

    num_workers = args.workers
    if num_workers <= 0:
        # Auto: use multiprocessing for large datasets, single-process for small
        if n > 5000:
            num_workers = min(cpu_count(), 16)
        else:
            num_workers = 0

    # Stats
    total_instances = 0
    total_poly_points = 0
    total_segments = 0
    source_counts = {}
    skipped = 0
    written = 0

    t0 = time.time()
    work_args = [(idx, args.seed, args.split) for idx in range(n)]

    if num_workers > 1:
        logger.info(f"Using {num_workers} worker processes")
        # Multiprocessing path
        with open(args.output, "w") as f:
            with Pool(
                processes=num_workers,
                initializer=_init_worker,
                initargs=(args.dataset, args.split),
            ) as pool:
                for i, (record, err) in enumerate(
                    pool.imap(_convert_one, work_args, chunksize=64)
                ):
                    if err:
                        logger.warning(f"Error on sample {i}: {err}")
                        skipped += 1
                        continue
                    if record is None:
                        skipped += 1
                        continue

                    for inst in record["instances"]:
                        total_instances += 1
                        src = inst.get("polygon_source", "unknown")
                        source_counts[src] = source_counts.get(src, 0) + 1
                        for poly in inst["polygons"]:
                            total_segments += 1
                            total_poly_points += len(poly)

                    f.write(json.dumps(record) + "\n")
                    written += 1

                    if (i + 1) % 10000 == 0:
                        elapsed = time.time() - t0
                        rate = (i + 1) / elapsed
                        eta = (n - i - 1) / rate if rate > 0 else 0
                        logger.info(f"  {i + 1}/{n} samples ({rate:.0f}/s, ETA {eta:.0f}s)")
    else:
        logger.info("Using single process")
        # Single-process path
        with open(args.output, "w") as f:
            for idx in range(n):
                record, err = _convert_one((idx, args.seed, args.split))
                if err:
                    logger.warning(f"Error on sample {idx}: {err}")
                    skipped += 1
                    continue
                if record is None:
                    skipped += 1
                    continue

                for inst in record["instances"]:
                    total_instances += 1
                    src = inst.get("polygon_source", "unknown")
                    source_counts[src] = source_counts.get(src, 0) + 1
                    for poly in inst["polygons"]:
                        total_segments += 1
                        total_poly_points += len(poly)

                f.write(json.dumps(record) + "\n")
                written += 1

                if (idx + 1) % 1000 == 0:
                    logger.info(f"  Converted {idx + 1}/{n} samples...")

    elapsed = time.time() - t0

    logger.info(f"\nConversion complete in {elapsed:.1f}s")
    logger.info(f"  Written: {written} samples to {args.output}")
    logger.info(f"  Skipped: {skipped}")
    logger.info(f"  Avg instances/sample: {total_instances / max(written, 1):.1f}")
    logger.info(f"  Avg segments/instance: {total_segments / max(total_instances, 1):.1f}")
    logger.info(f"  Avg points/segment: {total_poly_points / max(total_segments, 1):.1f}")
    logger.info(f"  Polygon source breakdown: {source_counts}")


if __name__ == "__main__":
    main()