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