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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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
from __future__ import annotations

"""Enhanced PK Sampler with guaranteed cross-device sampling and hard negative mining.

PKSamplerV3 addresses limitations of the original PKSampler:
    - Guarantees cross-device positives (when available)
    - Filters identities with insufficient samples
    - Robust fallback strategies for edge cases
    - Better hard negative mining through label diversity
"""

import random
from collections import defaultdict

from torch.utils.data import Sampler

from .image_dataset import ImageDataset, ImageListDataset


class PKSamplerV3(Sampler):
    """Enhanced PK sampler for metric learning with cross-device guarantees.

    Samples P identities × K samples per batch, with special handling for:
        - Cross-device sampling: Ensures samples from different devices within each identity
        - Hard negatives: Maximizes label diversity across batches
        - Quality filtering: Only uses identities with sufficient samples

    Parameters
    ----------
    dataset : ImageDataset
        The fingerprint dataset.
    p : int
        Number of identities per batch (P).
    k : int
        Number of samples per identity (K).
    ensure_cross_device : bool
        If True, prioritize sampling from different devices within each identity.
    min_devices_per_identity : int
        Minimum number of distinct devices required for an identity to be viable
        when ensure_cross_device=True.
    hard_negative_ratio : float
        Currently unused. Reserved for future hard negative mining based on
        pre-computed similarity matrix.

    Notes
    -----
    Batch size = P × K (e.g., 8 identities × 4 samples = 32).
    """

    def __init__(
        self,
        dataset: ImageDataset,
        p: int = 8,
        k: int = 4,
        ensure_cross_device: bool = True,
        min_devices_per_identity: int = 2,
        hard_negative_ratio: float = 0.5,
    ):
        self.p = p
        self.k = k
        self.ensure_cross_device = ensure_cross_device
        self.min_devices_per_identity = min_devices_per_identity
        self.hard_negative_ratio = hard_negative_ratio

        # Build index structures
        self.label_to_indices: dict[int, list[int]] = defaultdict(list)
        self.label_to_device_indices: dict[int, dict[str | None, list[int]]] = (
            defaultdict(lambda: defaultdict(list))
        )

        for idx, label in enumerate(dataset.labels):
            self.label_to_indices[label].append(idx)
            device = dataset.devices[idx]
            self.label_to_device_indices[label][device].append(idx)

        # Filter viable labels based on cross-device requirements
        if ensure_cross_device:
            self.viable_labels = self._filter_viable_labels_cross_device()
        else:
            self.viable_labels = self._filter_viable_labels_basic()

        if len(self.viable_labels) < p:
            print(
                f"⚠️  Warning: Only {len(self.viable_labels)} viable labels with "
                f"cross-device requirement (need {p}). Relaxing constraints..."
            )
            # Fallback: Use all labels with at least k samples
            self.viable_labels = [
                lbl
                for lbl, indices in self.label_to_indices.items()
                if len(indices) >= k
            ]

        if len(self.viable_labels) < p:
            print(
                f"⚠️  Critical: Only {len(self.viable_labels)} labels with ≥{k} samples. "
                f"Using all available labels."
            )
            self.viable_labels = list(self.label_to_indices.keys())

        # Compute number of batches
        total_samples = sum(
            len(self.label_to_indices[lbl]) for lbl in self.viable_labels
        )
        self._len = max(1, total_samples // (p * k))

        print(
            f"PKSamplerV3: {len(self.viable_labels)} viable labels, "
            f"{self._len} batches per epoch (P={p}, K={k})"
        )

    # ------------------------------------------------------------------
    def _filter_viable_labels_cross_device(self) -> list[int]:
        """Filter labels that have sufficient cross-device samples."""
        viable: list[int] = []

        for label, dev_dict in self.label_to_device_indices.items():
            # Count distinct non-None devices
            distinct_devices = [dev for dev in dev_dict if dev is not None]
            num_devices = len(distinct_devices)

            # Check total samples
            total_samples = sum(len(indices) for indices in dev_dict.values())

            if num_devices >= self.min_devices_per_identity and total_samples >= self.k:
                viable.append(label)

        return viable

    # ------------------------------------------------------------------
    def _filter_viable_labels_basic(self) -> list[int]:
        """Filter labels with at least K samples."""
        return [
            lbl
            for lbl, indices in self.label_to_indices.items()
            if len(indices) >= self.k
        ]

    # ------------------------------------------------------------------
    def _sample_cross_device_indices(self, label: int) -> list[int]:
        """Sample K indices ensuring cross-device diversity.

        Strategy:
            1. Identify available devices for this identity
            2. Distribute K samples across devices as evenly as possible
            3. Fill remaining with random samples if needed

        Args:
            label: Identity label to sample from.

        Returns:
            List of K sample indices.
        """
        by_device = self.label_to_device_indices[label]
        devices = [
            dev for dev in by_device if dev is not None and len(by_device[dev]) > 0
        ]

        # Fallback: Not enough devices, use random sampling
        if len(devices) < 2:
            indices = self.label_to_indices[label]
            if len(indices) >= self.k:
                return random.sample(indices, self.k)
            else:
                return random.choices(indices, k=self.k)

        # Strategy: Distribute K samples across devices
        chosen: list[int] = []
        devices_shuffled = devices.copy()
        random.shuffle(devices_shuffled)

        # Compute samples per device
        k_per_device = max(1, self.k // len(devices))

        for dev in devices_shuffled:
            if len(chosen) >= self.k:
                break

            available = by_device[dev]
            n_sample = min(k_per_device, len(available), self.k - len(chosen))

            if n_sample > 0:
                sampled = (
                    random.sample(available, n_sample)
                    if len(available) >= n_sample
                    else available
                )
                chosen.extend(sampled)

        # Fill remaining slots
        if len(chosen) < self.k:
            remaining_pool = [
                idx for idx in self.label_to_indices[label] if idx not in chosen
            ]
            needed = self.k - len(chosen)

            if len(remaining_pool) >= needed:
                chosen.extend(random.sample(remaining_pool, needed))
            else:
                # Last resort: Add all remaining + duplicate from existing
                chosen.extend(remaining_pool)
                while len(chosen) < self.k:
                    chosen.append(random.choice(self.label_to_indices[label]))

        return chosen[: self.k]

    # ------------------------------------------------------------------
    def _sample_basic_indices(self, label: int) -> list[int]:
        """Sample K indices without device constraints."""
        indices = self.label_to_indices[label]

        if len(indices) >= self.k:
            return random.sample(indices, self.k)
        else:
            return random.choices(indices, k=self.k)

    # ------------------------------------------------------------------
    def _create_batch(self) -> list[int]:
        """Create one batch with P identities × K samples.

        Returns:
            List of sample indices for this batch.
        """
        # Randomly select P identities
        if len(self.viable_labels) >= self.p:
            batch_labels = random.sample(self.viable_labels, self.p)
        else:
            # Sample with replacement if not enough labels
            batch_labels = random.choices(self.viable_labels, k=self.p)

        # Sample K indices per identity
        batch: list[int] = []
        for label in batch_labels:
            if self.ensure_cross_device:
                indices = self._sample_cross_device_indices(label)
            else:
                indices = self._sample_basic_indices(label)
            batch.extend(indices)

        return batch

    # ------------------------------------------------------------------
    def __iter__(self):
        """Yield batches for one epoch."""
        for _ in range(self._len):
            yield self._create_batch()

    def __len__(self) -> int:
        return self._len


class ContinualReplayPKSampler(Sampler):
    """PK sampler that mixes current-stage labels with replay labels per batch.

    The combined dataset is expected to contain:
        1. Current-stage samples in the range ``[0, current_size)``
        2. Replay exemplar samples in the range ``[current_size, len(dataset))``

    Each batch draws ``current_p`` identities from the new stage and
    ``replay_p`` identities from replay memory, which reduces abrupt domain
    shift between stages and gives old identities direct rehearsal batches.
    """

    def __init__(
        self,
        dataset: ImageDataset | ImageListDataset,
        current_size: int,
        p: int = 8,
        k: int = 4,
        replay_p: int = 2,
        ensure_cross_device: bool = True,
        min_devices_per_identity: int = 2,
    ):
        self.dataset = dataset
        self.current_size = max(0, int(current_size))
        self.p = int(p)
        self.k = int(k)
        self.ensure_cross_device = ensure_cross_device
        self.min_devices_per_identity = min_devices_per_identity

        replay_size = max(0, len(dataset.samples) - self.current_size)
        if replay_size <= 0:
            replay_p = 0

        replay_p = max(0, min(int(replay_p), self.p - 1))
        self.replay_p = replay_p
        self.current_p = self.p - self.replay_p

        self.current_label_to_indices: dict[int, list[int]] = defaultdict(list)
        self.current_label_to_device_indices: dict[int, dict[str | None, list[int]]] = (
            defaultdict(lambda: defaultdict(list))
        )
        self.replay_label_to_indices: dict[int, list[int]] = defaultdict(list)
        self.replay_label_to_device_indices: dict[int, dict[str | None, list[int]]] = (
            defaultdict(lambda: defaultdict(list))
        )

        for idx, label in enumerate(dataset.labels[: self.current_size]):
            self.current_label_to_indices[label].append(idx)
            device = dataset.devices[idx]
            self.current_label_to_device_indices[label][device].append(idx)

        for idx, label in enumerate(
            dataset.labels[self.current_size :], start=self.current_size
        ):
            self.replay_label_to_indices[label].append(idx)
            device = dataset.devices[idx]
            self.replay_label_to_device_indices[label][device].append(idx)

        self.current_labels = self._filter_viable_labels(
            self.current_label_to_indices,
            self.current_label_to_device_indices,
        )
        self.replay_labels = self._filter_viable_labels(
            self.replay_label_to_indices,
            self.replay_label_to_device_indices,
        )

        if len(self.current_labels) == 0:
            raise ValueError(
                "ContinualReplayPKSampler requires at least one current-stage label"
            )

        if len(self.replay_labels) == 0:
            self.replay_p = 0
            self.current_p = self.p

        total_current_samples = sum(
            len(self.current_label_to_indices[label]) for label in self.current_labels
        )
        self._len = max(1, total_current_samples // max(1, self.current_p * self.k))

        print(
            f"ContinualReplayPKSampler: current_labels={len(self.current_labels)} "
            f"replay_labels={len(self.replay_labels)} current_p={self.current_p} "
            f"replay_p={self.replay_p} batches={self._len}"
        )

    def _filter_viable_labels(
        self,
        label_to_indices: dict[int, list[int]],
        label_to_device_indices: dict[int, dict[str | None, list[int]]],
    ) -> list[int]:
        viable: list[int] = []
        for label, indices in label_to_indices.items():
            if len(indices) < self.k:
                continue
            if not self.ensure_cross_device:
                viable.append(label)
                continue

            distinct_devices = [
                device
                for device, device_indices in label_to_device_indices[label].items()
                if device is not None and len(device_indices) > 0
            ]
            if len(distinct_devices) >= self.min_devices_per_identity:
                viable.append(label)

        if viable:
            return viable

        return [
            label
            for label, indices in label_to_indices.items()
            if len(indices) >= self.k
        ] or list(label_to_indices.keys())

    def _sample_indices(
        self,
        label: int,
        label_to_indices: dict[int, list[int]],
        label_to_device_indices: dict[int, dict[str | None, list[int]]],
    ) -> list[int]:
        indices = label_to_indices[label]
        if not self.ensure_cross_device:
            return (
                random.sample(indices, self.k)
                if len(indices) >= self.k
                else random.choices(indices, k=self.k)
            )

        by_device = label_to_device_indices[label]
        devices = [
            device
            for device in by_device
            if device is not None and len(by_device[device]) > 0
        ]
        if len(devices) < self.min_devices_per_identity:
            return (
                random.sample(indices, self.k)
                if len(indices) >= self.k
                else random.choices(indices, k=self.k)
            )

        chosen: list[int] = []
        devices_shuffled = devices.copy()
        random.shuffle(devices_shuffled)

        for device in devices_shuffled:
            if len(chosen) >= self.k:
                break
            chosen.append(random.choice(by_device[device]))

        remaining_pool = [idx for idx in indices if idx not in chosen]
        needed = self.k - len(chosen)
        if needed > 0:
            if len(remaining_pool) >= needed:
                chosen.extend(random.sample(remaining_pool, needed))
            else:
                chosen.extend(remaining_pool)
                while len(chosen) < self.k:
                    chosen.append(random.choice(indices))

        return chosen[: self.k]

    def _sample_labels(self, labels: list[int], n_labels: int) -> list[int]:
        if n_labels <= 0:
            return []
        if len(labels) >= n_labels:
            return random.sample(labels, n_labels)
        return random.choices(labels, k=n_labels)

    def __iter__(self):
        for _ in range(self._len):
            batch: list[int] = []

            for label in self._sample_labels(self.current_labels, self.current_p):
                batch.extend(
                    self._sample_indices(
                        label,
                        self.current_label_to_indices,
                        self.current_label_to_device_indices,
                    )
                )

            for label in self._sample_labels(self.replay_labels, self.replay_p):
                batch.extend(
                    self._sample_indices(
                        label,
                        self.replay_label_to_indices,
                        self.replay_label_to_device_indices,
                    )
                )

            yield batch

    def __len__(self) -> int:
        return self._len