yunfengwang commited on
Commit
766d72e
·
verified ·
1 Parent(s): 0f0f196

Upload scripts/generate_sft_grounding_data.py with huggingface_hub

Browse files
scripts/generate_sft_grounding_data.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Generate SFT grounding data with negative samples for improved precision and rejection ability.
4
+
5
+ Produces:
6
+ - data/sft/grounding/sft_grounding.jsonl
7
+ - 70% positive samples with full CoT thinking template
8
+ - 30% negative samples (object not in image -> empty response)
9
+
10
+ Usage:
11
+ python scripts/generate_sft_grounding_data.py \
12
+ --coco_jsonl data/pretrain/grounding.jsonl \
13
+ --image_root data/coco/val \
14
+ --output data/sft/grounding/sft_grounding.jsonl \
15
+ --neg_ratio 0.30
16
+ """
17
+
18
+ import os
19
+ import sys
20
+ import json
21
+ import random
22
+ import argparse
23
+ from pathlib import Path
24
+ from collections import defaultdict
25
+
26
+ PROJECT_ROOT = Path(__file__).resolve().parent.parent
27
+ sys.path.insert(0, str(PROJECT_ROOT))
28
+
29
+ from utils.coco_categories import COCO_CATS
30
+
31
+ random.seed(42)
32
+
33
+ IRREGULAR_PLURALS = {
34
+ "person": "people",
35
+ "mouse": "mice",
36
+ "sheep": "sheep",
37
+ "knife": "knives",
38
+ "child": "children",
39
+ }
40
+
41
+
42
+ def pluralize(word: str) -> str:
43
+ low = word.lower()
44
+ if low in IRREGULAR_PLURALS:
45
+ return IRREGULAR_PLURALS[low]
46
+ if " " in word:
47
+ parts = word.rsplit(" ", 1)
48
+ return parts[0] + " " + pluralize(parts[1])
49
+ if word.endswith(("s", "sh", "ch", "x", "z")):
50
+ return word + "es"
51
+ if word.endswith("y") and word[-2] not in "aeiou":
52
+ return word[:-1] + "ies"
53
+ return word + "s"
54
+
55
+
56
+ GROUNDING_TEMPLATES = [
57
+ "Locate the {category} in the image.",
58
+ "Locate the {category} in this image.",
59
+ "Find the {category} in the image.",
60
+ "Where is the {category} in the image?",
61
+ "Where is the {category}?",
62
+ "Show me the {category} in the image.",
63
+ "Point out the {category}.",
64
+ "Locate the {plural} in the image.",
65
+ ]
66
+
67
+
68
+ def format_box_token(boxes):
69
+ """Format boxes into <|box|>[[x1,y1,x2,y2],...]<|/box|>."""
70
+ if not boxes:
71
+ return ""
72
+ inner = ",".join(f"[{x1},{y1},{x2},{y2}]" for x1, y1, x2, y2 in boxes)
73
+ return f"<|box|>[{inner}]<|/box|>"
74
+
75
+
76
+ def build_positive_thinking(category, boxes):
77
+ """Build CoT thinking for positive sample."""
78
+ refs = "\n".join(
79
+ f"I see a <|ref|>{category}<|/ref|><|box|>[[{b[0]},{b[1]},{b[2]},{b[3]}]]<|/box|>."
80
+ for b in (boxes if boxes else [])
81
+ )
82
+ if not refs:
83
+ refs = f"I see a <|ref|>{category}<|/ref|><|box|>[]<|/box|>."
84
+
85
+ return (
86
+ f"1. **Analyzing the request**\n"
87
+ f"The user asks me to locate the {category} in this image.\n"
88
+ f"2. **Object grounding**\n"
89
+ f"{refs}\n"
90
+ f"3. **Conclusion**\n"
91
+ f"The {category} is located at the specified coordinates."
92
+ )
93
+
94
+
95
+ def build_positive_answer(category, boxes):
96
+ if not boxes:
97
+ return f"The {category} is not visible in the image."
98
+ box_str = ",".join(f"[{x1},{y1},{x2},{y2}]" for x1, y1, x2, y2 in boxes)
99
+ return f"The {category} is located at [{box_str}]."
100
+
101
+
102
+ def build_negative_thinking(category):
103
+ return (
104
+ f"1. **Analyzing the request**\n"
105
+ f"The user asks me to locate the {category} in this image.\n"
106
+ f"2. **Object grounding**\n"
107
+ f"After carefully scanning the entire image, I do not see any {category} present.\n"
108
+ f"3. **Conclusion**\n"
109
+ f"There is no {category} in this image."
110
+ )
111
+
112
+
113
+ def build_negative_answer(category):
114
+ return f"There is no {category} in the image."
115
+
116
+
117
+ def main():
118
+ parser = argparse.ArgumentParser()
119
+ parser.add_argument("--coco_jsonl", type=str, default="data/pretrain/grounding.jsonl")
120
+ parser.add_argument("--image_root", type=str, default="data/coco/val")
121
+ parser.add_argument("--output", type=str, default="data/sft/grounding/sft_grounding.jsonl")
122
+ parser.add_argument("--neg_ratio", type=float, default=0.30)
123
+ parser.add_argument("--max_samples", type=int, default=10000)
124
+ args = parser.parse_args()
125
+
126
+ out_path = Path(args.output)
127
+ out_path.parent.mkdir(parents=True, exist_ok=True)
128
+
129
+ # Load all positive samples
130
+ print("Loading COCO grounding data...")
131
+ all_samples = []
132
+ with open(args.coco_jsonl, "r", encoding="utf-8") as f:
133
+ for line in f:
134
+ item = json.loads(line.strip())
135
+ img_rel = item.get("image", "")
136
+ label_raw = item.get("label", 0)
137
+ try:
138
+ label_id = int(label_raw)
139
+ category = COCO_CATS.get(label_id, f"object_{label_id}")
140
+ except (ValueError, TypeError):
141
+ # label is already a string (category name)
142
+ category = str(label_raw)
143
+ boxes = [tuple(b) for b in item.get("boxes", [])]
144
+ all_samples.append({
145
+ "image": img_rel,
146
+ "category": category,
147
+ "label_id": label_id,
148
+ "boxes": boxes,
149
+ })
150
+
151
+ # Group by image for negative sampling
152
+ img_to_labels = defaultdict(set)
153
+ for s in all_samples:
154
+ img_to_labels[s["image"]].add(s["label_id"])
155
+
156
+ # Build positive SFT samples
157
+ # Cap boxes at 8 per sample to keep sequence length manageable for 12G VRAM
158
+ MAX_BOXES_PER_SAMPLE = 8
159
+ positive_samples = []
160
+ for s in all_samples:
161
+ if not s["boxes"]:
162
+ continue
163
+ boxes = s["boxes"][:MAX_BOXES_PER_SAMPLE]
164
+ cat = s["category"]
165
+ plural = pluralize(cat)
166
+ question = random.choice(GROUNDING_TEMPLATES).format(category=cat, plural=plural)
167
+ positive_samples.append({
168
+ "image": s["image"],
169
+ "question": question,
170
+ "thinking": build_positive_thinking(cat, boxes),
171
+ "answer": build_positive_answer(cat, boxes),
172
+ "boxes": boxes,
173
+ "points": [],
174
+ })
175
+
176
+ # Build negative SFT samples
177
+ all_label_ids = list(COCO_CATS.keys())
178
+ img_list = list(img_to_labels.keys())
179
+ negative_samples = []
180
+ for img_rel in img_list:
181
+ present = img_to_labels[img_rel]
182
+ absent = [lid for lid in all_label_ids if lid not in present]
183
+ if absent:
184
+ # Sample 1-2 negative categories per image
185
+ n_neg = min(2, len(absent))
186
+ for neg_label in random.sample(absent, n_neg):
187
+ category = COCO_CATS[neg_label]
188
+ plural = pluralize(category)
189
+ question = random.choice(GROUNDING_TEMPLATES).format(category=category, plural=plural)
190
+ negative_samples.append({
191
+ "image": img_rel,
192
+ "question": question,
193
+ "thinking": build_negative_thinking(category),
194
+ "answer": build_negative_answer(category),
195
+ "boxes": [],
196
+ "points": [],
197
+ })
198
+
199
+ # Shuffle and sample
200
+ random.shuffle(positive_samples)
201
+ random.shuffle(negative_samples)
202
+
203
+ # Determine counts based on neg_ratio
204
+ n_pos_target = int(args.max_samples * (1 - args.neg_ratio))
205
+ n_neg_target = int(args.max_samples * args.neg_ratio)
206
+
207
+ pos_selected = positive_samples[:n_pos_target]
208
+ neg_selected = negative_samples[:n_neg_target]
209
+
210
+ # Combine and shuffle
211
+ combined = pos_selected + neg_selected
212
+ random.shuffle(combined)
213
+
214
+ # Write output
215
+ with open(out_path, "w", encoding="utf-8") as f:
216
+ for item in combined:
217
+ f.write(json.dumps(item, ensure_ascii=False) + "\n")
218
+
219
+ print(f"Generated {len(combined)} SFT samples:")
220
+ print(f" Positive: {len(pos_selected)}")
221
+ print(f" Negative: {len(neg_selected)}")
222
+ print(f" Saved to: {out_path}")
223
+
224
+
225
+ if __name__ == "__main__":
226
+ main()