File size: 14,138 Bytes
2b8876a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
"""
Dataset loader for LucasFang/FLUX-Reason-6M.

This adapter converts the FLUX-Reason-6M dataset format into our step-level
chain-of-thought ReasoningChain format with proper step annotations.
"""

import json
import re
from typing import List, Dict, Optional, Any, Union
from pathlib import Path
import torch
from torch.utils.data import Dataset
from datasets import load_dataset
from PIL import Image
import io

from .step_data import (
    ReasoningChain,
    ReasoningStep,
    StepType,
    SPECIAL_TOKENS,
)


class FLUXReasonDataset(Dataset):
    """
    Dataset adapter for FLUX-Reason-6M that converts reasoning annotations
    into step-level chain-of-thought format.
    
    The FLUX-Reason-6M dataset contains images with reasoning chains. This adapter
    parses the reasoning text and creates structured ReasoningStep objects.
    """
    
    def __init__(
        self,
        dataset_name: str = "LucasFang/FLUX-Reason-6M",
        split: str = "train",
        streaming: bool = True,
        max_samples: Optional[int] = None,
        image_key: str = "image",
        reasoning_key: str = "reasoning",
        question_key: str = "question",
        answer_key: str = "answer",
        cache_dir: Optional[str] = None,
    ):
        """
        Initialize FLUX-Reason-6M dataset adapter.
        
        Args:
            dataset_name: HuggingFace dataset identifier
            split: Dataset split (train, validation, test)
            streaming: Use streaming mode for large datasets
            max_samples: Maximum number of samples to load (None = all)
            image_key: Column name for images
            reasoning_key: Column name for reasoning text
            question_key: Column name for questions
            answer_key: Column name for final answers
            cache_dir: Directory to cache downloaded data
        """
        self.dataset_name = dataset_name
        self.split = split
        self.streaming = streaming
        self.max_samples = max_samples
        self.image_key = image_key
        self.reasoning_key = reasoning_key
        self.question_key = question_key
        self.answer_key = answer_key
        
        print(f"Loading {dataset_name} ({split} split)...")
        
        # Load dataset from HuggingFace
        try:
            if streaming:
                self.hf_dataset = load_dataset(
                    dataset_name,
                    split=split,
                    streaming=True,
                    cache_dir=cache_dir,
                )
                self.hf_dataset_iter = iter(self.hf_dataset)
            else:
                self.hf_dataset = load_dataset(
                    dataset_name,
                    split=split,
                    cache_dir=cache_dir,
                )
                if max_samples:
                    self.hf_dataset = self.hf_dataset.select(range(min(max_samples, len(self.hf_dataset))))
        except Exception as e:
            raise RuntimeError(f"Failed to load dataset {dataset_name}: {e}")
        
        # Pre-build reasoning chains for non-streaming mode
        if not streaming:
            print("Converting to ReasoningChain format...")
            self.reasoning_chains = []
            for idx, sample in enumerate(self.hf_dataset):
                chain = self._parse_sample_to_chain(sample, idx)
                if chain:
                    self.reasoning_chains.append(chain)
            print(f"Loaded {len(self.reasoning_chains)} reasoning chains")
        else:
            self.reasoning_chains = None
    
    def __len__(self) -> int:
        if self.streaming:
            return self.max_samples or 10**9  # Large number for streaming
        return len(self.reasoning_chains)
    
    def __getitem__(self, idx: int) -> Optional[ReasoningChain]:
        """Get a reasoning chain by index."""
        if self.streaming:
            # For streaming, get next item from iterator
            try:
                sample = next(self.hf_dataset_iter)
            except StopIteration:
                self.hf_dataset_iter = iter(self.hf_dataset)
                sample = next(self.hf_dataset_iter)
            return self._parse_sample_to_chain(sample, idx)
        else:
            return self.reasoning_chains[idx]
    
    def _parse_sample_to_chain(self, sample: Dict[str, Any], idx: int) -> Optional[ReasoningChain]:
        """
        Parse a FLUX-Reason-6M sample into a ReasoningChain.
        
        Args:
            sample: Raw sample from HuggingFace dataset
            idx: Sample index
            
        Returns:
            ReasoningChain object or None if parsing fails
        """
        try:
            # Extract fields
            image = sample.get(self.image_key)
            reasoning_text = sample.get(self.reasoning_key, "")
            question = sample.get(self.question_key, "")
            answer = sample.get(self.answer_key, "")
            
            # Convert image to PIL if needed
            if isinstance(image, bytes):
                image = Image.open(io.BytesIO(image)).convert('RGB')
            elif hasattr(image, 'convert'):
                image = image.convert('RGB')
            
            # Parse reasoning text into steps
            steps = self._parse_reasoning_steps(reasoning_text)
            
            if not steps:
                # If no steps found, create a single inference step
                steps = [
                    ReasoningStep(
                        step_id=0,
                        step_type=StepType.INFERENCE,
                        description=reasoning_text if reasoning_text else "Direct inference",
                        confidence=0.8,
                    )
                ]
            
            # Create reasoning chain
            chain = ReasoningChain(
                chain_id=f"flux_reason_{idx}",
                image_path=None,  # Streaming mode, no path
                image=image,
                prompt=question,
                steps=steps,
                final_answer=answer,
                is_correct=True,  # Assume dataset contains correct reasoning
                metadata={
                    "dataset": self.dataset_name,
                    "split": self.split,
                    "original_idx": idx,
                }
            )
            
            return chain
            
        except Exception as e:
            print(f"Warning: Failed to parse sample {idx}: {e}")
            return None
    
    def _parse_reasoning_steps(self, reasoning_text: str) -> List[ReasoningStep]:
        """
        Parse reasoning text into structured ReasoningStep objects.
        
        This handles various reasoning formats:
        - Numbered steps: "1. ...", "2. ...", etc.
        - Step markers: "Step 1:", "Step 2:", etc.
        - Natural paragraphs separated by newlines
        
        Args:
            reasoning_text: Raw reasoning text from dataset
            
        Returns:
            List of ReasoningStep objects
        """
        if not reasoning_text or not reasoning_text.strip():
            return []
        
        steps = []
        
        # Try to split by numbered patterns
        # Pattern 1: "1. ", "2. ", etc.
        numbered_pattern = r'(\d+)\.\s+'
        # Pattern 2: "Step 1:", "Step 2:", etc.
        step_pattern = r'[Ss]tep\s+(\d+):\s*'
        
        # Try numbered pattern first
        parts = re.split(numbered_pattern, reasoning_text)
        if len(parts) > 2:  # Found numbered steps
            for i in range(1, len(parts), 2):
                if i + 1 < len(parts):
                    step_num = int(parts[i]) - 1
                    step_text = parts[i + 1].strip()
                    if step_text:
                        steps.append(self._create_step_from_text(step_num, step_text))
        else:
            # Try step pattern
            parts = re.split(step_pattern, reasoning_text, flags=re.IGNORECASE)
            if len(parts) > 2:  # Found "Step X:" format
                for i in range(1, len(parts), 2):
                    if i + 1 < len(parts):
                        step_num = int(parts[i]) - 1
                        step_text = parts[i + 1].strip()
                        if step_text:
                            steps.append(self._create_step_from_text(step_num, step_text))
            else:
                # Fall back to splitting by double newlines (paragraphs)
                paragraphs = [p.strip() for p in reasoning_text.split('\n\n') if p.strip()]
                if len(paragraphs) > 1:
                    for idx, paragraph in enumerate(paragraphs):
                        steps.append(self._create_step_from_text(idx, paragraph))
                else:
                    # Split by single newlines if no paragraphs
                    lines = [l.strip() for l in reasoning_text.split('\n') if l.strip()]
                    if len(lines) > 1:
                        for idx, line in enumerate(lines):
                            steps.append(self._create_step_from_text(idx, line))
                    else:
                        # Single line reasoning - create one step
                        steps.append(self._create_step_from_text(0, reasoning_text.strip()))
        
        return steps
    
    def _create_step_from_text(self, step_id: int, text: str) -> ReasoningStep:
        """
        Create a ReasoningStep from text, inferring the step type from keywords.
        
        Args:
            step_id: Step index
            text: Step description text
            
        Returns:
            ReasoningStep object
        """
        # Infer step type from keywords in text
        text_lower = text.lower()
        
        if any(kw in text_lower for kw in ['see', 'observe', 'notice', 'image shows', 'picture']):
            step_type = StepType.PERCEPTION
        elif any(kw in text_lower for kw in ['located', 'position', 'where', 'left', 'right', 'top', 'bottom']):
            step_type = StepType.LOCALIZATION
        elif any(kw in text_lower for kw in ['compare', 'larger', 'smaller', 'bigger', 'different', 'similar']):
            step_type = StepType.COMPARISON
        elif any(kw in text_lower for kw in ['count', 'number', 'how many', 'total', 'sum']):
            step_type = StepType.COUNTING
        elif any(kw in text_lower for kw in ['therefore', 'thus', 'conclude', 'deduce', 'infer']):
            step_type = StepType.INFERENCE
        elif any(kw in text_lower for kw in ['combine', 'together', 'overall', 'compose']):
            step_type = StepType.COMPOSITION
        elif any(kw in text_lower for kw in ['check', 'verify', 'confirm', 'validate']):
            step_type = StepType.VERIFICATION
        else:
            step_type = StepType.INFERENCE  # Default
        
        # Create step with inferred type
        return ReasoningStep(
            step_id=step_id,
            step_type=step_type,
            description=text,
            confidence=0.85,  # Default confidence for dataset samples
            dependencies=list(range(step_id)) if step_id > 0 else [],  # Depends on all previous steps
        )


def create_flux_reason_dataloader(
    tokenizer: Any,
    batch_size: int = 4,
    num_workers: int = 4,
    streaming: bool = True,
    max_samples: Optional[int] = None,
    **kwargs
) -> torch.utils.data.DataLoader:
    """
    Create a DataLoader for FLUX-Reason-6M dataset.
    
    Args:
        tokenizer: Tokenizer for text encoding
        batch_size: Number of samples per batch
        num_workers: Number of worker processes
        streaming: Use streaming mode
        max_samples: Maximum samples to load
        **kwargs: Additional arguments for FLUXReasonDataset
        
    Returns:
        Configured DataLoader
    """
    from .step_data import StepDataset
    
    # Create FLUX dataset
    flux_dataset = FLUXReasonDataset(
        streaming=streaming,
        max_samples=max_samples,
        **kwargs
    )
    
    # If not streaming, wrap in StepDataset for tokenization
    if not streaming and flux_dataset.reasoning_chains:
        step_dataset = StepDataset(
            reasoning_chains=flux_dataset.reasoning_chains,
            tokenizer=tokenizer,
            max_steps=10,
            include_visual_features=False,  # FLUX dataset doesn't have pre-extracted features
            filter_incorrect=False,
        )
        
        return torch.utils.data.DataLoader(
            step_dataset,
            batch_size=batch_size,
            num_workers=num_workers,
            shuffle=True,
            collate_fn=lambda batch: batch,  # Custom collation handled in trainer
        )
    else:
        # For streaming, return raw flux dataset
        # (trainer will handle tokenization on-the-fly)
        return torch.utils.data.DataLoader(
            flux_dataset,
            batch_size=batch_size,
            num_workers=0 if streaming else num_workers,  # Streaming doesn't support multiprocessing well
            shuffle=False,  # Streaming mode doesn't support shuffle
        )


# Example usage
if __name__ == "__main__":
    # Test dataset loading
    print("Testing FLUX-Reason-6M dataset adapter...")
    
    dataset = FLUXReasonDataset(
        streaming=False,
        max_samples=10,
    )
    
    print(f"\nLoaded {len(dataset)} samples")
    
    # Show first example
    if len(dataset) > 0:
        chain = dataset[0]
        print(f"\n{'='*60}")
        print("Example Reasoning Chain:")
        print(f"{'='*60}")
        print(f"Chain ID: {chain.chain_id}")
        print(f"Prompt: {chain.prompt}")
        print(f"Number of steps: {len(chain.steps)}")
        print(f"\nSteps:")
        for step in chain.steps:
            print(f"  Step {step.step_id} ({step.step_type.value}): {step.description[:100]}...")
        print(f"\nFinal Answer: {chain.final_answer}")
        print(f"\n{'='*60}")
        print("\nFormatted with special tokens:")
        print(f"{'='*60}")
        formatted = chain.format_with_tokens()
        print(formatted[:500] + "..." if len(formatted) > 500 else formatted)