From bf877b3fc4964a3307182fda13dd885f4c8339d9 Mon Sep 17 00:00:00 2001 From: b-enedict Date: Tue, 1 Dec 2026 12:17:51 +0100 Subject: [PATCH 1/7] [MINOR] Add alignment operator registry and fix orb alignment Register alignment operators per modality combination and load them lazily like the other builtin operators. Rename " orb_alignment.py" (leading space) to orb_alignment.py and fix its constructor, matcher and descriptor handling. Alignment.apply_matching now tags matched metadata with the matching index and fills unmatched instances with a placeholder. Assisted-by: AI Co-Authored-By: Claude Opus 5.5 --- .../scuro/drsearch/operator_registry.py | 48 ++++++++++++ .../scuro/representations/alignment.py | 74 ++++++++++++++----- .../{ orb_alignment.py => orb_alignment.py} | 29 +++++++- .../scuro/representations/pHash_alignment.py | 7 ++ 4 files changed, 137 insertions(+), 21 deletions(-) rename src/main/python/systemds/scuro/representations/{ orb_alignment.py => orb_alignment.py} (60%) diff --git a/src/main/python/systemds/scuro/drsearch/operator_registry.py b/src/main/python/systemds/scuro/drsearch/operator_registry.py index f62d5192832..90b7b1dfa66 100644 --- a/src/main/python/systemds/scuro/drsearch/operator_registry.py +++ b/src/main/python/systemds/scuro/drsearch/operator_registry.py @@ -20,6 +20,7 @@ # ------------------------------------------------------------- from importlib import import_module from typing import Iterable, Union, List +from functools import reduce import math from systemds.scuro.modality.type import ModalityType from systemds.scuro.representations.representation import Representation @@ -84,6 +85,7 @@ "sum", ) _DIMENSIONALITY_REDUCTION_MODULES = ("mlp_averaging",) +_ALIGNMENT_MODULES = ("orb_alignment", "pHash_alignment") _OPTIONAL_MODULES = {"image_bind"} _loaded_builtin_modules = set() @@ -108,6 +110,14 @@ def load_builtin_operators( _loaded_builtin_modules.add(module_name) +def load_alignment_operators(): + for module_name in _ALIGNMENT_MODULES: + if module_name in _loaded_builtin_modules: + continue + import_module(f"systemds.scuro.representations.{module_name}") + _loaded_builtin_modules.add(module_name) + + class Registry: """ A registry for all representations per modality. @@ -122,6 +132,7 @@ class Registry: _context_representation_operators = {} _dimensionality_reduction_operators = {} _expensive_representations = {} + _alignment_operators = {} def __new__(cls): if not cls._instance: @@ -336,6 +347,30 @@ def _drop_windows_below_min_count(self, effective_window_lenghts, num_windows): def get_expensive_representations(self, modality: ModalityType): return self._expensive_representations[modality] + def add_alignment_operator(self, alignment_operator, modality_combination): + n_modalities = len(modality_combination) + combined_modality = reduce(lambda a, b: a | b, modality_combination) + + if n_modalities not in self._alignment_operators: + self._alignment_operators[n_modalities] = {} + + if combined_modality not in self._alignment_operators[n_modalities]: + self._alignment_operators[n_modalities][combined_modality] = [] + + self._alignment_operators[n_modalities][combined_modality].append( + alignment_operator + ) + + def get_alignment_operator(self, modality_combination: List[ModalityType]): + load_alignment_operators() + n_modalities = len(modality_combination) + combined_modality = reduce(lambda a, b: a | b, modality_combination) + + try: + return self._alignment_operators[n_modalities][combined_modality] + except KeyError: + return [] + def is_expensive_representation(representation: Representation): registry = Registry() @@ -430,3 +465,16 @@ def decorator(cls): return cls return decorator + + +def register_alignment_operator(*modality_combinations: List[ModalityType]): + """ + Decorator to register an alignment operator + """ + + def decorator(cls): + for combination in modality_combinations: + Registry().add_alignment_operator(cls, combination) + return cls + + return decorator diff --git a/src/main/python/systemds/scuro/representations/alignment.py b/src/main/python/systemds/scuro/representations/alignment.py index 42e6df0b205..5b1fdadaa8b 100644 --- a/src/main/python/systemds/scuro/representations/alignment.py +++ b/src/main/python/systemds/scuro/representations/alignment.py @@ -23,6 +23,8 @@ from collections import defaultdict import copy +import numpy as np + @dataclass class Match: @@ -31,16 +33,30 @@ class Match: distance: float +def _empty_like(reference): + """Type-appropriate 'no match found' placeholder, modeled on `reference` + (an existing data instance from the same modality) so it survives the + modality's metadata handlers (e.g. TEXT's `len(data)`) the same way a + real instance would.""" + if isinstance(reference, str): + return "" + if isinstance(reference, np.ndarray): + return np.zeros_like(reference) + if isinstance(reference, list): + return [] + return reference + + class Alignment(ABC): def __init__(self, name): self.name = name - def execute(self, primary_modality, secondary_modality): + def execute(self, fixated_modality, aligned_modality): primary_descriptor_collections = self._batch_compute_descriptors( - primary_modality + fixated_modality ) secondary_descriptor_collections = self._batch_compute_descriptors( - secondary_modality + aligned_modality ) matches = [] @@ -95,18 +111,42 @@ def execute(self, primary_modality, secondary_modality): return matches @staticmethod - def apply_matching(alignment, secondary_modality): - aligned_modality = copy.deepcopy(secondary_modality) - aligned_modality.data = [None] * len(alignment) - aligned_modality.metadata = [None] * len(alignment) - - for match in alignment: - aligned_modality.data[match.primary] = secondary_modality.data[ - match.secondary - ] - aligned_modality.metadata[match.primary] = secondary_modality.metadata[ - match.secondary - ] + def apply_matching(matching, aligned_modality): + aligned_modality = copy.deepcopy(aligned_modality) + original_data = aligned_modality.data + original_metadata = aligned_modality.metadata + + new_data = [None] * len(matching) + new_metadata = [None] * len(matching) + for match in matching: + if match.secondary is None: + # No descriptor match was found for this primary instance + # (e.g. a blank/corrupt frame) -- fill with an empty + # placeholder instead of crashing, but tag it so it's + # discoverable if it skews downstream results. + print( + f"Alignment.apply_matching: no match found for primary " + f"index {match.primary}; filling with an empty placeholder" + ) + new_data[match.primary] = _empty_like(original_data[0]) + new_metadata[match.primary] = { + **copy.deepcopy(original_metadata[0]), + "matching_idx": match.primary, + "unmatched": True, + } + continue + + new_data[match.primary] = original_data[match.secondary] + new_metadata[match.primary] = { + **original_metadata[match.secondary], + "matching_idx": match.primary, + } + + # Assign metadata (a plain attribute) before data (a property whose + # setter eagerly calls update_metadata()) so that trigger only ever + # sees fully-populated data/metadata, never `None` placeholders. + aligned_modality.metadata = new_metadata + aligned_modality.data = new_data return aligned_modality @@ -122,8 +162,8 @@ def _batch_compute_descriptors(self, modality): else: if not modality.has_data(): modality.extract_raw_data() - for d in modality.data: - descriptors.append(self.compute_descriptor(d)) + for d in modality.data: + descriptors.append(self.compute_descriptor(d)) return descriptors diff --git a/src/main/python/systemds/scuro/representations/ orb_alignment.py b/src/main/python/systemds/scuro/representations/orb_alignment.py similarity index 60% rename from src/main/python/systemds/scuro/representations/ orb_alignment.py rename to src/main/python/systemds/scuro/representations/orb_alignment.py index 5594f3bc54d..42825fe294e 100644 --- a/src/main/python/systemds/scuro/representations/ orb_alignment.py +++ b/src/main/python/systemds/scuro/representations/orb_alignment.py @@ -19,6 +19,8 @@ # # ------------------------------------------------------------- from systemds.scuro.representations.alignment import Alignment +from systemds.scuro.drsearch.operator_registry import register_alignment_operator +from systemds.scuro.modality.type import ModalityType from dataclasses import dataclass import numpy as np import cv2 as cv @@ -30,22 +32,41 @@ class OrbDescriptor: desc: object +@register_alignment_operator( + [ModalityType.VIDEO, ModalityType.VIDEO], + [ModalityType.VIDEO, ModalityType.IMAGE], + [ModalityType.IMAGE, ModalityType.IMAGE], +) class OrbAlignment(Alignment): def __init__(self): self.orb = cv.ORB_create() self.bfm = cv.BFMatcher(cv.NORM_HAMMING, crossCheck=True) - super().__init("OrbAlignment") + super().__init__("OrbAlignment") + + @staticmethod + def _to_uint8(frame): + if np.issubdtype(frame.dtype, np.floating): + return (frame * 255).astype(np.uint8, copy=True) + return np.asarray(frame, dtype=np.uint8) def compute_descriptor(self, segment): - return [OrbDescriptor(self.orb.detectAndCompute(segment, None))] + if segment.ndim == 3: + kp, desc = self.orb.detectAndCompute(self._to_uint8(segment), None) + return [OrbDescriptor(kp, desc)] + if segment.ndim == 4: + return [ + OrbDescriptor(*self.orb.detectAndCompute(self._to_uint8(frame), None)) + for frame in segment + ] + raise ValueError(f"Unexpected segment shape: {segment.shape}") def compare(self, a, b): if a.desc is None or b.desc is None: return float("inf") - matches = bfm.match(a.desc, b.desc) + matches = self.bfm.match(a.desc, b.desc) good_matches = [m for m in matches if m.distance < 40] if len(good_matches) == 0: - return float(inf) + return float("inf") return np.median([m.distance for m in good_matches]) diff --git a/src/main/python/systemds/scuro/representations/pHash_alignment.py b/src/main/python/systemds/scuro/representations/pHash_alignment.py index 6185ee0b92a..ad75c71978f 100644 --- a/src/main/python/systemds/scuro/representations/pHash_alignment.py +++ b/src/main/python/systemds/scuro/representations/pHash_alignment.py @@ -19,10 +19,17 @@ # # ------------------------------------------------------------- from systemds.scuro.representations.alignment import Alignment +from systemds.scuro.drsearch.operator_registry import register_alignment_operator +from systemds.scuro.modality.type import ModalityType import cv2 as cv import numpy as np +@register_alignment_operator( + [ModalityType.VIDEO, ModalityType.VIDEO], + [ModalityType.VIDEO, ModalityType.IMAGE], + [ModalityType.IMAGE, ModalityType.IMAGE], +) class PHashAlignment(Alignment): def __init__(self): super().__init__("pHashAlignment") From d3a5c661f0baaff1cb1f081a4e33ccb988bfc0cb Mon Sep 17 00:00:00 2001 From: b-enedict Date: Tue, 1 Dec 2026 12:19:23 +0100 Subject: [PATCH 2/7] [MINOR] Add source file path to Scuro loader metadata Every loader now records the file an instance was read from under the "file" metadata key (JSON instances additionally keep their "file_idx"). For lazily loaded images and videos the path is attached when the cached metadata is copied, so existing stats caches stay valid. VideoLoader gets an optional ext parameter. Assisted-by: AI Co-Authored-By: Claude Opus 5.5 --- .../systemds/scuro/dataloader/audio_loader.py | 2 +- .../systemds/scuro/dataloader/image_loader.py | 15 ++++++++++----- .../systemds/scuro/dataloader/json_loader.py | 9 ++++++++- .../systemds/scuro/dataloader/pdf_loader.py | 5 ++++- .../systemds/scuro/dataloader/text_loader.py | 5 ++++- .../scuro/dataloader/timeseries_loader.py | 9 ++++++--- .../systemds/scuro/dataloader/video_loader.py | 15 +++++++++------ 7 files changed, 42 insertions(+), 18 deletions(-) diff --git a/src/main/python/systemds/scuro/dataloader/audio_loader.py b/src/main/python/systemds/scuro/dataloader/audio_loader.py index 7ed59fc1150..42fa1a07f69 100644 --- a/src/main/python/systemds/scuro/dataloader/audio_loader.py +++ b/src/main/python/systemds/scuro/dataloader/audio_loader.py @@ -92,7 +92,7 @@ def _decode_file(self, file: str): if self.normalize: audio = librosa.util.normalize(audio) - return audio, self.modality_type.create_metadata(sr, audio) + return audio, {**self.modality_type.create_metadata(sr, audio), "file": file} def extract(self, file: str, index: Optional[Union[str, List[str]]] = None): audio, metadata = self._decode_file(file) diff --git a/src/main/python/systemds/scuro/dataloader/image_loader.py b/src/main/python/systemds/scuro/dataloader/image_loader.py index b94fa52bd34..a2def02f087 100644 --- a/src/main/python/systemds/scuro/dataloader/image_loader.py +++ b/src/main/python/systemds/scuro/dataloader/image_loader.py @@ -67,10 +67,12 @@ def load(self): if self.chunk_size: return super().load() - self.data = LazyFileSequence( - self.get_file_names(self.indices), self._decode_file - ) - self.metadata = self._all_metadata.copy() + file_names = self.get_file_names(self.indices) + self.data = LazyFileSequence(file_names, self._decode_file) + self.metadata = [ + {**metadata, "file": file} + for metadata, file in zip(self._all_metadata, file_names) + ] return self.data, self.metadata def _decode_file(self, file: str): @@ -90,7 +92,10 @@ def extract(self, file: str, index: Optional[Union[str, List[str]]] = None): height, width, channels = image.shape self.metadata.append( - self.modality_type.create_metadata(width, height, channels) + { + **self.modality_type.create_metadata(width, height, channels), + "file": file, + } ) self.data.append(image) diff --git a/src/main/python/systemds/scuro/dataloader/json_loader.py b/src/main/python/systemds/scuro/dataloader/json_loader.py index c8361643046..ac035d0e6c7 100644 --- a/src/main/python/systemds/scuro/dataloader/json_loader.py +++ b/src/main/python/systemds/scuro/dataloader/json_loader.py @@ -80,8 +80,15 @@ def extract(self, file: str, index: Optional[Union[str, List[str]]] = None): text = self._get_text(record) self.data.append(text) + file_reference = {"file": file} + if record is not json_file: + file_reference["file_idx"] = idx self.metadata.append( - {**self.modality_type.create_metadata(len(text), text), **record} + { + **self.modality_type.create_metadata(len(text), text), + **record, + **file_reference, + } ) def get_stats(self, source_path: str): diff --git a/src/main/python/systemds/scuro/dataloader/pdf_loader.py b/src/main/python/systemds/scuro/dataloader/pdf_loader.py index add02e50457..0a1edbe4761 100644 --- a/src/main/python/systemds/scuro/dataloader/pdf_loader.py +++ b/src/main/python/systemds/scuro/dataloader/pdf_loader.py @@ -64,7 +64,10 @@ def extract(self, file: str, index: Optional[Union[str, List[str]]] = None): image = image.astype(np.uint8, copy=False) self.metadata.append( - self.modality_type.create_metadata(width, height, channels) + { + **self.modality_type.create_metadata(width, height, channels), + "file": file, + } ) self.data.append(image) diff --git a/src/main/python/systemds/scuro/dataloader/text_loader.py b/src/main/python/systemds/scuro/dataloader/text_loader.py index f734a080b15..834f33f8632 100644 --- a/src/main/python/systemds/scuro/dataloader/text_loader.py +++ b/src/main/python/systemds/scuro/dataloader/text_loader.py @@ -57,7 +57,10 @@ def extract(self, file: str, index: Optional[Union[str, List[str]]] = None): line = re.sub(self.prefix, "", line) line = line.replace("\n", "") self.metadata.append( - self.modality_type.create_metadata(len(line.split()), line) + { + **self.modality_type.create_metadata(len(line.split()), line), + "file": file, + } ) self.data.append(line) diff --git a/src/main/python/systemds/scuro/dataloader/timeseries_loader.py b/src/main/python/systemds/scuro/dataloader/timeseries_loader.py index 669022cda41..e57abebebbe 100644 --- a/src/main/python/systemds/scuro/dataloader/timeseries_loader.py +++ b/src/main/python/systemds/scuro/dataloader/timeseries_loader.py @@ -99,9 +99,12 @@ def extract(self, file: str, index: Optional[Union[str, List[str]]] = None): else: for i, index in enumerate(self.indices): self.metadata.append( - self.modality_type.create_metadata( - self.signal_names, data[i], self.sampling_rate - ) + { + **self.modality_type.create_metadata( + self.signal_names, data[i], self.sampling_rate + ), + "file": file, + } ) self.data.append(data[i]) diff --git a/src/main/python/systemds/scuro/dataloader/video_loader.py b/src/main/python/systemds/scuro/dataloader/video_loader.py index 028c89a4ba3..05cf6117af4 100644 --- a/src/main/python/systemds/scuro/dataloader/video_loader.py +++ b/src/main/python/systemds/scuro/dataloader/video_loader.py @@ -74,9 +74,10 @@ def __init__( load=True, fps=None, target_size: Optional[Tuple[int, int]] = None, + ext=".mp4", ): super().__init__( - source_path, indices, data_type, chunk_size, ModalityType.VIDEO + source_path, indices, data_type, chunk_size, ModalityType.VIDEO, ext ) self.load_data_from_file = load self.fps = fps @@ -99,10 +100,12 @@ def load(self): if self.chunk_size: return super().load() - self.data = LazyFileSequence( - self.get_file_names(self.indices), self._decode_data - ) - self.metadata = self._all_metadata.copy() + file_names = self.get_file_names(self.indices) + self.data = LazyFileSequence(file_names, self._decode_data) + self.metadata = [ + {**metadata, "file": file} + for metadata, file in zip(self._all_metadata, file_names) + ] return self.data, self.metadata def _decode_data(self, file: str): @@ -191,7 +194,7 @@ def _decode_file(self, file: str): def extract(self, file: str, index: Optional[Union[str, List[str]]] = None): data, metadata = self._decode_file(file) - self.metadata.append(metadata) + self.metadata.append({**metadata, "file": file}) self.data.append(data) def get_stats(self, source_path: str): From 6c6bcf939f86554a2b422036e46b82e068679e5c Mon Sep 17 00:00:00 2001 From: b-enedict Date: Tue, 1 Dec 2026 12:19:38 +0100 Subject: [PATCH 3/7] [MINOR] Add OCR loader to Scuro OCRLoader extracts the text of images with Tesseract and exposes it as a TEXT modality. It is exported lazily, so pytesseract is only required when the loader is used. Assisted-by: AI Co-Authored-By: Claude Opus 5.5 --- src/main/python/systemds/scuro/__init__.py | 2 + .../systemds/scuro/dataloader/ocr_loader.py | 97 +++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 src/main/python/systemds/scuro/dataloader/ocr_loader.py diff --git a/src/main/python/systemds/scuro/__init__.py b/src/main/python/systemds/scuro/__init__.py index 58116b81bc4..0a68f913ed2 100644 --- a/src/main/python/systemds/scuro/__init__.py +++ b/src/main/python/systemds/scuro/__init__.py @@ -27,6 +27,7 @@ ("dataloader.video_loader", "VideoLoader"), ("dataloader.text_loader", "TextLoader"), ("dataloader.json_loader", "JSONLoader"), + ("dataloader.ocr_loader", "OCRLoader"), ("dataloader.tabular_loader", "TabularLoader"), ( "representations.representation", @@ -132,6 +133,7 @@ def __getattr__(name): "AudioLoader", "VideoLoader", "TextLoader", + "OCRLoader", "Representation", "Aggregation", "AggregatedRepresentation", diff --git a/src/main/python/systemds/scuro/dataloader/ocr_loader.py b/src/main/python/systemds/scuro/dataloader/ocr_loader.py new file mode 100644 index 00000000000..278df35f48c --- /dev/null +++ b/src/main/python/systemds/scuro/dataloader/ocr_loader.py @@ -0,0 +1,97 @@ +# ------------------------------------------------------------- +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +# ------------------------------------------------------------- +from typing import List, Optional, Union + +import numpy as np + +from systemds.scuro.dataloader.base_loader import BaseLoader +import cv2 +import pytesseract +from systemds.scuro.modality.type import ModalityType + + +class OCRLoader(BaseLoader): + """ + Loads images and extracts their textual content using the Tesseract OCR + engine. The recognized text is exposed as a TEXT modality so that it can be + further processed by the text representations. + + Requires the Tesseract binary to be installed on the system as well as the + ``pytesseract`` python wrapper. + """ + + def __init__( + self, + source_path: str, + indices: List[str], + data_type: Union[np.dtype, str] = str, + chunk_size: Optional[int] = None, + load=True, + ext=".jpg", + language: str = "eng", + config: str = "", + ): + """ + :param source_path: The location where the raw images lie + :param indices: A list of indices as strings corresponding to the file names + :param data_type: The data type the recognized text is stored as + :param chunk_size: An optional argument to load the data in chunks + :param load: Whether the data is read from file + :param ext: The file extension of the images + :param language: The language(s) passed to Tesseract (e.g. ``"eng"`` or ``"eng+deu"``) + :param config: Additional configuration flags forwarded to Tesseract + """ + super().__init__( + source_path, indices, data_type, chunk_size, ModalityType.TEXT, ext + ) + self.load_data_from_file = load + self.language = language + self.config = config + + def extract(self, file: str, index: Optional[Union[str, List[str]]] = None): + self.file_sanity_check(file) + + image = cv2.imread(file, cv2.IMREAD_COLOR) + # cv2.imread signals an undecodable file by *returning None* rather + # than raising. Passing that straight into cvtColor reaches OpenCV's + # native assertion layer, which depending on the build aborts the + # interpreter outright instead of raising -- killing the process with + # no Python traceback. Fail loudly here so the caller can log it. + if image is None: + raise ValueError( + f"cv2 could not decode image {file} (unsupported format, or " + f"truncated/corrupt file)" + ) + image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) + + text = pytesseract.image_to_string( + image, lang=self.language, config=self.config + ) + text = text.replace("\n", " ").strip() + + self.metadata.append( + { + **self.modality_type.create_metadata(len(text.split()), text), + "file": file, + } + ) + + self.data.append(text) From de26c748735056104389f4dc76443aded8ef799b Mon Sep 17 00:00:00 2001 From: b-enedict Date: Tue, 1 Dec 2026 12:20:14 +0100 Subject: [PATCH 4/7] [MINOR] Scuro padding control, GPU transcription and contrastive sampling - UnimodalModality.apply_representation(s) take an apply_padding flag - TranscriptLoader runs Whisper on the detected GPU and falls back to CPU - TransformedModality.context keeps the data when a context operator only annotates metadata and returns None - Contrastive learning names anchor/augmentation modalities and can cap the number of negatives per positive - Modality errors in the unimodal optimizer are printed to stderr Assisted-by: AI Co-Authored-By: Claude Opus 5.5 --- .../scuro/dataloader/transcript_loader.py | 61 +++++++++++++-- .../scuro/drsearch/unimodal_optimizer.py | 11 ++- .../systemds/scuro/modality/transformed.py | 6 +- .../scuro/modality/unimodal_modality.py | 27 ++++--- .../representations/contrastive_learning.py | 75 ++++++++++++++----- 5 files changed, 142 insertions(+), 38 deletions(-) diff --git a/src/main/python/systemds/scuro/dataloader/transcript_loader.py b/src/main/python/systemds/scuro/dataloader/transcript_loader.py index 67166f2c327..20b566e443c 100644 --- a/src/main/python/systemds/scuro/dataloader/transcript_loader.py +++ b/src/main/python/systemds/scuro/dataloader/transcript_loader.py @@ -18,12 +18,14 @@ # under the License. # # ------------------------------------------------------------- -from typing import List, Optional, Union +import warnings +from typing import List, Optional, Tuple, Union from faster_whisper import WhisperModel import numpy as np from systemds.scuro.dataloader.base_loader import BaseLoader from systemds.scuro.modality.type import ModalityType +from systemds.scuro.utils.static_variables import get_device class TranscriptLoader(BaseLoader): @@ -35,15 +37,64 @@ def __init__( chunk_size: Optional[int] = None, normalize: bool = True, transcribe_model_size: str = "medium", + device: Optional[str] = None, + gpu_id: Optional[int] = None, load=True, ): super().__init__(source_path, indices, data_type, chunk_size, ModalityType.TEXT) - self.model = WhisperModel( - transcribe_model_size, device="cpu", compute_type="int8" - ) + self.model = self._load_model(transcribe_model_size, device, gpu_id) self.normalize = normalize self.load_data_from_file = load + @staticmethod + def _resolve_device( + device: Optional[str], gpu_id: Optional[int] + ) -> Tuple[str, int, str]: + """ + faster-whisper runs on CTranslate2, not torch, so it wants a device + string plus an index instead of a torch.device. Map get_device() onto + that triple and pick the compute type that fits the device: float16 on + GPU, int8 on CPU. + """ + if device is None: + torch_device = get_device(gpu_id) + device = torch_device.type + device_index = torch_device.index if torch_device.index is not None else 0 + else: + device_index = gpu_id if gpu_id is not None else 0 + + compute_type = "float16" if device == "cuda" else "int8" + return device, device_index, compute_type + + def _load_model( + self, + transcribe_model_size: str, + device: Optional[str], + gpu_id: Optional[int], + ) -> WhisperModel: + device, device_index, compute_type = self._resolve_device(device, gpu_id) + + try: + return WhisperModel( + transcribe_model_size, + device=device, + device_index=device_index, + compute_type=compute_type, + ) + except Exception as e: # noqa: BLE001 + if device == "cpu": + raise + # A visible torch CUDA device does not guarantee CTranslate2 can use + # it: it loads its own cuBLAS/cuDNN and fails here when those are + # missing. Fall back rather than taking the whole run down. + warnings.warn( + f"Falling back to CPU transcription: could not load Whisper on " + f"{device}:{device_index} ({e})" + ) + return WhisperModel( + transcribe_model_size, device="cpu", compute_type="int8" + ) + def extract(self, file: str, index: Optional[Union[str, List[str]]] = None): self.file_sanity_check(file) segments, _ = self.model.transcribe(file, vad_filter=True) @@ -54,6 +105,6 @@ def extract(self, file: str, index: Optional[Union[str, List[str]]] = None): md["timestamp_end"] = seg.end md["text"] = seg.text - self.metadata.append(md) + self.metadata.append({**md, "file": file}) self.data.append(seg.text) diff --git a/src/main/python/systemds/scuro/drsearch/unimodal_optimizer.py b/src/main/python/systemds/scuro/drsearch/unimodal_optimizer.py index 9073ed45b85..c55822e7c95 100644 --- a/src/main/python/systemds/scuro/drsearch/unimodal_optimizer.py +++ b/src/main/python/systemds/scuro/drsearch/unimodal_optimizer.py @@ -23,6 +23,7 @@ import math import os import pickle +import sys import time from concurrent.futures import ProcessPoolExecutor, as_completed import multiprocessing as mp @@ -501,7 +502,10 @@ def optimize_parallel(self, n_workers=None): self.operator_performance.results, ) except Exception as e: - print(f"Error processing modality {modality.modality_id}: {e}") + print( + f"Error processing modality {modality.modality_id}: {e}", + file=sys.stderr, + ) import traceback traceback.print_exc() @@ -545,7 +549,10 @@ def _optimize_modalities(self): if self.save_all_results: self.store_results(f"{modality.modality_id}_unimodal_results.pkl") except Exception as e: - print(f"Error processing modality {modality.modality_id}: {e}") + print( + f"Error processing modality {modality.modality_id}: {e}", + file=sys.stderr, + ) import traceback traceback.print_exc() diff --git a/src/main/python/systemds/scuro/modality/transformed.py b/src/main/python/systemds/scuro/modality/transformed.py index eb5aa7c4edd..71e7b6fa09f 100644 --- a/src/main/python/systemds/scuro/modality/transformed.py +++ b/src/main/python/systemds/scuro/modality/transformed.py @@ -140,7 +140,11 @@ def context(self, context_operator): self, context_operator, self_contained=self.self_contained ) start = time.time() - transformed_modality.data = context_operator.execute(self) + # Context operators that only annotate metadata (e.g. the + # SentenceBoundarySplitIndices family records text spans) return None. + # Keep the original data in that case, as UnimodalModality.context does. + data = context_operator.execute(self) + transformed_modality.data = self.data if data is None else data set_valid_windows( transformed_modality, getattr(context_operator, "valid_windows", None) ) diff --git a/src/main/python/systemds/scuro/modality/unimodal_modality.py b/src/main/python/systemds/scuro/modality/unimodal_modality.py index 8b37da3a56e..34f5933fd11 100644 --- a/src/main/python/systemds/scuro/modality/unimodal_modality.py +++ b/src/main/python/systemds/scuro/modality/unimodal_modality.py @@ -204,10 +204,12 @@ def apply_representations( parallel=False, representation_keys=None, aggregations=None, + apply_padding=True, ): """ Applies a list of representations to the modality. Specifically, it applies the representations to the modality in a chunked manner. :param representations: List of representations to apply + :param apply_padding: If True, pads variable length instances to a common length :return: List of transformed modalities """ if representation_keys is None: @@ -240,7 +242,7 @@ def apply_representations( representation_keys, representations, aggregations ) ] - return self._apply_transform_units(units, parallel) + return self._apply_transform_units(units, parallel, apply_padding) def apply_representation_layers( self, representation, layer_names, aggregation=None @@ -258,7 +260,7 @@ def apply_representation_layers( [(layer_names, representation, transform)], parallel=False ) - def _apply_transform_units(self, units, parallel): + def _apply_transform_units(self, units, parallel, apply_padding=True): """Run each unit over every data chunk and gather its outputs by key. A unit is (keys, representation, transform), where one call of transform @@ -368,11 +370,12 @@ def _apply_transform_units(self, units, parallel): for representation_key in keys: if representation_key in failed_representations: continue - self._apply_padding( - transformed_modalities_per_representation[representation_key], - original_lengths_per_representation[representation_key], - padding_per_representation[representation_key], - ) + if apply_padding: + self._apply_padding( + transformed_modalities_per_representation[representation_key], + original_lengths_per_representation[representation_key], + padding_per_representation[representation_key], + ) transformed_modalities_per_representation[ representation_key ].transform_time += ( @@ -384,10 +387,12 @@ def _apply_transform_units(self, units, parallel): self.failed_representations = failed_representations return transformed_modalities_per_representation - def apply_representation(self, representation, aggregation=None): - return self.apply_representations([representation], aggregation=aggregation)[ - representation.name - ] + def apply_representation( + self, representation, aggregation=None, apply_padding=True + ): + return self.apply_representations( + [representation], aggregation=aggregation, apply_padding=apply_padding + )[representation.name] def _apply_padding(self, modality, original_lengths, pad_dim_one): if len(original_lengths) > 0 and min(original_lengths) < max(original_lengths): diff --git a/src/main/python/systemds/scuro/representations/contrastive_learning.py b/src/main/python/systemds/scuro/representations/contrastive_learning.py index 3599079e6f7..fec0e151d3b 100644 --- a/src/main/python/systemds/scuro/representations/contrastive_learning.py +++ b/src/main/python/systemds/scuro/representations/contrastive_learning.py @@ -19,16 +19,19 @@ # # ------------------------------------------------------------- import copy +from functools import reduce +import random class ContrasitveLearning: @staticmethod def execute( - input_first_modality, - input_second_modality, - input_first_extensions, - input_second_extensions, + input_anchor_modality, + input_augmentation_modality, + input_anchor_extensions, + input_augmentation_extensions, metadata_matching_function, + max_negatives_per_positive=float("inf"), ): # Add check for same dimensionality of input modlities and extensions @@ -44,38 +47,72 @@ def empty_modality_copy(input_modality): return modality - first_modality = empty_modality_copy(input_first_modality) - second_modality = empty_modality_copy(input_second_modality) - first_extensions = empty_modality_copy(input_first_extensions) - second_extensions = empty_modality_copy(input_second_extensions) + anchor_modality = empty_modality_copy(input_anchor_modality) + augmentation_modality = empty_modality_copy(input_augmentation_modality) + anchor_extensions = empty_modality_copy(input_anchor_extensions) + augmentation_extensions = empty_modality_copy(input_augmentation_extensions) labels = [] - for i in range(len(input_first_modality.data)): - for j in range(len(input_second_modality.data)): - first_modality.data.append(input_first_modality.data[i]) - first_modality.metadata.append(input_first_modality.metadata[i]) + augmentation_modality_length = len(input_augmentation_modality.data) + for i in range(len(input_anchor_modality.data)): + for j in range(augmentation_modality_length): + anchor_modality.data.append(input_anchor_modality.data[i]) + anchor_modality.metadata.append(input_anchor_modality.metadata[i]) - for m, input_m in zip(first_extensions, input_first_extensions): + for m, input_m in zip(anchor_extensions, input_anchor_extensions): m.data.append(input_m.data[i]) m.metadata.append(input_m.metadata[i]) - second_modality.data.append(input_second_modality.data[j]) - second_modality.metadata.append(input_second_modality.metadata[j]) + augmentation_modality.data.append(input_augmentation_modality.data[j]) + augmentation_modality.metadata.append( + input_augmentation_modality.metadata[j] + ) - for m, input_m in zip(second_extensions, input_second_extensions): + for m, input_m in zip( + augmentation_extensions, input_augmentation_extensions + ): m.data.append(input_m.data[j]) m.metadata.append(input_m.metadata[j]) if metadata_matching_function( - input_first_modality.metadata[i], input_second_modality.metadata[j] + input_anchor_modality.metadata[i], + input_augmentation_modality.metadata[j], ): labels.append(True) else: labels.append(False) + if max_negatives_per_positive == float("inf"): + continue + + new_labels = labels[-augmentation_modality_length:] + n_positives = new_labels.count(True) + max_new_negatives = n_positives * max_negatives_per_positive + negatives_indices = [ + m + len(labels) - augmentation_modality_length + for m in range(augmentation_modality_length) + if not new_labels[m] + ] + to_remove = random.sample( + negatives_indices, k=max(len(negatives_indices) - max_new_negatives, 0) + ) + + for k in sorted(to_remove, reverse=True): + labels.pop(k) + for mod in ( + [ + anchor_modality, + augmentation_modality, + ] + + anchor_extensions + + augmentation_extensions + ): + mod.data.pop(k) + mod.metadata.pop(k) + return ( - [first_modality] + first_extensions, - [second_modality] + second_extensions, + [anchor_modality] + anchor_extensions, + [augmentation_modality] + augmentation_extensions, labels, ) From 4b1e0836475a3b4783a67cdb4ff0b58acfbad0f4 Mon Sep 17 00:00:00 2001 From: b-enedict Date: Tue, 1 Dec 2026 12:21:47 +0100 Subject: [PATCH 5/7] [MINOR] Add PairedModality to Scuro PairedModality wraps two or more modalities of the same type (e.g. a retrieval corpus and its queries) and applies every operation to each of them, with a per-modality allow list of operations. Representations with an unsupervised fit requirement are fitted once on the corpus side and applied to all sides via transform_fitted, so the pair stays in one feature space. AggregatedRepresentation is dispatched through the modality so that a pair can fan it out. Assisted-by: AI Co-Authored-By: Claude Opus 5.5 --- src/main/python/systemds/scuro/__init__.py | 3 + .../systemds/scuro/drsearch/node_executor.py | 3 +- .../scuro/drsearch/representation_dag.py | 20 +- .../scuro/modality/paired_modality.py | 429 ++++++++++++++++++ 4 files changed, 453 insertions(+), 2 deletions(-) create mode 100644 src/main/python/systemds/scuro/modality/paired_modality.py diff --git a/src/main/python/systemds/scuro/__init__.py b/src/main/python/systemds/scuro/__init__.py index 0a68f913ed2..8573f435b82 100644 --- a/src/main/python/systemds/scuro/__init__.py +++ b/src/main/python/systemds/scuro/__init__.py @@ -82,6 +82,7 @@ ("modality.transformed", "TransformedModality"), ("modality.type", "ModalityType"), ("modality.unimodal_modality", "UnimodalModality"), + ("modality.paired_modality", "PairedModality PairedOperation"), ("drsearch.task", "Task"), ("drsearch.evaluation_split", "EvaluationSplit"), ("drsearch.operator_registry", "Registry"), @@ -181,6 +182,8 @@ def __getattr__(name): "TransformedModality", "ModalityType", "UnimodalModality", + "PairedModality", + "PairedOperation", "Task", "Registry", "OptimizationData", diff --git a/src/main/python/systemds/scuro/drsearch/node_executor.py b/src/main/python/systemds/scuro/drsearch/node_executor.py index 3e9f6cd00be..e22d5ca66ba 100644 --- a/src/main/python/systemds/scuro/drsearch/node_executor.py +++ b/src/main/python/systemds/scuro/drsearch/node_executor.py @@ -43,6 +43,7 @@ from systemds.scuro.drsearch.representation_dag import ( RepresentationDag, RepresentationNode, + apply_aggregated_representation, ) from systemds.scuro.drsearch.task import PerformanceMeasure from systemds.scuro.models.fused_mlp import ( @@ -296,7 +297,7 @@ def _run_node_op(): elif isinstance(node_operation, DimensionalityReduction): return input_mods[0].dimensionality_reduction(node_operation) elif isinstance(node_operation, AggregatedRepresentation): - return node_operation.transform(input_mods[0]) + return apply_aggregated_representation(input_mods[0], node_operation) elif isinstance(node_operation, UnimodalRepresentation): pushdown_config = node.parameters.get("_pushdown_aggregation", None) agg = ( diff --git a/src/main/python/systemds/scuro/drsearch/representation_dag.py b/src/main/python/systemds/scuro/drsearch/representation_dag.py index 5567c45554e..0f83f0e2259 100644 --- a/src/main/python/systemds/scuro/drsearch/representation_dag.py +++ b/src/main/python/systemds/scuro/drsearch/representation_dag.py @@ -51,6 +51,22 @@ from collections import Counter, OrderedDict, defaultdict, deque +def apply_aggregated_representation(modality, aggregated_representation): + """Apply an ``AggregatedRepresentation`` through the modality where it + knows how, and directly otherwise. + + ``AggregatedRepresentation`` is dispatched as + ``operation.transform(modality)`` instead of through a method on the + modality, so a container modality never gets the chance to fan it out + over what it contains. ``PairedModality`` exposes + ``apply_aggregated_representation`` for exactly that. + """ + fan_out = getattr(modality, "apply_aggregated_representation", None) + if fan_out is not None: + return fan_out(aggregated_representation) + return aggregated_representation.transform(modality) + + def pushdown_aggregation_for_node( node_parameters: Optional[Dict[str, Any]], ) -> Optional[AggregatedRepresentation]: @@ -419,7 +435,9 @@ def run_operation(): elif isinstance(node_operation, DimensionalityReduction): result = input_mods[0].dimensionality_reduction(node_operation) elif isinstance(node_operation, AggregatedRepresentation): - result = node_operation.transform(input_mods[0]) + result = apply_aggregated_representation( + input_mods[0], node_operation + ) elif isinstance(node_operation, UnimodalRepresentation): if rep_cache is not None: result = rep_cache[node_operation.name] diff --git a/src/main/python/systemds/scuro/modality/paired_modality.py b/src/main/python/systemds/scuro/modality/paired_modality.py new file mode 100644 index 00000000000..146c81d7436 --- /dev/null +++ b/src/main/python/systemds/scuro/modality/paired_modality.py @@ -0,0 +1,429 @@ +# ------------------------------------------------------------- +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +# ------------------------------------------------------------- +from enum import Enum +from typing import List + +from systemds.scuro.modality.indexed import IndexedModality +from systemds.scuro.modality.unimodal_modality import UnimodalModality +from systemds.scuro.representations.representation import FitRequirement + + +class PairedOperation(Enum): + """ + Operations that a ``PairedModality`` can delegate to its contained + modalities. The operation is only applied to a contained modality if it is + listed among that modality's allowed operations, otherwise it is skipped and + the modality is passed through unchanged. + """ + + REPRESENTATION = "representation" + CONTEXT = "context" + AGGREGATION = "aggregation" + WINDOW_AGGREGATION = "window_aggregation" + DIMENSIONALITY_REDUCTION = "dimensionality_reduction" + PADDING = "padding" + + +#: Every operation that changes an embedding's shape or the space it lives in. +#: +#: A retrieval pair's query side has to receive all of these or it silently +#: stops being comparable with the corpus: whatever stage runs on the corpus +#: alone leaves the query at the bare representation's own output width, and +#: the two can no longer be ranked against each other. ``PADDING`` is the one +#: operation that is legitimately corpus-only -- padding a question out to the +#: corpus's instance length is meaningless -- so it is the only one left out. +#: +#: Pass this as the query side's ``allowed_operations`` entry: +#: ``PairedModality([corpus, query], [None, SHAPE_AFFECTING_OPERATIONS])``. +SHAPE_AFFECTING_OPERATIONS = frozenset(PairedOperation) - {PairedOperation.PADDING} + + +class PairedModality: + """ + Wraps two (or more) unimodal modalities of the same type and applies the + same transformations and representations to all of them, mirroring the + interface of :class:`UnimodalModality`. + + For every operation an ``allowed_operations`` specification decides, per + modality, whether the operation is applied. If an operation is not allowed + for a given modality (e.g. padding is not possible for it), the operation is + skipped for that modality and it is passed through unchanged. + """ + + #: Which contained modality a representation with an unsupervised fit + #: requirement is fitted on, with every other side merely transformed by + #: that fitted state (see :meth:`apply_representation`). Index 0 is the corpus by convention in every + #: retrieval pair, and a vocabulary belongs to the corpus, not to the + #: handful of short questions asked against it. A class attribute rather + #: than a constructor argument so the subclasses that rebuild a pair + #: (``_wrap``, ``copy_from_instance``) carry it without restating it. + fit_modality_index = 0 + + def __init__(self, modalities, allowed_operations=None, default_modality_index=0): + """ + :param modalities: List of modalities to pair. They must all share the + same modality type. + :param allowed_operations: Optional specification of which operations + are possible for each modality. Either ``None`` (all operations + allowed for every modality) or a list parallel to ``modalities`` + where each entry is ``None`` (all allowed) or an iterable of + :class:`PairedOperation` (or their string values). + :param default_modality_index: Index of the modality that represents the + pair when a single value is requested (data, metadata, type, ...). + """ + if len(modalities) < 2: + raise ValueError("PairedModality requires at least two modalities") + + for modality in modalities[1:]: + if modality.modality_type != modalities[0].modality_type: + raise ValueError("Modalities must have the same type") + + if not 0 <= default_modality_index < len(modalities): + raise ValueError("default_modality_index is out of range") + + self.modalities = list(modalities) + self.default_modality_index = default_modality_index + # Strong reference to a shared-memory wrapper assigned through the + # ``data`` setter -- see the comment there for why dropping it segfaults. + self._shared_memory_backing = None + self.allowed_operations = self._normalize_allowed_operations( + allowed_operations, len(self.modalities) + ) + + # ------------------------------------------------------------------ + # Allowed operation handling + # ------------------------------------------------------------------ + def _normalize_allowed_operations(self, allowed_operations, n): + if allowed_operations is None: + return [set(PairedOperation) for _ in range(n)] + + if len(allowed_operations) != n: + raise ValueError( + "allowed_operations must have one entry per modality " + f"({n} expected, {len(allowed_operations)} given)" + ) + + normalized = [] + for ops in allowed_operations: + if ops is None: + normalized.append(set(PairedOperation)) + else: + normalized.append({self._to_operation(op) for op in ops}) + return normalized + + @staticmethod + def _to_operation(operation): + if isinstance(operation, PairedOperation): + return operation + return PairedOperation(operation) + + def _is_allowed(self, index, operation): + return operation in self.allowed_operations[index] + + # ------------------------------------------------------------------ + # Delegation helpers + # ------------------------------------------------------------------ + def _apply_to_each(self, operation, fn): + """ + Applies ``fn(modality, index)`` to every contained modality for which + ``operation`` is allowed and passes the others through unchanged, then + wraps the results in a new ``PairedModality``. + """ + results = [] + for index, modality in enumerate(self.modalities): + if self._is_allowed(index, operation): + results.append(fn(modality, index)) + else: + results.append(modality) + return self._wrap(results) + + def _wrap(self, modalities): + wrapped = PairedModality( + modalities, self.allowed_operations, self.default_modality_index + ) + # An operation can hand back a contained modality unchanged (e.g. + # AggregatedRepresentation returns its input when the dimensions + # already match), so the new pair may hold data that is still views + # into this pair's shared-memory segment. Carry the reference that + # keeps that segment mapped, or those views dangle as soon as this + # pair is released. + wrapped._shared_memory_backing = self._shared_memory_backing + return wrapped + + # ------------------------------------------------------------------ + # UnimodalModality-compatible interface + # ------------------------------------------------------------------ + def extract_raw_data(self): + for modality in self.modalities: + modality.extract_raw_data() + + def context(self, context_operator): + return self._apply_to_each( + PairedOperation.CONTEXT, + lambda modality, index: modality.context(context_operator), + ) + + def apply_aggregated_representation(self, aggregated_representation): + """ + Applies an ``AggregatedRepresentation`` to every contained modality for + which ``AGGREGATION`` is allowed. + + ``RepresentationDag`` dispatches an ``AggregatedRepresentation`` as + ``operation.transform(modality)`` rather than through a modality + method, which for a pair hands the representation *this* object. Its + ``.data`` is one array per contained modality, so the aggregation reads + the pair's two modalities as two "instances" and reduces across them -- + raising on a ragged corpus and collapsing the pair on a uniform one. + Fan out instead, like every other operation kind. + """ + return self._apply_to_each( + PairedOperation.AGGREGATION, + lambda modality, index: aggregated_representation.transform(modality), + ) + + def aggregate(self, aggregation_function): + return self._apply_to_each( + PairedOperation.AGGREGATION, + lambda modality, index: modality.aggregate(aggregation_function), + ) + + def window_aggregation(self, window_size, aggregation): + return self._apply_to_each( + PairedOperation.WINDOW_AGGREGATION, + lambda modality, index: modality.window_aggregation( + window_size, aggregation + ), + ) + + def dimensionality_reduction(self, dimensionality_reduction_operator): + return self._apply_to_each( + PairedOperation.DIMENSIONALITY_REDUCTION, + lambda modality, index: modality.dimensionality_reduction( + dimensionality_reduction_operator + ), + ) + + def apply_representation(self, representation, aggregation=None): + """ + Applies ``representation`` to every contained modality for which + ``REPRESENTATION`` is allowed. + + A representation that has to be fitted on its input (an unsupervised + fit requirement, e.g. the BoW/TF-IDF vocabulary or a Word2Vec model) is + fitted once on :attr:`fit_modality_index` and that fitted state is used + to transform every side. Fitting each side on its own would put the + pair into unrelated feature spaces that cannot be compared. + """ + if ( + getattr(representation, "fit_requirement", FitRequirement.NONE) + is FitRequirement.UNSUPERVISED + ): + fit_modality = self.modalities[self.fit_modality_index] + self._materialize(fit_modality) + fit_state = representation.fit(self._index(fit_modality)) + return self._apply_to_each( + PairedOperation.REPRESENTATION, + lambda modality, index: self._transform_fitted( + modality, representation, fit_state, aggregation + ), + ) + + return self._apply_to_each( + PairedOperation.REPRESENTATION, + lambda modality, index: self._transform( + modality, index, representation, aggregation + ), + ) + + @staticmethod + def _materialize(modality): + if not modality.has_data(): + modality.extract_raw_data() + + @staticmethod + def _index(modality): + return IndexedModality(modality, range(len(modality.data))) + + def _transform_fitted(self, modality, representation, fit_state, aggregation): + self._materialize(modality) + return representation.transform_fitted( + self._index(modality), fit_state, aggregation=aggregation + ).modality + + def apply_representations(self, representations, aggregation=None, parallel=False): + """ + Applies a list of representations to every contained modality. + :return: Dict mapping representation name to the resulting PairedModality + """ + return { + representation.name: self.apply_representation(representation, aggregation) + for representation in representations + } + + def _transform(self, modality, index, representation, aggregation): + # Padding is bundled into the representation step for unimodal + # modalities, so it is gated separately here. + if isinstance(modality, UnimodalModality): + return modality.apply_representation( + representation, + aggregation=aggregation, + apply_padding=self._is_allowed(index, PairedOperation.PADDING), + ) + return modality.apply_representation(representation, aggregation=aggregation) + + def pad(self, value=0, max_len=None): + for index, modality in enumerate(self.modalities): + if self._is_allowed(index, PairedOperation.PADDING): + modality.pad(value=value, max_len=max_len) + return self + + def flatten(self, padding=False): + for index, modality in enumerate(self.modalities): + do_pad = padding and self._is_allowed(index, PairedOperation.PADDING) + modality.flatten(padding=do_pad) + return self + + def copy_from_instance(self): + return PairedModality( + [modality.copy_from_instance() for modality in self.modalities], + self.allowed_operations, + self.default_modality_index, + ) + + # ------------------------------------------------------------------ + # Access to the representative (default) modality + # ------------------------------------------------------------------ + def get_default(self): + return self.modalities[self.default_modality_index] + + @property + def modality_type(self): + return self.get_default().modality_type + + @property + def schema(self): + return self.get_default().schema + + @property + def modality_id(self): + return self.get_default().modality_id + + @property + def data_type(self): + return self.get_default().data_type + + @property + def self_contained(self): + # AggregatedRepresentation.transform (and any other representation that + # builds a TransformedModality from its input) reads this off the + # modality it is handed, which for a paired search is this object. + return self.get_default().self_contained + + @property + def data(self): + # Return the data of *all* contained modalities so that whenever the + # pipeline reads ``.data`` to store, cache, serialize or hand it to a + # task, no modality is dropped and paired results stay meaningful. The + # result is a list aligned with ``self.modalities`` (index i holds the + # data of modality i). Use ``get_default().data`` if you specifically + # need the representative modality's array. + return [modality.data for modality in self.modalities] + + @data.setter + def data(self, value): + # Distribute per-modality data back so the round-trip + # (read ``.data`` -> materialize/restore -> write ``.data``) keeps every + # modality intact. ``value`` is normally the (possibly shared-memory + # backed) counterpart of what the getter returned, i.e. a sequence + # aligned with ``self.modalities``. Fall back to assigning the default + # modality for anything that is not such a sequence. + # A shared-memory wrapper (duck-typed by ``shm_name``) hands out numpy + # *views* into its mapped segment, and unmaps that segment as soon as it + # is garbage collected -- so distributing ``value[i]`` below without + # keeping ``value`` itself alive leaves every contained modality holding + # views into freed memory, and the next read or pickle of them is a + # use-after-free (SIGSEGV, no traceback, and in a spawned-worker + # pipeline it surfaces only as returncode -11). Since the getter returns + # a fresh list, this object is otherwise the pair's only reference to + # the wrapper: hold it for as long as the views can be reached. + if hasattr(value, "shm_name"): + self._shared_memory_backing = value + + # ``add_shared_memory_candidate`` takes its *nested* branch for a pair, + # because the getter's ``[modality_0_data, modality_1_data]`` is exactly + # a list-of-lists-of-arrays, and the resulting wrapper's ``len`` is its + # group count -- which equals ``len(self.modalities)``, so distributing + # one group per contained modality is the right thing to do. + if ( + value is not None + and hasattr(value, "__len__") + and len(value) == len(self.modalities) + ): + for modality, modality_data in zip(self.modalities, value): + modality.data = modality_data + else: + self.get_default().data = value + + @property + def stats(self): + return self.get_default().stats + + @property + def data_loader(self): + # The scheduler inspects the leaf modality's data_loader (e.g. for + # chunk_size) when grouping leaf-dependent nodes. + return self.get_default().data_loader + + @property + def metadata(self): + return self.get_default().metadata + + @property + def transform_time(self): + return sum(modality.transform_time for modality in self.modalities) + + def has_data(self): + return self.get_default().has_data() + + def has_metadata(self): + return self.get_default().has_metadata() + + def get_stats(self): + return self.get_default().get_stats() + + def estimate_peak_memory_bytes(self): + return self.get_default().estimate_peak_memory_bytes() + + def calculate_memory_usage(self): + # The result cache calls this on the (transformed) modality it stores. + return self.get_default().calculate_memory_usage() + + # ------------------------------------------------------------------ + # Container conveniences + # ------------------------------------------------------------------ + def __len__(self): + return len(self.modalities) + + def __iter__(self): + return iter(self.modalities) + + def __getitem__(self, index): + return self.modalities[index] From 7c64b5609cebbc23d94bc9f6043f761dd79abf1b Mon Sep 17 00:00:00 2001 From: b-enedict Date: Tue, 1 Dec 2026 14:34:53 +0100 Subject: [PATCH 6/7] [MINOR] Add alignment graph to Scuro AlignmentGraph models groups of implicitly aligned modalities as nodes and computed alignments as edges. For a set of representations it finds every combination of shortest alignment paths to a common target group (plus the unaligned variant) as MatchingPlans. AlignedRepresentation composes a plan into one matching and reorders a modality accordingly. The optimizers do not use the graph yet; the places where it would hook into the unimodal, multimodal and GA optimizers and into DAG execution are marked with comments. Assisted-by: AI Co-Authored-By: Claude Opus 5.5 --- .../scuro/drsearch/alignment_graph.py | 282 ++++++++++++++++++ .../scuro/drsearch/multimodal_ga_optimizer.py | 4 + .../scuro/drsearch/multimodal_optimizer.py | 40 +++ .../systemds/scuro/drsearch/node_executor.py | 3 + .../scuro/drsearch/representation_dag.py | 3 + .../scuro/drsearch/split_aware_evaluator.py | 6 + .../scuro/drsearch/unimodal_optimizer.py | 13 + .../representations/aligned_representation.py | 87 ++++++ .../tests/scuro/test_alignment_graph.py | 165 ++++++++++ 9 files changed, 603 insertions(+) create mode 100644 src/main/python/systemds/scuro/drsearch/alignment_graph.py create mode 100644 src/main/python/systemds/scuro/representations/aligned_representation.py create mode 100644 src/main/python/tests/scuro/test_alignment_graph.py diff --git a/src/main/python/systemds/scuro/drsearch/alignment_graph.py b/src/main/python/systemds/scuro/drsearch/alignment_graph.py new file mode 100644 index 00000000000..51dc82b2906 --- /dev/null +++ b/src/main/python/systemds/scuro/drsearch/alignment_graph.py @@ -0,0 +1,282 @@ +# ------------------------------------------------------------- +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +# ------------------------------------------------------------- +from __future__ import annotations + +import logging +from collections import deque +from dataclasses import dataclass, field +from itertools import product +from typing import Any, Dict, List, Optional + +from systemds.scuro.drsearch.operator_registry import Registry +from systemds.scuro.representations.alignment import Match + +logger = logging.getLogger(__name__) + + +@dataclass(eq=False) +class AlignmentNode: + """A group of modalities that are implicitly aligned with each other + (e.g. a video and the audio track extracted from it).""" + + group_id: int + edges: List["AlignmentEdge"] = field(default_factory=list, repr=False) + + def __hash__(self): + return hash(self.group_id) + + def __eq__(self, other): + return isinstance(other, AlignmentNode) and self.group_id == other.group_id + + +@dataclass +class AlignmentEdge: + """A computed alignment from ``start`` to ``to``. + + ``matching`` holds one :class:`Match` per instance of the fixated + representation (``to``): ``primary`` indexes the fixated instances and + ``secondary`` the instances of the aligned representation (``start``). + """ + + start: AlignmentNode = field(repr=False) + to: AlignmentNode = field(repr=False) + alignment_type: str + matching: List[Match] = field(repr=False) + aligned_representation_id: int + fixated_representation_id: int + + +@dataclass +class MatchingPlan: + """The chain of alignments that maps the instances of the representation + ``source_representation_id`` onto the instances of an alignment target.""" + + source_representation_id: int + alignment_sequence: List[AlignmentEdge] + + def __str__(self): + edges = "".join( + f"|{edge.alignment_type} -> {edge.fixated_representation_id}" + for edge in self.alignment_sequence + ) + return f"{self.source_representation_id}{edges}" + + +@dataclass +class RepresentationWrapper: + representation: Any + group_id: int + rep_id: Any + + +class AlignmentGraph: + """Graph of the alignments that can be computed between groups of + modalities. + + Every group of implicitly aligned modalities becomes a node. Computing an + alignment between representations of two groups adds an edge, so that a + representation can be aligned to any other group that is reachable through + a chain of alignments. + """ + + def __init__(self, modality_groups): + """ + :param modality_groups: List of groups, each a list of modalities that + are already aligned with each other. The first modality's id is + used as the id of the group. + """ + self.representations: Dict[Any, RepresentationWrapper] = {} + self.nodes: Dict[int, AlignmentNode] = {} + self._create_graph_abstraction_from_mod_groups(modality_groups) + + def explore_and_execute_possible_alignments(self): + """Computes every registered alignment between the representations of + two different groups and adds the results as edges to the graph. + + Only representations that carry their modality (the ones the graph was + created with) are aligned. Representations added through + :meth:`register_new_representation` share the instance order of their + group and therefore reuse the group's alignments. + """ + registry = Registry() + wrappers = [ + wrapper + for wrapper in self.representations.values() + if wrapper.representation is not None + ] + for fixated, aligned in product(wrappers, repeat=2): + if fixated.group_id == aligned.group_id: + continue + + alignment_operators = registry.get_alignment_operator( + [ + fixated.representation.modality_type, + aligned.representation.modality_type, + ] + ) + for alignment_operator in alignment_operators: + alignment = alignment_operator() + matching = alignment.execute( + fixated.representation, aligned.representation + ) + start = self.nodes[aligned.group_id] + start.edges.append( + AlignmentEdge( + start, + self.nodes[fixated.group_id], + alignment.name, + matching, + aligned.rep_id, + fixated.rep_id, + ) + ) + + def find_representation_subset_alignments( + self, representation_subset_ids, include_unaligned: bool = True + ) -> List[List[MatchingPlan]]: + """Returns every way of aligning the given representations to one + common target group. + + For each group that can act as the alignment target, every combination + of shortest alignment paths from the other groups to it yields one + variation: a list of :class:`MatchingPlan`, one per representation that + has to be aligned (representations of the target group need none). + Targets that some group cannot reach are skipped. + + :param representation_subset_ids: Ids of the representations to align + :param include_unaligned: If True, the first variation is the empty + plan list, i.e. leaving the representations unaligned + """ + nodes = [] + for representation_id in representation_subset_ids: + node = self.get_node(representation_id) + if node not in nodes: + nodes.append(node) + + if len(nodes) < 2: + return [[]] + + variations = [[]] if include_unaligned else [] + for target in nodes: + path_options = [] + for flexible in nodes: + if flexible == target: + continue + paths = self._shortest_alignment_paths(flexible, target) + if not paths: + logger.debug( + "No alignment path from group %s to group %s", + flexible.group_id, + target.group_id, + ) + path_options = None + break + path_options.append(paths) + + if path_options is None: + continue + + for combination in product(*path_options): + path_per_group = {path[0].start.group_id: path for path in combination} + variation = [] + for representation_id in representation_subset_ids: + group_id = self.get_node(representation_id).group_id + if group_id in path_per_group: + variation.append( + MatchingPlan( + representation_id, list(path_per_group[group_id]) + ) + ) + variations.append(variation) + + logger.debug("Alignment variations:\n%s", self.format_variations(variations)) + return variations + + @staticmethod + def _shortest_alignment_paths( + start_node: AlignmentNode, end_node: AlignmentNode + ) -> List[List[AlignmentEdge]]: + """All shortest edge paths from ``start_node`` to ``end_node``. Parallel + edges (different alignment operators) yield separate paths.""" + depth = {start_node.group_id: 0} + queue = deque([edge] for edge in start_node.edges) + shortest_paths = [] + min_path_len = None + + while queue: + path = queue.popleft() + if min_path_len is not None and len(path) > min_path_len: + break + + edge = path[-1] + if edge.to == end_node: + min_path_len = len(path) + shortest_paths.append(path) + continue + + group_id = edge.to.group_id + if group_id in depth and depth[group_id] < len(path): + continue + depth[group_id] = len(path) + + for next_edge in edge.to.edges: + queue.append(path + [next_edge]) + + return shortest_paths + + @staticmethod + def format_variations(variations) -> str: + inner = [] + for variation in variations: + plans = ",\n".join(f" {plan}" for plan in variation) + inner.append(f" [\n{plans}\n ]") + return "[\n" + "\n\n".join(inner) + "\n]" + + def _create_graph_abstraction_from_mod_groups(self, modality_groups): + for group in modality_groups: + group_id = group[0].modality_id + self.nodes[group_id] = AlignmentNode(group_id) + + for modality in group: + self.representations[modality.modality_id] = RepresentationWrapper( + modality, group_id, modality.modality_id + ) + + def register_new_representation(self, existing_id, new_id): + """Registers ``new_id`` as a representation derived from + ``existing_id``. It belongs to the same group and therefore shares the + group's alignments.""" + if new_id in self.representations: + return + + existing = self.representations.get(existing_id) + if existing is None: + raise KeyError(f"Unknown representation id: {existing_id}") + + self.representations[new_id] = RepresentationWrapper( + None, existing.group_id, new_id + ) + + def get_node(self, representation_id) -> Optional[AlignmentNode]: + wrapper = self.representations.get(representation_id) + if wrapper is None: + raise KeyError(f"Unknown representation id: {representation_id}") + return self.nodes[wrapper.group_id] diff --git a/src/main/python/systemds/scuro/drsearch/multimodal_ga_optimizer.py b/src/main/python/systemds/scuro/drsearch/multimodal_ga_optimizer.py index 0743307d5aa..f4e13c356e7 100644 --- a/src/main/python/systemds/scuro/drsearch/multimodal_ga_optimizer.py +++ b/src/main/python/systemds/scuro/drsearch/multimodal_ga_optimizer.py @@ -1111,6 +1111,10 @@ def _assign_fusion_ops(self, subtree: Tree, ops: Dict[str, Any], path: str) -> N self._assign_fusion_ops(right, ops, path + "R") def _genome_to_dag(self, genome: DagGenome) -> RepresentationDag: + # Alignment graph integration (not enabled yet): the alignment variant + # would become part of the genome, and leaves that have to be aligned + # would get an AlignedRepresentation node on top, as in + # MultimodalOptimizer._generate_fusion_dags. builder = RepresentationDAGBuilder() leaf_ids = [ builder.create_leaf_node(mod_id, repr_idx) diff --git a/src/main/python/systemds/scuro/drsearch/multimodal_optimizer.py b/src/main/python/systemds/scuro/drsearch/multimodal_optimizer.py index 3bd201f0c7b..73f8a8d518a 100644 --- a/src/main/python/systemds/scuro/drsearch/multimodal_optimizer.py +++ b/src/main/python/systemds/scuro/drsearch/multimodal_optimizer.py @@ -37,6 +37,12 @@ from systemds.scuro.representations.aggregated_representation import ( AggregatedRepresentation, ) + +# Alignment graph integration (not enabled yet): +# from systemds.scuro.drsearch.alignment_graph import AlignmentGraph +# from systemds.scuro.representations.aligned_representation import ( +# AlignedRepresentation, +# ) from systemds.scuro.drsearch.algebra import ( AlgebraConfig, canonical_id, @@ -144,8 +150,13 @@ def __init__( resume: bool = False, algebra: Optional[AlgebraConfig] = None, objectives=None, + # Alignment graph integration (not enabled yet): an AlignmentGraph on + # which explore_and_execute_possible_alignments() has already run, so + # fusion DAGs can be generated once per alignment variant. + # alignment_graph: Optional["AlignmentGraph"] = None, ): self.modalities = modalities + # self.alignment_graph = alignment_graph self.objectives = ( [(metric, "max")] if objectives is None else validate_objectives(objectives) ) @@ -458,11 +469,40 @@ def build_variants( ) seen_canonical = set() + # Alignment graph integration (not enabled yet): every fusion DAG would + # be generated once per alignment variant. The first variant is the + # empty one, which keeps the current, unaligned DAGs. + # + # alignment_variants = ( + # self.alignment_graph.find_representation_subset_alignments( + # [modality_id for modality_id, _ in leaf_infos] + # ) + # if self.alignment_graph is not None + # else [[]] + # ) + # for alignment_variant in alignment_variants: + # plan_per_modality = { + # plan.source_representation_id: plan for plan in alignment_variant + # } + # ... the loop below, indented by one level ... + for permuted_leaf_infos in leaf_orders: base_builder = RepresentationDAGBuilder() leaf_id_map = {} for idx, (modality_id, repr_idx) in enumerate(permuted_leaf_infos): nodeid = base_builder.create_leaf_node(modality_id, repr_idx) + # Alignment graph integration (not enabled yet): a leaf that + # has to be aligned gets an AlignedRepresentation node on top. + # The plan's string goes into the parameters because the DAG's + # pipeline id only sees plain values. + # + # plan = plan_per_modality.get(modality_id) + # if plan is not None: + # nodeid = base_builder.create_operation_node( + # AlignedRepresentation, + # [nodeid], + # {"matching_sequence": plan, "description": str(plan)}, + # ) leaf_id_map[idx] = nodeid indices = list(range(n)) diff --git a/src/main/python/systemds/scuro/drsearch/node_executor.py b/src/main/python/systemds/scuro/drsearch/node_executor.py index e22d5ca66ba..1080c6f2685 100644 --- a/src/main/python/systemds/scuro/drsearch/node_executor.py +++ b/src/main/python/systemds/scuro/drsearch/node_executor.py @@ -298,6 +298,9 @@ def _run_node_op(): return input_mods[0].dimensionality_reduction(node_operation) elif isinstance(node_operation, AggregatedRepresentation): return apply_aggregated_representation(input_mods[0], node_operation) + # Alignment graph integration (not enabled yet): + # elif isinstance(node_operation, AlignedRepresentation): + # return node_operation.transform(input_mods[0]) elif isinstance(node_operation, UnimodalRepresentation): pushdown_config = node.parameters.get("_pushdown_aggregation", None) agg = ( diff --git a/src/main/python/systemds/scuro/drsearch/representation_dag.py b/src/main/python/systemds/scuro/drsearch/representation_dag.py index 0f83f0e2259..e3d6fd919c5 100644 --- a/src/main/python/systemds/scuro/drsearch/representation_dag.py +++ b/src/main/python/systemds/scuro/drsearch/representation_dag.py @@ -438,6 +438,9 @@ def run_operation(): result = apply_aggregated_representation( input_mods[0], node_operation ) + # Alignment graph integration (not enabled yet): + # elif isinstance(node_operation, AlignedRepresentation): + # result = node_operation.transform(input_mods[0]) elif isinstance(node_operation, UnimodalRepresentation): if rep_cache is not None: result = rep_cache[node_operation.name] diff --git a/src/main/python/systemds/scuro/drsearch/split_aware_evaluator.py b/src/main/python/systemds/scuro/drsearch/split_aware_evaluator.py index 2ad2a9d7225..1b3ab4b7354 100644 --- a/src/main/python/systemds/scuro/drsearch/split_aware_evaluator.py +++ b/src/main/python/systemds/scuro/drsearch/split_aware_evaluator.py @@ -147,6 +147,12 @@ def _apply_stateless(self, operation, inputs, node): transformed = inputs.modality.dimensionality_reduction(operation) elif isinstance(operation, AggregatedRepresentation): transformed = operation.transform(inputs.modality) + # Alignment graph integration (not enabled yet): a matching indexes the + # full dataset, but a partition only holds the instances of one CV + # split, so the matching has to be restricted to inputs.instance_ids + # (and the matched source instances) before it is applied here. + # elif isinstance(operation, AlignedRepresentation): + # ... elif isinstance(operation, UnimodalRepresentation): transformed = inputs.modality.apply_representation( operation, aggregation=aggregation diff --git a/src/main/python/systemds/scuro/drsearch/unimodal_optimizer.py b/src/main/python/systemds/scuro/drsearch/unimodal_optimizer.py index c55822e7c95..115149c8cd3 100644 --- a/src/main/python/systemds/scuro/drsearch/unimodal_optimizer.py +++ b/src/main/python/systemds/scuro/drsearch/unimodal_optimizer.py @@ -317,7 +317,12 @@ def __init__( enable_checkpointing: bool = False, window_combination_chains: int = 1, algebra: Optional[AlgebraConfig] = None, + # Alignment graph integration (not enabled yet): representations built + # here would be registered in the graph so that they inherit their + # modality's alignments. + # alignment_graph=None, ): + # self.alignment_graph = alignment_graph self._node_stats: Dict[str, Any] = {} self.pruned = [] self.window_combination_chains = window_combination_chains @@ -871,6 +876,14 @@ def _build_modality_dag( rep_node_id = builder.create_operation_node( operator.__class__, [leaf_id], operator.get_current_parameters() ) + # Alignment graph integration (not enabled yet). Note that + # optimize_parallel() builds DAGs in spawned worker processes, so the + # registrations have to be returned with the results and applied in + # the parent process. + # if self.alignment_graph is not None: + # self.alignment_graph.register_new_representation( + # modality.modality_id, rep_node_id + # ) current_node_id = rep_node_id rep_dag = builder.build(current_node_id) requires_dimensionality_reduction = getattr( diff --git a/src/main/python/systemds/scuro/representations/aligned_representation.py b/src/main/python/systemds/scuro/representations/aligned_representation.py new file mode 100644 index 00000000000..3daeef08eee --- /dev/null +++ b/src/main/python/systemds/scuro/representations/aligned_representation.py @@ -0,0 +1,87 @@ +# ------------------------------------------------------------- +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +# ------------------------------------------------------------- +from __future__ import annotations + +from typing import List, Union + +from systemds.scuro.drsearch.alignment_graph import MatchingPlan +from systemds.scuro.representations.alignment import Alignment, Match +from systemds.scuro.representations.representation import Representation + + +class AlignedRepresentation(Representation): + """Reorders the instances of a modality according to a matching, so that + instance ``i`` of the result corresponds to instance ``i`` of the alignment + target.""" + + def __init__( + self, + matching_sequence: Union[List[Match], MatchingPlan] = None, + description: str = None, + params=None, + ): + if params is not None: + matching_sequence = params.get("matching_sequence", matching_sequence) + description = params.get("description", description) + + super().__init__("AlignedRepresentation", {}) + if isinstance(matching_sequence, MatchingPlan): + self.matching = self.reduce_matching_plan(matching_sequence) + if description is None: + description = str(matching_sequence) + else: + self.matching = list(matching_sequence or []) + self.description = description + + def transform(self, modality): + return Alignment.apply_matching(self.matching, modality) + + @staticmethod + def reduce_matching_plan(matching_plan: MatchingPlan) -> List[Match]: + """Composes the matchings along the plan's alignment sequence into one + matching from the target's instances to the source's instances. + + Distances add up along the sequence. An instance that is unmatched at + any step stays unmatched. The plan and its edges are not modified. + """ + edges = matching_plan.alignment_sequence + if not edges: + raise ValueError("A matching plan needs at least one alignment") + + # primary (instance of the current target) -> (source instance, distance) + composed = { + match.primary: (match.secondary, match.distance) + for match in edges[0].matching + } + for edge in edges[1:]: + next_composed = {} + for match in edge.matching: + source, distance = composed.get(match.secondary, (None, None)) + if match.secondary is None or source is None: + next_composed[match.primary] = (None, float("inf")) + else: + next_composed[match.primary] = (source, match.distance + distance) + composed = next_composed + + return [ + Match(primary, source, distance) + for primary, (source, distance) in sorted(composed.items()) + ] diff --git a/src/main/python/tests/scuro/test_alignment_graph.py b/src/main/python/tests/scuro/test_alignment_graph.py new file mode 100644 index 00000000000..b1b8642ed40 --- /dev/null +++ b/src/main/python/tests/scuro/test_alignment_graph.py @@ -0,0 +1,165 @@ +# ------------------------------------------------------------- +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +# ------------------------------------------------------------- +import unittest + +from systemds.scuro.drsearch.alignment_graph import ( + AlignmentEdge, + AlignmentGraph, + MatchingPlan, +) +from systemds.scuro.drsearch.operator_registry import Registry +from systemds.scuro.modality.type import ModalityType +from systemds.scuro.representations.aligned_representation import ( + AlignedRepresentation, +) +from systemds.scuro.representations.alignment import Match + + +class _Modality: + def __init__(self, modality_id, data=None, modality_type=ModalityType.TEXT): + self.modality_id = modality_id + self.modality_type = modality_type + self.data = data or [] + self.metadata = [{"idx": i} for i in range(len(self.data))] + + +class _ReverseAlignment: + """Matches instance i of the fixated modality to instance n-1-i.""" + + name = "reverse" + + def execute(self, fixated, aligned): + n = len(fixated.data) + return [Match(i, n - 1 - i, 1.0) for i in range(n)] + + +def _connect(graph, start_id, to_id, matching, name="op"): + start, to = graph.nodes[start_id], graph.nodes[to_id] + start.edges.append(AlignmentEdge(start, to, name, matching, start_id, to_id)) + + +class TestAlignmentGraph(unittest.TestCase): + def _chain_graph(self): + # Groups 1 -> 2 -> 3, where group 1 also contains modality 4. + graph = AlignmentGraph( + [[_Modality(1), _Modality(4)], [_Modality(2)], [_Modality(3)]] + ) + _connect(graph, 1, 2, [Match(0, 1, 0.5), Match(1, 0, 0.5)]) + _connect(graph, 2, 3, [Match(0, 0, 1.0), Match(1, None, float("inf"))]) + return graph + + def test_shortest_paths_follow_chain_and_parallel_edges(self): + graph = self._chain_graph() + _connect(graph, 1, 3, [Match(0, 0, 0.1)], name="direct") + _connect(graph, 1, 3, [Match(0, 0, 0.2)], name="direct2") + paths = graph._shortest_alignment_paths(graph.nodes[1], graph.nodes[3]) + self.assertEqual( + sorted(p[0].alignment_type for p in paths), ["direct", "direct2"] + ) + self.assertTrue(all(len(p) == 1 for p in paths)) + + def test_variations_skip_unreachable_targets_and_keep_unaligned(self): + graph = self._chain_graph() + variations = graph.find_representation_subset_alignments([1, 3]) + # Empty variation first, then only target 3 (1 cannot be reached). + self.assertEqual(variations[0], []) + self.assertEqual(len(variations), 2) + (plan,) = variations[1] + self.assertEqual(plan.source_representation_id, 1) + self.assertEqual(len(plan.alignment_sequence), 2) + + no_unaligned = graph.find_representation_subset_alignments( + [1, 3], include_unaligned=False + ) + self.assertEqual(len(no_unaligned), 1) + + def test_members_of_a_group_share_its_alignment_plan(self): + graph = self._chain_graph() + variations = graph.find_representation_subset_alignments( + [1, 4, 2], include_unaligned=False + ) + to_group_2 = [v for v in variations if len(v) == 2] + self.assertEqual([p.source_representation_id for p in to_group_2[0]], [1, 4]) + + def test_register_new_representation_joins_group(self): + graph = self._chain_graph() + graph.register_new_representation(2, "rep_node") + self.assertEqual(graph.get_node("rep_node").group_id, 2) + with self.assertRaises(KeyError): + graph.register_new_representation("missing", "other") + + def test_explore_uses_registered_alignment_operators(self): + registry = Registry() + registry.add_alignment_operator( + _ReverseAlignment, [ModalityType.TEXT, ModalityType.TEXT] + ) + try: + graph = AlignmentGraph( + [[_Modality(1, ["a", "b", "c"])], [_Modality(2, ["x", "y", "z"])]] + ) + graph.explore_and_execute_possible_alignments() + finally: + registry._alignment_operators[2][ModalityType.TEXT].remove( + _ReverseAlignment + ) + edge_types = [e.alignment_type for e in graph.nodes[1].edges] + self.assertIn("reverse", edge_types) + self.assertEqual(graph.nodes[1].edges[0].to.group_id, 2) + + +class TestAlignedRepresentation(unittest.TestCase): + def test_reduce_matching_plan_composes_without_mutation(self): + graph = TestAlignmentGraph()._chain_graph() + (plan,) = graph.find_representation_subset_alignments( + [1, 3], include_unaligned=False + )[0] + before = [list(e.matching) for e in plan.alignment_sequence] + matching = AlignedRepresentation.reduce_matching_plan(plan) + # target 0 -> group 2 instance 0 -> group 1 instance 1 + self.assertEqual(matching[0], Match(0, 1, 1.5)) + self.assertEqual(matching[1].secondary, None) + self.assertEqual([list(e.matching) for e in plan.alignment_sequence], before) + # Reducing twice gives the same result. + self.assertEqual(AlignedRepresentation.reduce_matching_plan(plan), matching) + + def test_transform_reorders_and_marks_unmatched(self): + source = _Modality(1, ["first", "second"]) + aligned = AlignedRepresentation( + params={ + "matching_sequence": [Match(0, 1, 0.0), Match(1, None, 0.0)], + "description": "test", + } + ).transform(source) + self.assertEqual(aligned.data, ["second", ""]) + self.assertTrue(aligned.metadata[1]["unmatched"]) + self.assertEqual(source.data, ["first", "second"]) + + def test_description_defaults_to_plan_string(self): + graph = TestAlignmentGraph()._chain_graph() + (plan,) = graph.find_representation_subset_alignments( + [1, 2], include_unaligned=False + )[0] + self.assertEqual(AlignedRepresentation(plan).description, str(plan)) + self.assertIsInstance(plan, MatchingPlan) + + +if __name__ == "__main__": + unittest.main() From 14bea12435cb9c4dc1d9105d0205cd826e8420f0 Mon Sep 17 00:00:00 2001 From: b-enedict Date: Tue, 1 Dec 2026 14:57:32 +0100 Subject: [PATCH 7/7] [MINOR] Add tests for new Scuro components Cover the source file metadata of the loaders (eager, chunked and JSON), the OCR loader with a mocked Tesseract, PairedModality (validation, shared fitted vocabulary, allowed operations, data distribution), the negative sampling cap of contrastive learning and disabling padding in UnimodalModality.apply_representation. Assisted-by: AI Co-Authored-By: Claude Opus 5.5 --- .../tests/scuro/test_alignment_graph.py | 34 +++--- .../scuro/test_chunked_leaf_execution.py | 11 ++ .../tests/scuro/test_contrastive_learning.py | 82 +++++++++++++ .../python/tests/scuro/test_data_loaders.py | 62 ++++++++++ .../python/tests/scuro/test_ocr_loader.py | 81 +++++++++++++ .../tests/scuro/test_paired_modality.py | 113 ++++++++++++++++++ 6 files changed, 365 insertions(+), 18 deletions(-) create mode 100644 src/main/python/tests/scuro/test_contrastive_learning.py create mode 100644 src/main/python/tests/scuro/test_ocr_loader.py create mode 100644 src/main/python/tests/scuro/test_paired_modality.py diff --git a/src/main/python/tests/scuro/test_alignment_graph.py b/src/main/python/tests/scuro/test_alignment_graph.py index b1b8642ed40..cd8b86629e8 100644 --- a/src/main/python/tests/scuro/test_alignment_graph.py +++ b/src/main/python/tests/scuro/test_alignment_graph.py @@ -56,18 +56,19 @@ def _connect(graph, start_id, to_id, matching, name="op"): start.edges.append(AlignmentEdge(start, to, name, matching, start_id, to_id)) -class TestAlignmentGraph(unittest.TestCase): - def _chain_graph(self): - # Groups 1 -> 2 -> 3, where group 1 also contains modality 4. - graph = AlignmentGraph( - [[_Modality(1), _Modality(4)], [_Modality(2)], [_Modality(3)]] - ) - _connect(graph, 1, 2, [Match(0, 1, 0.5), Match(1, 0, 0.5)]) - _connect(graph, 2, 3, [Match(0, 0, 1.0), Match(1, None, float("inf"))]) - return graph +def _chain_graph(): + # Groups 1 -> 2 -> 3, where group 1 also contains modality 4. + graph = AlignmentGraph( + [[_Modality(1), _Modality(4)], [_Modality(2)], [_Modality(3)]] + ) + _connect(graph, 1, 2, [Match(0, 1, 0.5), Match(1, 0, 0.5)]) + _connect(graph, 2, 3, [Match(0, 0, 1.0), Match(1, None, float("inf"))]) + return graph + +class TestAlignmentGraph(unittest.TestCase): def test_shortest_paths_follow_chain_and_parallel_edges(self): - graph = self._chain_graph() + graph = _chain_graph() _connect(graph, 1, 3, [Match(0, 0, 0.1)], name="direct") _connect(graph, 1, 3, [Match(0, 0, 0.2)], name="direct2") paths = graph._shortest_alignment_paths(graph.nodes[1], graph.nodes[3]) @@ -77,9 +78,8 @@ def test_shortest_paths_follow_chain_and_parallel_edges(self): self.assertTrue(all(len(p) == 1 for p in paths)) def test_variations_skip_unreachable_targets_and_keep_unaligned(self): - graph = self._chain_graph() + graph = _chain_graph() variations = graph.find_representation_subset_alignments([1, 3]) - # Empty variation first, then only target 3 (1 cannot be reached). self.assertEqual(variations[0], []) self.assertEqual(len(variations), 2) (plan,) = variations[1] @@ -92,7 +92,7 @@ def test_variations_skip_unreachable_targets_and_keep_unaligned(self): self.assertEqual(len(no_unaligned), 1) def test_members_of_a_group_share_its_alignment_plan(self): - graph = self._chain_graph() + graph = _chain_graph() variations = graph.find_representation_subset_alignments( [1, 4, 2], include_unaligned=False ) @@ -100,7 +100,7 @@ def test_members_of_a_group_share_its_alignment_plan(self): self.assertEqual([p.source_representation_id for p in to_group_2[0]], [1, 4]) def test_register_new_representation_joins_group(self): - graph = self._chain_graph() + graph = _chain_graph() graph.register_new_representation(2, "rep_node") self.assertEqual(graph.get_node("rep_node").group_id, 2) with self.assertRaises(KeyError): @@ -127,17 +127,15 @@ def test_explore_uses_registered_alignment_operators(self): class TestAlignedRepresentation(unittest.TestCase): def test_reduce_matching_plan_composes_without_mutation(self): - graph = TestAlignmentGraph()._chain_graph() + graph = _chain_graph() (plan,) = graph.find_representation_subset_alignments( [1, 3], include_unaligned=False )[0] before = [list(e.matching) for e in plan.alignment_sequence] matching = AlignedRepresentation.reduce_matching_plan(plan) - # target 0 -> group 2 instance 0 -> group 1 instance 1 self.assertEqual(matching[0], Match(0, 1, 1.5)) self.assertEqual(matching[1].secondary, None) self.assertEqual([list(e.matching) for e in plan.alignment_sequence], before) - # Reducing twice gives the same result. self.assertEqual(AlignedRepresentation.reduce_matching_plan(plan), matching) def test_transform_reorders_and_marks_unmatched(self): @@ -153,7 +151,7 @@ def test_transform_reorders_and_marks_unmatched(self): self.assertEqual(source.data, ["first", "second"]) def test_description_defaults_to_plan_string(self): - graph = TestAlignmentGraph()._chain_graph() + graph = _chain_graph() (plan,) = graph.find_representation_subset_alignments( [1, 2], include_unaligned=False )[0] diff --git a/src/main/python/tests/scuro/test_chunked_leaf_execution.py b/src/main/python/tests/scuro/test_chunked_leaf_execution.py index 13a5635db45..73360ae3973 100644 --- a/src/main/python/tests/scuro/test_chunked_leaf_execution.py +++ b/src/main/python/tests/scuro/test_chunked_leaf_execution.py @@ -264,6 +264,17 @@ def test_unchunked_ragged_representation_is_padded(self): np.testing.assert_array_equal(masks[1], np.array([1.0, 1.0, 0.0])) np.testing.assert_array_equal(masks[2], np.array([1.0, 1.0, 1.0])) + def test_unchunked_ragged_representation_is_not_padded_when_disabled(self): + modality = _make_modality(chunk_size=None) + transformed = modality.apply_representation( + RaggedFrameOperation(), apply_padding=False + ) + + self.assertEqual( + [value.shape for value in transformed.data], + [(index % 3 + 1, 4) for index in range(NUM_INSTANCES)], + ) + def test_chunked_run_sees_every_instance(self): """End to end, the search must score the whole dataset. diff --git a/src/main/python/tests/scuro/test_contrastive_learning.py b/src/main/python/tests/scuro/test_contrastive_learning.py new file mode 100644 index 00000000000..76f053380ba --- /dev/null +++ b/src/main/python/tests/scuro/test_contrastive_learning.py @@ -0,0 +1,82 @@ +# ------------------------------------------------------------- +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +# ------------------------------------------------------------- + +import unittest +from types import SimpleNamespace + +from systemds.scuro.representations.contrastive_learning import ContrasitveLearning + + +def _modality(ids, prefix): + return SimpleNamespace( + data=[f"{prefix}{i}" for i in ids], metadata=[{"id": i} for i in ids] + ) + + +def _same_id(anchor_metadata, augmentation_metadata): + return anchor_metadata["id"] == augmentation_metadata["id"] + + +class TestContrastiveLearning(unittest.TestCase): + def test_pairs_every_anchor_with_every_augmentation(self): + (anchor,), (augmentation,), labels = ContrasitveLearning.execute( + _modality([0, 1], "a"), _modality([0, 1, 1], "b"), [], [], _same_id + ) + + self.assertEqual(len(labels), 6) + self.assertEqual(labels.count(True), 3) + self.assertEqual(anchor.data, ["a0"] * 3 + ["a1"] * 3) + self.assertEqual(augmentation.data, ["b0", "b1", "b1"] * 2) + + def test_max_negatives_per_positive_caps_negatives(self): + anchors, augmentations, labels = ContrasitveLearning.execute( + _modality([0, 1], "a"), + _modality([0, 1, 2, 3], "b"), + [_modality([0, 1], "x")], + [], + _same_id, + max_negatives_per_positive=1, + ) + + self.assertEqual(labels.count(True), 2) + self.assertEqual(labels.count(False), 2) + anchor, extension = anchors + for i, label in enumerate(labels): + self.assertEqual( + label, _same_id(anchor.metadata[i], augmentations[0].metadata[i]) + ) + self.assertEqual(extension.metadata[i], anchor.metadata[i]) + + def test_zero_negatives_per_positive_keeps_only_positives(self): + _, _, labels = ContrasitveLearning.execute( + _modality([0, 1], "a"), + _modality([0, 1, 2], "b"), + [], + [], + _same_id, + max_negatives_per_positive=0, + ) + + self.assertEqual(labels, [True, True]) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/main/python/tests/scuro/test_data_loaders.py b/src/main/python/tests/scuro/test_data_loaders.py index 6cd35e930a3..893d062cc5e 100644 --- a/src/main/python/tests/scuro/test_data_loaders.py +++ b/src/main/python/tests/scuro/test_data_loaders.py @@ -200,6 +200,25 @@ def test_image_loader_stats(self): self.assertEqual(stats.max_height, 120) self.assertEqual(stats.max_channels, 3) + def test_loaders_record_source_file_in_metadata(self): + for loader_class, modality_type in [ + (AudioLoader, ModalityType.AUDIO), + (VideoLoader, ModalityType.VIDEO), + (TextLoader, ModalityType.TEXT), + (ImageLoader, ModalityType.IMAGE), + ]: + with self.subTest(loader=loader_class.__name__): + loader = loader_class( + self.data_generator.get_modality_path(modality_type), + self.data_generator.indices, + ) + _, metadata = loader.load() + + self.assertEqual( + [md["file"] for md in metadata], + loader.get_file_names(self.data_generator.indices), + ) + # def test_timeseries_loader_loads_all_instances(self): # loader = TimeseriesLoader( # self.data_generator.get_modality_path(ModalityType.TIMESERIES), @@ -227,6 +246,40 @@ def test_image_loader_stats(self): # self.assertEqual(stats.num_signals, 2) +class TestChunkedDataLoaders(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.test_file_path = "test_chunked_data" + cls.data_generator = setup_data( + [ModalityType.VIDEO, ModalityType.IMAGE], 2, cls.test_file_path + ) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.test_file_path) + + def test_chunked_loaders_record_source_file_in_metadata(self): + for loader_class, modality_type in [ + (VideoLoader, ModalityType.VIDEO), + (ImageLoader, ModalityType.IMAGE), + ]: + with self.subTest(loader=loader_class.__name__): + loader = loader_class( + self.data_generator.get_modality_path(modality_type), + self.data_generator.indices, + chunk_size=1, + ) + files = [ + md["file"] + for _, metadata, _ in loader.iter_loaded_chunks() + for md in metadata + ] + + self.assertEqual( + files, loader.get_file_names(self.data_generator.indices) + ) + + class TestJSONLoaderFields(unittest.TestCase): @classmethod def setUpClass(cls): @@ -257,6 +310,15 @@ def test_list_of_fields_is_joined_in_order(self): self.assertEqual(data, ["a b utt 0", "a b utt 1"]) self.assertEqual(loader.stats.max_length, len("a b utt 0")) + def test_metadata_keeps_record_and_references_file_and_index(self): + _, metadata = JSONLoader(self.json_path, self.indices, "utterance").load() + + self.assertEqual([md["utterance"] for md in metadata], ["utt 0", "utt 1"]) + self.assertEqual( + [(md["file"], md["file_idx"]) for md in metadata], + [(self.json_path, "0"), (self.json_path, "1")], + ) + if __name__ == "__main__": unittest.main() diff --git a/src/main/python/tests/scuro/test_ocr_loader.py b/src/main/python/tests/scuro/test_ocr_loader.py new file mode 100644 index 00000000000..702fbf0e5ce --- /dev/null +++ b/src/main/python/tests/scuro/test_ocr_loader.py @@ -0,0 +1,81 @@ +# ------------------------------------------------------------- +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +# ------------------------------------------------------------- + +import shutil +import sys +import unittest +from unittest.mock import MagicMock, patch + +from systemds.scuro.modality.type import ModalityType +from tests.scuro.data_generator import setup_data + + +class TestOCRLoader(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.test_file_path = "test_ocr_data" + cls.num_instances = 2 + cls.data_generator = setup_data( + [ModalityType.IMAGE], cls.num_instances, cls.test_file_path + ) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.test_file_path) + + def _load(self, **kwargs): + pytesseract = MagicMock() + pytesseract.image_to_string.return_value = "Slide title\nfirst point\n" + with patch.dict(sys.modules, {"pytesseract": pytesseract}): + sys.modules.pop("systemds.scuro.dataloader.ocr_loader", None) + from systemds.scuro.dataloader.ocr_loader import OCRLoader + + loader = OCRLoader( + self.data_generator.get_modality_path(ModalityType.IMAGE), + self.data_generator.indices, + **kwargs, + ) + data, metadata = loader.load() + return loader, data, metadata, pytesseract + + def test_ocr_loader_returns_recognized_text_per_image(self): + loader, data, _, _ = self._load() + + self.assertEqual(loader.modality_type, ModalityType.TEXT) + self.assertEqual(data, ["Slide title first point"] * self.num_instances) + + def test_ocr_loader_records_source_file_in_metadata(self): + loader, _, metadata, _ = self._load() + + self.assertEqual( + [md["file"] for md in metadata], + loader.get_file_names(self.data_generator.indices), + ) + + def test_ocr_loader_forwards_language_and_config(self): + _, _, _, pytesseract = self._load(language="eng+deu", config="--psm 6") + + _, kwargs = pytesseract.image_to_string.call_args + self.assertEqual(kwargs, {"lang": "eng+deu", "config": "--psm 6"}) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/main/python/tests/scuro/test_paired_modality.py b/src/main/python/tests/scuro/test_paired_modality.py new file mode 100644 index 00000000000..bc5ba65156d --- /dev/null +++ b/src/main/python/tests/scuro/test_paired_modality.py @@ -0,0 +1,113 @@ +# ------------------------------------------------------------- +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +# ------------------------------------------------------------- + +import os +import shutil +import unittest +from types import SimpleNamespace + +import numpy as np +from sklearn.feature_extraction.text import CountVectorizer + +from systemds.scuro.dataloader.text_loader import TextLoader +from systemds.scuro.modality.paired_modality import ( + SHAPE_AFFECTING_OPERATIONS, + PairedModality, + PairedOperation, +) +from systemds.scuro.modality.type import ModalityType +from systemds.scuro.modality.unimodal_modality import UnimodalModality +from systemds.scuro.representations.bow import BoW + +CORPUS = [ + "the cat sat on the mat", + "dogs chase the ball in the park", + "a matrix is multiplied by a vector", +] +QUERIES = ["which cat sat", "matrix vector product"] + + +class TestPairedModality(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.test_file_path = "test_paired_data" + cls.paths = {} + for name, texts in [("corpus", CORPUS), ("queries", QUERIES)]: + path = os.path.join(cls.test_file_path, name) + os.makedirs(path) + for i, text in enumerate(texts): + with open(os.path.join(path, f"{i}.txt"), "w") as f: + f.write(text) + cls.paths[name] = (path + "/", [str(i) for i in range(len(texts))]) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.test_file_path) + + def _modality(self, name): + return UnimodalModality(TextLoader(*self.paths[name])) + + def test_paired_modality_rejects_invalid_modalities(self): + corpus = self._modality("corpus") + image = SimpleNamespace(modality_type=ModalityType.IMAGE) + + with self.assertRaises(ValueError): + PairedModality([corpus]) + with self.assertRaises(ValueError): + PairedModality([corpus, image]) + + def test_fitted_representation_encodes_queries_with_corpus_vocabulary(self): + pair = PairedModality( + [self._modality("corpus"), self._modality("queries")], + [None, SHAPE_AFFECTING_OPERATIONS], + ) + + transformed = pair.apply_representation( + BoW(params={"ngram_range": 1, "min_df": 1}) + ) + + corpus, queries = (np.asarray(m.data) for m in transformed.modalities) + vectorizer = CountVectorizer().fit(CORPUS) + np.testing.assert_array_equal(corpus, vectorizer.transform(CORPUS).toarray()) + np.testing.assert_array_equal(queries, vectorizer.transform(QUERIES).toarray()) + + def test_operation_is_skipped_where_not_allowed(self): + queries = self._modality("queries") + pair = PairedModality( + [self._modality("corpus"), queries], [None, [PairedOperation.CONTEXT]] + ) + + transformed = pair.apply_representation(BoW()) + + self.assertIs(transformed.modalities[1], queries) + self.assertIsNot(transformed.modalities[0], pair.modalities[0]) + + def test_data_is_distributed_to_contained_modalities(self): + pair = PairedModality([self._modality("corpus"), self._modality("queries")]) + + pair.data = [["corpus text"], ["query text"]] + + self.assertEqual(pair.data, [["corpus text"], ["query text"]]) + self.assertEqual(pair.get_default().data, ["corpus text"]) + + +if __name__ == "__main__": + unittest.main()