File size: 11,202 Bytes
cfb5e7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Human feedback loop for active learning.

Manages the cycle of:
1. Model prediction
2. Uncertainty sampling
3. Human annotation
4. Model retraining
"""

import json
import logging
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple

import pandas as pd

logger = logging.getLogger(__name__)


@dataclass
class FeedbackRecord:
    """Record of human feedback for a sample."""
    sample_id: str
    text: str
    original_prediction: str
    human_label: str
    confidence_feedback: float  # 0-1, did model seem confident?
    notes: str = ""
    timestamp: str = ""
    
    def to_dict(self) -> Dict:
        return {
            "sample_id": self.sample_id,
            "text": self.text,
            "original_prediction": self.original_prediction,
            "human_label": self.human_label,
            "confidence_feedback": self.confidence_feedback,
            "notes": self.notes,
            "timestamp": self.timestamp or datetime.now().isoformat(),
        }


@dataclass
class FeedbackLoopConfig:
    """Configuration for feedback loop."""
    min_feedback_samples: int = 50
    max_feedback_samples: int = 500
    retrain_threshold: int = 100  # Retrain after this many new samples
    disagreement_threshold: float = 0.3  # Retrain if disagreement rate > this
    batch_size: int = 32
    
    
@dataclass 
class LoopState:
    """State of the feedback loop."""
    iteration: int = 0
    total_annotated: int = 0
    total_retrained: int = 0
    disagreement_rate: float = 0.0
    model_performance: Dict = field(default_factory=dict)
    history: List[Dict] = field(default_factory=list)


class HumanFeedbackLoop:
    """Manages the human-in-the-loop training cycle."""
    
    def __init__(
        self,
        config: Optional[FeedbackLoopConfig] = None,
        output_dir: str = "outputs/active_learning",
    ):
        self.config = config or FeedbackLoopConfig()
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        
        self.state = LoopState()
        self.feedback_records: List[FeedbackRecord] = []
        self.labeled_samples: List[Dict] = []
        
    def add_feedback(
        self,
        sample_id: str,
        text: str,
        original_prediction: str,
        human_label: str,
        confidence_feedback: float = 0.5,
        notes: str = "",
    ) -> None:
        """Add human feedback for a sample."""
        record = FeedbackRecord(
            sample_id=sample_id,
            text=text,
            original_prediction=original_prediction,
            human_label=human_label,
            confidence_feedback=confidence_feedback,
            notes=notes,
            timestamp=datetime.now().isoformat(),
        )
        
        self.feedback_records.append(record)
        
        # Add to labeled samples
        self.labeled_samples.append({
            "id": sample_id,
            "text": text,
            "label": human_label,
            "source": "human_feedback",
        })
        
        self.state.total_annotated += 1
        
        logger.info(
            f"Added feedback for {sample_id}: "
            f"{original_prediction} -> {human_label}"
        )
    
    def batch_add_feedback(
        self,
        feedback_list: List[Dict],
    ) -> None:
        """Add multiple feedback records at once."""
        for fb in feedback_list:
            self.add_feedback(
                sample_id=fb.get("sample_id", fb.get("id")),
                text=fb.get("text", ""),
                original_prediction=fb.get("original_prediction", "unknown"),
                human_label=fb.get("human_label", fb.get("label")),
                confidence_feedback=fb.get("confidence_feedback", 0.5),
                notes=fb.get("notes", ""),
            )
    
    def should_retrain(self) -> Tuple[bool, str]:
        """Check if model should be retrained.
        
        Returns:
            (should_retrain, reason)
        """
        n_new = len(self.feedback_records)
        
        # Check minimum samples
        if n_new < self.config.min_feedback_samples:
            return False, f"Only {n_new} samples (min: {self.config.min_feedback_samples})"
        
        # Check retrain threshold
        if n_new >= self.config.retrain_threshold:
            self._calculate_disagreement_rate()
            if self.state.disagreement_rate > self.config.disagreement_threshold:
                return True, f"High disagreement ({self.state.disagreement_rate:.1%})"
            return True, f"Reached {n_new} samples threshold"
        
        return False, f"Not enough samples: {n_new}"
    
    def _calculate_disagreement_rate(self) -> float:
        """Calculate disagreement rate between model and human."""
        if not self.feedback_records:
            self.state.disagreement_rate = 0.0
            return 0.0
        
        disagreements = sum(
            1 for r in self.feedback_records
            if r.original_prediction != r.human_label
        )
        
        self.state.disagreement_rate = disagreements / len(self.feedback_records)
        return self.state.disagreement_rate
    
    def get_training_data(
        self,
        include_previous: bool = True,
    ) -> List[Dict]:
        """Get accumulated training data.
        
        Args:
            include_previous: Include previously retrained data
        
        Returns:
            List of samples with labels
        """
        if include_previous:
            return self.labeled_samples
        else:
            # Only return new samples since last retrain
            return self.labeled_samples[-self.config.retrain_threshold:]
    
    def export_training_data(
        self,
        path: Optional[str] = None,
        format: str = "jsonl",
    ) -> str:
        """Export training data to file."""
        if path is None:
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            path = self.output_dir / f"training_data_{timestamp}.{format}"
        
        if format == "jsonl":
            with open(path, "w", encoding="utf-8") as f:
                for sample in self.labeled_samples:
                    f.write(json.dumps(sample, ensure_ascii=False) + "\n")
        elif format == "csv":
            df = pd.DataFrame(self.labeled_samples)
            df.to_csv(path, index=False)
        
        logger.info(f"Exported {len(self.labeled_samples)} samples to {path}")
        return str(path)
    
    def mark_retrained(self, performance: Optional[Dict] = None) -> None:
        """Mark that retraining has occurred."""
        self.state.iteration += 1
        self.state.total_retrained += 1
        
        if performance:
            self.state.model_performance = performance
        
        # Record history
        self.history.append({
            "iteration": self.state.iteration,
            "timestamp": datetime.now().isoformat(),
            "total_annotated": self.state.total_annotated,
            "disagreement_rate": self.state.disagreement_rate,
            "performance": performance,
        })
        
        logger.info(
            f"Model retrained (iteration {self.state.iteration}). "
            f"Total annotated: {self.state.total_annotated}"
        )
    
    def get_statistics(self) -> Dict[str, Any]:
        """Get loop statistics."""
        return {
            "iteration": self.state.iteration,
            "total_annotated": self.state.total_annotated,
            "total_retrained": self.state.total_retrained,
            "disagreement_rate": self.state.disagreement_rate,
            "should_retrain": self.should_retrain()[0],
            "pending_samples": len(self.feedback_records),
            "recent_history": self.history[-5:] if self.history else [],
        }
    
    def get_label_distribution(self) -> Dict[str, int]:
        """Get distribution of labels."""
        from collections import Counter
        labels = [r.human_label for r in self.feedback_records]
        return dict(Counter(labels))
    
    def analyze_errors(self) -> Dict[str, Any]:
        """Analyze patterns in model errors."""
        errors = [
            r for r in self.feedback_records
            if r.original_prediction != r.human_label
        ]
        
        if not errors:
            return {"total_errors": 0}
        
        # Group by confusion pairs
        confusion_pairs = {}
        for e in errors:
            pair = (e.original_prediction, e.human_label)
            confusion_pairs[pair] = confusion_pairs.get(pair, 0) + 1
        
        return {
            "total_errors": len(errors),
            "error_rate": len(errors) / len(self.feedback_records),
            "confusion_matrix": confusion_pairs,
            "most_common_error": max(
                confusion_pairs.items(),
                key=lambda x: x[1]
            ) if confusion_pairs else None,
        }
    
    def save_state(self, path: Optional[str] = None) -> str:
        """Save loop state to file."""
        if path is None:
            path = self.output_dir / "loop_state.json"
        
        state_data = {
            "config": {
                "min_feedback_samples": self.config.min_feedback_samples,
                "max_feedback_samples": self.config.max_feedback_samples,
                "retrain_threshold": self.config.retrain_threshold,
                "disagreement_threshold": self.config.disagreement_threshold,
            },
            "state": {
                "iteration": self.state.iteration,
                "total_annotated": self.state.total_annotated,
                "total_retrained": self.state.total_retrained,
                "disagreement_rate": self.state.disagreement_rate,
            },
            "history": self.history,
        }
        
        with open(path, "w", encoding="utf-8") as f:
            json.dump(state_data, f, indent=2)
        
        return str(path)
    
    def load_state(self, path: str) -> None:
        """Load loop state from file."""
        with open(path, "r", encoding="utf-8") as f:
            state_data = json.load(f)
        
        config_dict = state_data.get("config", {})
        self.config = FeedbackLoopConfig(**config_dict)
        
        state_dict = state_data.get("state", {})
        self.state = LoopState(**state_dict)
        
        self.history = state_data.get("history", [])


def create_feedback_loop(
    config: Optional[Dict] = None,
) -> HumanFeedbackLoop:
    """Factory function to create feedback loop."""
    loop_config = None
    if config:
        loop_config = FeedbackLoopConfig(**config)
    
    return HumanFeedbackLoop(config=loop_config)


if __name__ == "__main__":
    loop = create_feedback_loop()
    
    # Simulate feedback
    loop.add_feedback(
        sample_id="utt_001",
        text="ကျေးဇူးပါ",
        original_prediction="positive",
        human_label="sarcastic",
        notes="Voice tone suggests complaint",
    )
    
    print(f"Should retrain: {loop.should_retrain()}")
    print(f"Stats: {loop.get_statistics()}")