From 7210c08847cbffbffe396b480e84c2f1dc534ce3 Mon Sep 17 00:00:00 2001 From: nieprzecietny Date: Wed, 2 Dec 2026 01:08:35 +0100 Subject: [PATCH 1/2] fix(ml): a prediction carries the score of every label and the model description again ClassifyImage returned only the winning label: ImagePrediction.Scores and ModelInfo were left null, and a model saved without the Labels.txt entry (one not trained with this library) had no labels at all. An application that stores every score with the model's name, version and checksum got nothing to store. - ImageClassificationService.Predict fills Scores (label -> score) and ModelInfo. Labels come from Labels.txt and, when the model file has none, from the slot names of the loaded model; GetModelInfo uses the same fallback. - Scores stays null when the labels are not known or do not match the scores one to one. ModelInfo stays null when ModelFilePath is not configured or the file cannot be read: the pool decides where the model is loaded from, so a prediction never fails because of that file. - ModelHelper keeps the checksum of a model file until its size or write time changes. A prediction with the description of a 95 MB model takes about 70 ms instead of about 270 ms. - ModelHelper reads the version and the labels with read-only, shared access. The default access asked for write as well, so a read-only model file reported UNKNOWN and two concurrent reads could lock each other out. - PredictionEnginePoolAdapter.GetLabels returns the engine to the pool and answers with an empty array for a model whose scores are not named, instead of throwing. No public API changes. Tests cover the service, the model helper and the adapter against small models trained in the test; the docs and the package README describe the fields. --- docs-en/Libraries/MediatR/ML.md | 18 +- docs/Libraries/MediatR/ML.md | 18 +- .../Infrastructure/ClassificationService.cs | 85 +++++++++- .../Infrastructure/ModelHelper.cs | 31 +++- .../PredictionEnginePoolAdapter.cs | 26 ++- src/TailoredApps.Shared.MediatR.ML/README.md | 11 +- .../ImageClassificationServiceTests.cs | 152 ++++++++++++++++- .../ModelHelperTests.cs | 104 ++++++++++++ .../PredictionEnginePoolAdapterTests.cs | 160 ++++++++++++++++++ 9 files changed, 581 insertions(+), 24 deletions(-) create mode 100644 tests/TailoredApps.Shared.MediatR.ML.Tests/PredictionEnginePoolAdapterTests.cs diff --git a/docs-en/Libraries/MediatR/ML.md b/docs-en/Libraries/MediatR/ML.md index 430727fe..c5d857d4 100644 --- a/docs-en/Libraries/MediatR/ML.md +++ b/docs-en/Libraries/MediatR/ML.md @@ -104,12 +104,22 @@ public class ImageAnalysisController : ControllerBase prediction.FileName, prediction.PredictedLabel, prediction.PredictedScore, - Confidence = $"{prediction.PredictedScore:P2}" + Confidence = $"{prediction.PredictedScore:P2}", + prediction.Scores, // label -> score, for every label of the model + Model = prediction.ModelInfo?.Name, + ModelVersion = prediction.ModelInfo?.Version }); } } ``` +Besides the winning label, the prediction carries the score of every label (`Scores`) and the description of the model that produced it (`ModelInfo`: name, checksum, version, labels) - enough to store with a file which model judged it and how. + +- **Labels** are read from the `Labels.txt` entry that training writes into the model file. A model saved without it (one not trained with this library) gets its labels from the loaded model, in the order of its scores. +- **`Scores` is `null`** when the labels are not known or do not match the scores one to one. +- **`ModelInfo` is `null`** when `ImageClassification:ModelFilePath` is not configured or the file cannot be read. The pool decides where the model is loaded from, so a prediction does not depend on that file. +- **The checksum** of the model file is computed once and again only when the file's size or write time changes, so describing the model does not slow predictions down. + ### Model training ```csharp @@ -139,7 +149,7 @@ Training reads the files with the extension `.jpg` or `.png` from the source dir | `IImageClassificationService` | Interface | `Predict(byte[], fileName)`, `Train(images, folder, dest)`, `GetModelInfo()` | | `IPredictionEnginePoolAdapter` | Interface | Abstraction over the ML.NET `PredictionEnginePool` | | `ModelInfo` | Class | Model metadata: name, checksum, version, labels | -| `ImagePrediction` | Class | Prediction result: `PredictedLabel`, `PredictedScore`, `FileName`; `Scores` and `ModelInfo` are not filled by `ClassifyImage` | +| `ImagePrediction` | Class | Prediction result: `PredictedLabel`, `PredictedScore`, `FileName`, `Scores` (label -> score for every label; `null` when the labels are not known) and `ModelInfo` (`null` when `ModelFilePath` is not configured or unreadable) | | `InMemoryImageData` | Class | Model input data: the image as `byte[]` | | `ImagePredictionScore` | Class | Raw model output: `Score` (per class), `PredictedLabel` | | `ImageClassificationOptions` | Class | Options bound from the `ImageClassification` section: `ModelFilePath`, `TrainingRoot`, `ModelsRoot`, `MaxImageBytes` | @@ -207,6 +217,8 @@ var result = await _mediator.Send(new ClassifyImage }); // result.ImagePrediction.PredictedLabel — the predicted class // result.ImagePrediction.PredictedScore — confidence (0-1) +// result.ImagePrediction.Scores — label -> score for every label; null when the labels are not known +// result.ImagePrediction.ModelInfo — Name, Checksum, Version, Labels; null without a readable ModelFilePath ``` ### Model training @@ -225,6 +237,8 @@ var result = await _mediator.Send(new TrainImageClassificationModel - The model must be a ZIP file (ML.NET format) - The `ImageClassification` configuration section is required — a missing section throws `InvalidOperationException` when the options are first used - The model version and labels are stored in the archive as separate `Version.txt` and `Labels.txt` entries +- A model without `Labels.txt` (not trained with this library) gets its labels from the loaded model +- Check ImagePrediction.Scores and ImagePrediction.ModelInfo for null before using them - Training folder: each subfolder = one class, folder name = label - PredictionEnginePool is thread-safe — safe for concurrent use - PredictedScore ∈ [0,1] — the closer to 1, the higher the model's confidence diff --git a/docs/Libraries/MediatR/ML.md b/docs/Libraries/MediatR/ML.md index 3a632d09..10ba7db3 100644 --- a/docs/Libraries/MediatR/ML.md +++ b/docs/Libraries/MediatR/ML.md @@ -104,12 +104,22 @@ public class ImageAnalysisController : ControllerBase prediction.FileName, prediction.PredictedLabel, prediction.PredictedScore, - Confidence = $"{prediction.PredictedScore:P2}" + Confidence = $"{prediction.PredictedScore:P2}", + prediction.Scores, // etykieta -> wynik, dla każdej etykiety modelu + Model = prediction.ModelInfo?.Name, + ModelVersion = prediction.ModelInfo?.Version }); } } ``` +Oprócz zwycięskiej etykiety predykcja zawiera wynik każdej etykiety (`Scores`) i opis modelu, który ją wydał (`ModelInfo`: nazwa, checksum, wersja, etykiety) - tyle, ile trzeba, żeby zapisać przy pliku, który model go ocenił i jak. + +- **Etykiety** są czytane z wpisu `Labels.txt`, który trening zapisuje w pliku modelu. Model zapisany bez niego (nietrenowany tą biblioteką) dostaje etykiety z załadowanego modelu, w kolejności jego wyników. +- **`Scores` ma wartość `null`**, gdy etykiety nie są znane albo nie odpowiadają wynikom jeden do jednego. +- **`ModelInfo` ma wartość `null`**, gdy `ImageClassification:ModelFilePath` nie jest ustawione albo pliku nie da się odczytać. O tym, skąd ładowany jest model, decyduje pula, więc predykcja nie zależy od tego pliku. +- **Checksum** pliku modelu jest liczony raz i ponownie dopiero wtedy, gdy zmieni się rozmiar albo czas zapisu pliku, więc opis modelu nie spowalnia predykcji. + ### Trening modelu ```csharp @@ -139,7 +149,7 @@ Trening czyta pliki z rozszerzeniem `.jpg` lub `.png` z katalogu źródłowego i | `IImageClassificationService` | Interfejs | `Predict(byte[], fileName)`, `Train(images, folder, dest)`, `GetModelInfo()` | | `IPredictionEnginePoolAdapter` | Interfejs | Abstrakcja nad ML.NET `PredictionEnginePool` | | `ModelInfo` | Klasa | Metadane modelu: nazwa, checksum, wersja, etykiety | -| `ImagePrediction` | Klasa | Wynik predykcji: `PredictedLabel`, `PredictedScore`, `FileName`; `Scores` i `ModelInfo` nie są wypełniane przez `ClassifyImage` | +| `ImagePrediction` | Klasa | Wynik predykcji: `PredictedLabel`, `PredictedScore`, `FileName`, `Scores` (etykieta -> wynik dla każdej etykiety; `null`, gdy etykiety nie są znane) i `ModelInfo` (`null`, gdy `ModelFilePath` nie jest ustawione albo pliku nie da się odczytać) | | `InMemoryImageData` | Klasa | Dane wejściowe do modelu: obraz jako `byte[]` | | `ImagePredictionScore` | Klasa | Surowy wynik modelu: `Score` (per klasa), `PredictedLabel` | | `ImageClassificationOptions` | Klasa | Opcje wiązane z sekcji `ImageClassification`: `ModelFilePath`, `TrainingRoot`, `ModelsRoot`, `MaxImageBytes` | @@ -207,6 +217,8 @@ var result = await _mediator.Send(new ClassifyImage }); // result.ImagePrediction.PredictedLabel — przewidywana klasa // result.ImagePrediction.PredictedScore — pewność (0-1) +// result.ImagePrediction.Scores — etykieta -> wynik dla każdej etykiety; null, gdy etykiety nie są znane +// result.ImagePrediction.ModelInfo — Name, Checksum, Version, Labels; null bez czytelnego ModelFilePath ``` ### Trening modelu @@ -225,6 +237,8 @@ var result = await _mediator.Send(new TrainImageClassificationModel - Model musi być plikiem ZIP (ML.NET format) - Sekcja konfiguracji `ImageClassification` jest wymagana — jej brak powoduje `InvalidOperationException` przy pierwszym użyciu opcji - Wersja i etykiety modelu są zapisywane w archiwum jako osobne wpisy `Version.txt` i `Labels.txt` +- Model bez `Labels.txt` (nietrenowany tą biblioteką) dostaje etykiety z załadowanego modelu +- Przed użyciem sprawdź, czy ImagePrediction.Scores i ImagePrediction.ModelInfo nie mają wartości null - Folder treningowy: każdy podfolder = jedna klasa, nazwa folderu = etykieta - PredictionEnginePool jest thread-safe — bezpieczne współbieżne użycie - PredictedScore ∈ [0,1] — im bliżej 1, tym wyższe zaufanie modelu diff --git a/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ClassificationService.cs b/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ClassificationService.cs index 7987546f..9b13b492 100644 --- a/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ClassificationService.cs +++ b/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ClassificationService.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.IO; using System.Linq; using System.Text; using Microsoft.ML; @@ -36,13 +37,17 @@ public ImageClassificationService(IPredictionEnginePoolAdapter /// A object containing the model's name, checksum, version, and labels. + /// + /// The labels come from the Labels.txt entry of the model file and, for a model saved without that + /// entry, from the loaded model itself. + /// public ModelInfo GetModelInfo() { return new ModelInfo( modelInfoService.ModelFileName, modelInfoService.ModelChecksum, modelInfoService.ModelVersion, - modelInfoService.Labels + GetLabels() ); } @@ -51,29 +56,91 @@ public ModelInfo GetModelInfo() /// /// The raw byte content of the image to classify. /// The original file name of the image, used for identification in the result. - /// An containing the predicted label and score. + /// + /// An with the predicted label and its score, the score of every label + /// () and the description of the model (). + /// + /// + /// is when the labels of the model are not known + /// or do not match its scores one to one. is + /// when ImageClassification:ModelFilePath is not configured or the file cannot be read: the pool decides + /// where the model is loaded from, so a prediction does not depend on that file. + /// public ImagePrediction Predict(byte[] image, string? fileName) { var imageData = new InMemoryImageData(image, null, fileName); ImagePredictionScore prediction = predictionEnginePool.Predict(imageData); - // ModelInfo modelInfo = GetModelInfo(); + var scores = prediction.Score ?? throw new InvalidOperationException("The model returned no scores."); + var predictedScore = scores.Max(); + var labels = GetLabels(); ImagePrediction imagePrediction = new ImagePrediction() { - PredictedScore = (prediction.Score ?? throw new InvalidOperationException("The model returned no scores.")).Max(), + PredictedScore = predictedScore, FileName = fileName, PredictedLabel = prediction.PredictedLabel, - //ModelInfo = modelInfo, - //Scores = modelInfo.Labels - // .Zip(prediction.Score, (key, value) => new { key, value }) - // .ToDictionary(x => x.key, x => x.value) - + ModelInfo = DescribeModel(labels), + Scores = MapScores(labels, scores) } ; return imagePrediction; } + // Labels in the order of the model's scores: the Labels.txt entry that training writes into the model + // file or, for a model saved without it, the slot names of the loaded model. + private string[] GetLabels() + { + var labels = modelInfoService.Labels; + if (labels != null && labels.Length > 0) + { + return labels; + } + + return predictionEnginePool.GetLabels() ?? Array.Empty(); + } + + private ModelInfo? DescribeModel(string[] labels) + { + if (string.IsNullOrWhiteSpace(modelInfoService.ModelFilePath)) + { + return null; + } + + try + { + return new ModelInfo( + modelInfoService.ModelFileName, + modelInfoService.ModelChecksum, + modelInfoService.ModelVersion, + labels + ); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return null; + } + } + + private static Dictionary? MapScores(string[] labels, float[] scores) + { + if (labels.Length != scores.Length) + { + return null; + } + + var result = new Dictionary(labels.Length); + for (var i = 0; i < labels.Length; i++) + { + if (!result.TryAdd(labels[i], scores[i])) + { + return null; + } + } + + return result; + } + /// /// Trains an image classification model using the provided image dataset and saves it to disk. /// diff --git a/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ModelHelper.cs b/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ModelHelper.cs index 72aa0525..50930800 100644 --- a/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ModelHelper.cs +++ b/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ModelHelper.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Concurrent; using System.IO; using System.IO.Compression; using System.Linq; @@ -21,6 +22,11 @@ public class ModelHelper : IModelHelper /// The name of the labels entry stored inside the model zip archive. const string labelsFileName = "Labels.txt"; + // Checksums by full path. A model is described with every prediction, and hashing a model of about + // 100 MB each time would take longer than the prediction itself; the file is hashed again only when its + // size or write time changes. + private static readonly ConcurrentDictionary checksums = new(StringComparer.Ordinal); + /// /// Adds a timestamp-based version entry to the model zip archive. /// @@ -92,10 +98,20 @@ public void AddLabels(string modelFilePath, string[] labels) /// A lowercase hexadecimal string representing the MD5 hash of the file. public string GetChecksum(string modelFilePath) { + var file = new FileInfo(modelFilePath); + if (file.Exists + && checksums.TryGetValue(file.FullName, out var known) + && known.Length == file.Length + && known.LastWriteTimeUtc == file.LastWriteTimeUtc) + { + return known.Checksum; + } + using var md5 = MD5.Create(); using var stream = File.OpenRead(modelFilePath); - var checksum = md5.ComputeHash(stream); - return BitConverter.ToString(checksum).Replace("-", string.Empty).ToLower(); + var checksum = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", string.Empty).ToLower(); + checksums[file.FullName] = (file.Length, file.LastWriteTimeUtc, checksum); + return checksum; } /// @@ -109,7 +125,7 @@ public string GetVersion(string modelFilePath) { try { - using FileStream fileStream = new FileStream(modelFilePath, FileMode.Open); + using FileStream fileStream = OpenForReading(modelFilePath); using ZipArchive archive = new ZipArchive(fileStream, ZipArchiveMode.Read); ZipArchiveEntry? zipArchiveEntry = archive.GetEntry(versionFileName); if (zipArchiveEntry != null) @@ -136,7 +152,7 @@ public string[] GetLabels(string modelFilePath) { try { - using FileStream fileStream = new FileStream(modelFilePath, FileMode.Open); + using FileStream fileStream = OpenForReading(modelFilePath); using ZipArchive archive = new ZipArchive(fileStream, ZipArchiveMode.Read); ZipArchiveEntry? zipArchiveEntry = archive.GetEntry(labelsFileName); if (zipArchiveEntry != null) @@ -151,4 +167,11 @@ public string[] GetLabels(string modelFilePath) } return new string[0]; } + + // Read access only, shared with other readers: the default of FileMode.Open asks for write access too, so + // a read-only file could not be read and two requests reading at the same time locked each other out. + private static FileStream OpenForReading(string modelFilePath) + { + return new FileStream(modelFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); + } } diff --git a/src/TailoredApps.Shared.MediatR.ML/Infrastructure/PredictionEnginePoolAdapter.cs b/src/TailoredApps.Shared.MediatR.ML/Infrastructure/PredictionEnginePoolAdapter.cs index 3f8739b3..aee38bcf 100644 --- a/src/TailoredApps.Shared.MediatR.ML/Infrastructure/PredictionEnginePoolAdapter.cs +++ b/src/TailoredApps.Shared.MediatR.ML/Infrastructure/PredictionEnginePoolAdapter.cs @@ -32,13 +32,31 @@ public PredictionEnginePoolAdapter(PredictionEnginePool pred /// /// Retrieves the class label names from the prediction engine's output schema Score slot annotations. /// - /// An array of label name strings corresponding to the Score column slots. + /// + /// An array of label name strings corresponding to the Score column slots; empty when the model has no + /// Score column or its slots are not named. + /// public string[] GetLabels() { - var labelBuffer = new VBuffer>(); var predictionEngine = predictionEnginePool.GetPredictionEngine(); - predictionEngine.OutputSchema["Score"].Annotations.GetValue("SlotNames", ref labelBuffer); - return labelBuffer.DenseValues().Select(l => l.ToString()).ToArray(); + try + { + var score = predictionEngine.OutputSchema.GetColumnOrNull("Score"); + if (score == null || score.Value.Annotations.Schema.GetColumnOrNull("SlotNames") == null) + { + return Array.Empty(); + } + + var labelBuffer = new VBuffer>(); + score.Value.Annotations.GetValue("SlotNames", ref labelBuffer); + return labelBuffer.DenseValues().Select(l => l.ToString()).ToArray(); + } + finally + { + // The engine is only borrowed: without this every call would leave the pool one engine short + // and make it build another. + predictionEnginePool.ReturnPredictionEngine(predictionEngine); + } } /// diff --git a/src/TailoredApps.Shared.MediatR.ML/README.md b/src/TailoredApps.Shared.MediatR.ML/README.md index df15033f..77894659 100644 --- a/src/TailoredApps.Shared.MediatR.ML/README.md +++ b/src/TailoredApps.Shared.MediatR.ML/README.md @@ -41,6 +41,8 @@ using TailoredApps.Shared.MediatR.ImageClassification.Domain.DataModel.Message.C var classified = await mediator.Send(new ClassifyImage { FileByteArray = imageBytes, FileName = "photo.jpg" }); var label = classified.ImagePrediction?.PredictedLabel; var score = classified.ImagePrediction?.PredictedScore; +var scores = classified.ImagePrediction?.Scores; // label -> score, for every label of the model +var model = classified.ImagePrediction?.ModelInfo; // Name, Checksum, Version, Labels var trained = await mediator.Send(new TrainImageClassificationModel { @@ -76,8 +78,13 @@ The `ImageClassification` section: - The section is required: without it the options throw `InvalidOperationException` when first used. - `ClassifyImage` throws `ArgumentException` for empty content, for content over `MaxImageBytes` and for - content that does not start with a JPEG or PNG signature. Only `FileName`, `PredictedLabel` and - `PredictedScore` of the returned `ImagePrediction` are filled; `Scores` and `ModelInfo` stay `null`. + content that does not start with a JPEG or PNG signature. +- The returned `ImagePrediction` has `FileName`, `PredictedLabel` and `PredictedScore`, the score of every label + in `Scores` and the description of the model in `ModelInfo`. Labels come from the `Labels.txt` entry of the + model file; a model saved without it (not trained with this library) gets them from the loaded model. + `Scores` is `null` when the labels are not known or do not match the scores one to one. `ModelInfo` is `null` + when `ModelFilePath` is not configured or the file cannot be read; the prediction itself does not need it. +- The checksum of a model file is computed once and again only when the file's size or write time changes. - Training paths are resolved against `TrainingRoot` and `ModelsRoot`. A path outside its root throws `ArgumentException`; a root that is not configured throws `InvalidOperationException`. - Training reads files with the extension `.jpg` or `.png` from `Source` and its sub-folders and uses the name diff --git a/tests/TailoredApps.Shared.MediatR.ML.Tests/ImageClassificationServiceTests.cs b/tests/TailoredApps.Shared.MediatR.ML.Tests/ImageClassificationServiceTests.cs index fd05f2e0..5cace505 100644 --- a/tests/TailoredApps.Shared.MediatR.ML.Tests/ImageClassificationServiceTests.cs +++ b/tests/TailoredApps.Shared.MediatR.ML.Tests/ImageClassificationServiceTests.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using Moq; using TailoredApps.Shared.MediatR.ImageClassification.Infrastructure; using TailoredApps.Shared.MediatR.ImageClassification.Interfaces.Domain.Models; @@ -21,7 +22,7 @@ public ImageClassificationServiceTests() } [Fact] - public void When_Predict_Is_Called_Should_Map_Prediction_To_ImagePrediction() + public void When_Model_Has_No_Known_Labels_And_No_Configured_File_Predict_Should_Leave_Scores_And_ModelInfo_Null() { // arrange var imageBytes = new byte[] { 1, 2, 3 }; @@ -44,6 +45,122 @@ public void When_Predict_Is_Called_Should_Map_Prediction_To_ImagePrediction() Assert.Null(prediction.ModelInfo); } + [Fact] + public void When_Model_File_Has_Labels_Predict_Should_Return_Every_Score_And_The_Model_Description() + { + // arrange + var labels = new[] { "blue", "green", "red" }; + SetupModelFile(labels); + SetupPrediction("green", 0.1f, 0.7f, 0.2f); + + // act + var prediction = sut.Predict(new byte[] { 1, 2, 3 }, "testgreen.png"); + + // assert + Assert.Equal("green", prediction.PredictedLabel); + Assert.Equal(0.7f, prediction.PredictedScore); + Assert.NotNull(prediction.Scores); + Assert.Equal(3, prediction.Scores.Count); + Assert.Equal(0.1f, prediction.Scores["blue"]); + Assert.Equal(0.7f, prediction.Scores["green"]); + Assert.Equal(0.2f, prediction.Scores["red"]); + Assert.NotNull(prediction.ModelInfo); + Assert.Equal("image.zip", prediction.ModelInfo.Name); + Assert.Equal("abc123", prediction.ModelInfo.Checksum); + Assert.Equal("20260820.101010", prediction.ModelInfo.Version); + Assert.Same(labels, prediction.ModelInfo.Labels); + predictionEnginePoolMock.Verify(p => p.GetLabels(), Times.Never); + } + + [Fact] + public void When_Model_File_Has_No_Labels_Predict_Should_Take_Them_From_The_Loaded_Model() + { + // arrange + var labels = new[] { "blue", "green", "red" }; + SetupModelFile(Array.Empty()); + predictionEnginePoolMock.Setup(p => p.GetLabels()).Returns(labels); + SetupPrediction("red", 0.05f, 0.15f, 0.8f); + + // act + var prediction = sut.Predict(new byte[] { 1, 2, 3 }, "testred.png"); + + // assert + Assert.NotNull(prediction.Scores); + Assert.Equal(0.05f, prediction.Scores["blue"]); + Assert.Equal(0.15f, prediction.Scores["green"]); + Assert.Equal(0.8f, prediction.Scores["red"]); + Assert.NotNull(prediction.ModelInfo); + Assert.Same(labels, prediction.ModelInfo.Labels); + } + + [Fact] + public void When_Model_File_Is_Not_Configured_Predict_Should_Return_Scores_Without_Reading_The_File() + { + // arrange + predictionEnginePoolMock.Setup(p => p.GetLabels()).Returns(new[] { "blue", "green", "red" }); + SetupPrediction("blue", 0.6f, 0.3f, 0.1f); + + // act + var prediction = sut.Predict(new byte[] { 1, 2, 3 }, "testblue.png"); + + // assert + Assert.NotNull(prediction.Scores); + Assert.Equal(0.6f, prediction.Scores["blue"]); + Assert.Null(prediction.ModelInfo); + modelInfoServiceMock.VerifyGet(m => m.ModelChecksum, Times.Never); + modelInfoServiceMock.VerifyGet(m => m.ModelVersion, Times.Never); + } + + [Fact] + public void When_Model_File_Cannot_Be_Read_Predict_Should_Still_Return_The_Prediction() + { + // arrange + SetupModelFile(new[] { "blue", "green", "red" }); + modelInfoServiceMock.SetupGet(m => m.ModelChecksum).Throws(new FileNotFoundException("no model")); + SetupPrediction("green", 0.1f, 0.7f, 0.2f); + + // act + var prediction = sut.Predict(new byte[] { 1, 2, 3 }, "testgreen.png"); + + // assert + Assert.Equal("green", prediction.PredictedLabel); + Assert.Equal(0.7f, prediction.PredictedScore); + Assert.NotNull(prediction.Scores); + Assert.Null(prediction.ModelInfo); + } + + [Fact] + public void When_Labels_Do_Not_Match_The_Scores_Predict_Should_Leave_Scores_Null() + { + // arrange + SetupModelFile(new[] { "blue", "green" }); + SetupPrediction("red", 0.1f, 0.2f, 0.7f); + + // act + var prediction = sut.Predict(new byte[] { 1, 2, 3 }, "testred.png"); + + // assert + Assert.Equal("red", prediction.PredictedLabel); + Assert.Equal(0.7f, prediction.PredictedScore); + Assert.Null(prediction.Scores); + Assert.NotNull(prediction.ModelInfo); + } + + [Fact] + public void When_A_Label_Repeats_Predict_Should_Leave_Scores_Null() + { + // arrange + SetupModelFile(new[] { "blue", "blue", "red" }); + SetupPrediction("red", 0.1f, 0.2f, 0.7f); + + // act + var prediction = sut.Predict(new byte[] { 1, 2, 3 }, "testred.png"); + + // assert + Assert.Equal(0.7f, prediction.PredictedScore); + Assert.Null(prediction.Scores); + } + [Fact] public void When_Predict_Is_Called_Should_Forward_Image_Bytes_And_FileName_To_Engine() { @@ -98,5 +215,38 @@ public void When_GetModelInfo_Is_Called_Should_Map_Values_From_Model_Info_Servic Assert.Equal("abc123", modelInfo.Checksum); Assert.Equal("20260820.101010", modelInfo.Version); Assert.Same(labels, modelInfo.Labels); + predictionEnginePoolMock.Verify(p => p.GetLabels(), Times.Never); + } + + [Fact] + public void When_Model_File_Has_No_Labels_GetModelInfo_Should_Take_Them_From_The_Loaded_Model() + { + // arrange + var labels = new[] { "blue", "green", "red" }; + SetupModelFile(Array.Empty()); + predictionEnginePoolMock.Setup(p => p.GetLabels()).Returns(labels); + + // act + var modelInfo = sut.GetModelInfo(); + + // assert + Assert.Equal("image.zip", modelInfo.Name); + Assert.Same(labels, modelInfo.Labels); + } + + private void SetupModelFile(string[] labels) + { + modelInfoServiceMock.SetupGet(m => m.ModelFilePath).Returns("models/image.zip"); + modelInfoServiceMock.SetupGet(m => m.ModelFileName).Returns("image.zip"); + modelInfoServiceMock.SetupGet(m => m.ModelChecksum).Returns("abc123"); + modelInfoServiceMock.SetupGet(m => m.ModelVersion).Returns("20260820.101010"); + modelInfoServiceMock.SetupGet(m => m.Labels).Returns(labels); + } + + private void SetupPrediction(string predictedLabel, params float[] scores) + { + predictionEnginePoolMock + .Setup(p => p.Predict(It.IsAny())) + .Returns(new ImagePredictionScore { PredictedLabel = predictedLabel, Score = scores }); } } diff --git a/tests/TailoredApps.Shared.MediatR.ML.Tests/ModelHelperTests.cs b/tests/TailoredApps.Shared.MediatR.ML.Tests/ModelHelperTests.cs index 566c7e47..ec2cd70a 100644 --- a/tests/TailoredApps.Shared.MediatR.ML.Tests/ModelHelperTests.cs +++ b/tests/TailoredApps.Shared.MediatR.ML.Tests/ModelHelperTests.cs @@ -48,6 +48,110 @@ public void When_GetChecksum_Is_Called_Should_Return_Lower_Case_Md5_Of_File_Cont Assert.Equal("5d41402abc4b2a76b9719d911017c592", checksum); } + [Fact] + public void When_File_Content_Changes_GetChecksum_Should_Return_The_New_Checksum() + { + // arrange + var path = Path.Combine(workFolder, "changing.bin"); + File.WriteAllText(path, "hello"); + var first = sut.GetChecksum(path); + + // act + File.WriteAllText(path, "hello world"); + var second = sut.GetChecksum(path); + + // assert + Assert.Equal("5d41402abc4b2a76b9719d911017c592", first); + Assert.Equal("5eb63bbbe01eeed093cb22bb8f5acdc3", second); + } + + [Fact] + public void When_File_Of_The_Same_Size_Is_Written_Later_GetChecksum_Should_Return_The_New_Checksum() + { + // arrange + var path = Path.Combine(workFolder, "same-size.bin"); + File.WriteAllText(path, "hello"); + File.SetLastWriteTimeUtc(path, new DateTime(2026, 1, 1, 10, 0, 0, DateTimeKind.Utc)); + var first = sut.GetChecksum(path); + + // act + File.WriteAllText(path, "jello"); + File.SetLastWriteTimeUtc(path, new DateTime(2026, 1, 1, 10, 0, 1, DateTimeKind.Utc)); + var second = sut.GetChecksum(path); + + // assert + Assert.Equal("5d41402abc4b2a76b9719d911017c592", first); + Assert.NotEqual(first, second); + } + + [Fact] + public void When_File_Is_Unchanged_GetChecksum_Should_Return_The_Same_Checksum_From_Another_Instance() + { + // arrange + var path = Path.Combine(workFolder, "unchanged.bin"); + File.WriteAllText(path, "hello"); + var first = sut.GetChecksum(path); + + // act + var second = new ModelHelper().GetChecksum(path); + + // assert + Assert.Equal(first, second); + } + + [Fact] + public void When_File_Does_Not_Exist_GetChecksum_Should_Throw_FileNotFoundException() + { + // arrange + var path = Path.Combine(workFolder, "missing.bin"); + + // act & assert + Assert.Throws(() => sut.GetChecksum(path)); + } + + [Fact] + public void When_Archive_Is_Read_Only_Should_Still_Read_Version_And_Labels() + { + // arrange + var path = CreateEmptyZip(); + var version = sut.AddVersion(path); + sut.AddLabels(path, new[] { "red", "green" }); + File.SetAttributes(path, FileAttributes.ReadOnly); + + try + { + // act + var readVersion = sut.GetVersion(path); + var readLabels = sut.GetLabels(path); + + // assert + Assert.Equal(version, readVersion); + Assert.Equal(new[] { "red", "green" }, readLabels); + } + finally + { + File.SetAttributes(path, FileAttributes.Normal); + } + } + + [Fact] + public void When_Archive_Is_Being_Read_By_Another_Reader_Should_Still_Read_Version_And_Labels() + { + // arrange + var path = CreateEmptyZip(); + var version = sut.AddVersion(path); + sut.AddLabels(path, new[] { "red", "green" }); + using var otherReader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); + + // act + var readVersion = sut.GetVersion(path); + var readLabels = sut.GetLabels(path); + + // assert + Assert.Equal(version, readVersion); + Assert.Equal(new[] { "red", "green" }, readLabels); + } + [Fact] public void When_AddVersion_Is_Called_Should_Return_Timestamp_Version_And_Store_It_In_Archive() { diff --git a/tests/TailoredApps.Shared.MediatR.ML.Tests/PredictionEnginePoolAdapterTests.cs b/tests/TailoredApps.Shared.MediatR.ML.Tests/PredictionEnginePoolAdapterTests.cs new file mode 100644 index 00000000..bddff95e --- /dev/null +++ b/tests/TailoredApps.Shared.MediatR.ML.Tests/PredictionEnginePoolAdapterTests.cs @@ -0,0 +1,160 @@ +using System; +using System.IO; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.ML; +using Microsoft.ML; +using Microsoft.ML.Data; +using TailoredApps.Shared.MediatR.ImageClassification.Infrastructure; +using TailoredApps.Shared.MediatR.ImageClassification.Interfaces.Infrastructure; +using Xunit; + +namespace TailoredApps.Shared.MediatR.ML.Tests; + +/// +/// The adapter against real ML.NET models: small ones trained here on a handful of numbers, saved to a file +/// and loaded through the prediction engine pool the way an application loads its model. +/// +public class PredictionEnginePoolAdapterTests : IDisposable +{ + private readonly string workFolder; + + public PredictionEnginePoolAdapterTests() + { + workFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(workFolder); + } + + public void Dispose() + { + if (Directory.Exists(workFolder)) + { + Directory.Delete(workFolder, recursive: true); + } + } + + [Fact] + public void When_Model_Is_A_Classifier_GetLabels_Should_Return_Its_Labels_In_Score_Order() + { + // arrange + using var provider = BuildProvider(SaveClassifier()); + var sut = provider.GetRequiredService>(); + + // act + var labels = sut.GetLabels(); + var prediction = sut.Predict(new ColorSample { Red = 0.05f, Green = 0.1f, Blue = 0.95f }); + + // assert + Assert.Equal(new[] { "blue", "green", "red" }, labels); + Assert.Equal("blue", prediction.PredictedLabel); + Assert.Equal(labels.Length, prediction.Score.Length); + Assert.Equal("blue", labels[Array.IndexOf(prediction.Score, prediction.Score.Max())]); + } + + [Fact] + public void When_GetLabels_Is_Called_Many_Times_Should_Keep_Returning_The_Same_Labels() + { + // arrange + using var provider = BuildProvider(SaveClassifier()); + var sut = provider.GetRequiredService>(); + + // act + var all = Enumerable.Range(0, 50).Select(_ => sut.GetLabels()).ToList(); + + // assert + Assert.All(all, labels => Assert.Equal(new[] { "blue", "green", "red" }, labels)); + } + + [Fact] + public void When_Model_Scores_Are_Not_Named_GetLabels_Should_Return_Empty_Array() + { + // arrange + using var provider = BuildProvider(SaveRegression()); + var sut = provider.GetRequiredService>(); + + // act + var labels = sut.GetLabels(); + + // assert + Assert.Empty(labels); + } + + private ServiceProvider BuildProvider(string modelPath) where TPrediction : class, new() + { + var services = new ServiceCollection(); + services.AddPredictionEnginePool() + .FromFile(modelPath, watchForChanges: false) + .AddAdapter(); + return services.BuildServiceProvider(); + } + + private string SaveClassifier() + { + var mlContext = new MLContext(seed: 1); + var data = mlContext.Data.LoadFromEnumerable(Samples()); + var pipeline = mlContext.Transforms.Conversion + .MapValueToKey("LabelAsKey", nameof(ColorSample.Label), keyOrdinality: Microsoft.ML.Transforms.ValueToKeyMappingEstimator.KeyOrdinality.ByValue) + .Append(mlContext.Transforms.Concatenate("Features", nameof(ColorSample.Red), nameof(ColorSample.Green), nameof(ColorSample.Blue))) + .Append(mlContext.MulticlassClassification.Trainers.SdcaMaximumEntropy("LabelAsKey", "Features")) + .Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel", "PredictedLabel")); + + return Save(mlContext, pipeline.Fit(data), data.Schema, "classifier.zip"); + } + + private string SaveRegression() + { + var mlContext = new MLContext(seed: 1); + var data = mlContext.Data.LoadFromEnumerable(Samples()); + var pipeline = mlContext.Transforms + .Concatenate("Features", nameof(ColorSample.Red), nameof(ColorSample.Green), nameof(ColorSample.Blue)) + .Append(mlContext.Regression.Trainers.Sdca(nameof(ColorSample.Brightness), "Features")); + + return Save(mlContext, pipeline.Fit(data), data.Schema, "regression.zip"); + } + + private string Save(MLContext mlContext, ITransformer model, DataViewSchema schema, string fileName) + { + var path = Path.Combine(workFolder, fileName); + mlContext.Model.Save(model, schema, path); + return path; + } + + private static ColorSample[] Samples() + { + var random = new Random(1); + float High() => 0.8f + (float)random.NextDouble() * 0.2f; + float Low() => (float)random.NextDouble() * 0.2f; + + return Enumerable.Range(0, 40).SelectMany(_ => new[] + { + new ColorSample { Red = High(), Green = Low(), Blue = Low(), Label = "red", Brightness = 0.3f }, + new ColorSample { Red = Low(), Green = High(), Blue = Low(), Label = "green", Brightness = 0.6f }, + new ColorSample { Red = Low(), Green = Low(), Blue = High(), Label = "blue", Brightness = 0.1f }, + }).ToArray(); + } + + public class ColorSample + { + public float Red { get; set; } + + public float Green { get; set; } + + public float Blue { get; set; } + + public string Label { get; set; } + + public float Brightness { get; set; } + } + + public class ColorPrediction + { + public string PredictedLabel { get; set; } + + public float[] Score { get; set; } + } + + public class BrightnessPrediction + { + public float Score { get; set; } + } +} From d69b72b8e9661f772b8c84f353d00f59c136fb44 Mon Sep 17 00:00:00 2001 From: nieprzecietny Date: Wed, 2 Dec 2026 01:19:16 +0100 Subject: [PATCH 2/2] fix(ml): labels and model description of a prediction come from the model that made it Review of the previous commit: the labels were read from the Labels.txt entry of the model file and the description from that file at the time of every prediction. When the file is replaced while the pool keeps the model it loaded (watchForChanges: false), a model with as many classes but other labels would have its scores attributed to the wrong labels, and the description would name the replacement. - The adapter the library registers predicts and reports, in one call, the labels of the engine that made the prediction and the model the pool held meanwhile (an internal contract; no public API change). - Scores are keyed by those labels only. Labels.txt is no longer used for a prediction; GetModelInfo(), which describes the file, still reads it and falls back to the loaded model. - The file is described once for every loaded model, when that model is first used, and the description is kept for as long as the model lives. A replaced file changes the description only after the pool reloads it. - ModelInfo stays null when the pool replaced the model while the prediction ran, and with an adapter other than the library's, because the model behind it cannot be told apart from the file. Tests: the service against an adapter that reports its model (replaced file, reloaded model, model swapped during a prediction), and the whole path against a real pool: a model of colours is loaded, a model of shapes with its own Labels.txt takes the file's place, and predictions keep the colours and the first checksum. --- docs-en/Libraries/MediatR/ML.md | 16 +- docs/Libraries/MediatR/ML.md | 16 +- .../Infrastructure/ClassificationService.cs | 94 ++++++--- .../Infrastructure/ModelBoundPrediction.cs | 42 ++++ .../PredictionEnginePoolAdapter.cs | 49 ++++- src/TailoredApps.Shared.MediatR.ML/README.md | 14 +- .../ImageClassificationServiceTests.cs | 180 ++++++++++++++---- .../PredictionEnginePoolAdapterTests.cs | 76 ++++++++ 8 files changed, 399 insertions(+), 88 deletions(-) create mode 100644 src/TailoredApps.Shared.MediatR.ML/Infrastructure/ModelBoundPrediction.cs diff --git a/docs-en/Libraries/MediatR/ML.md b/docs-en/Libraries/MediatR/ML.md index c5d857d4..d966aa57 100644 --- a/docs-en/Libraries/MediatR/ML.md +++ b/docs-en/Libraries/MediatR/ML.md @@ -115,9 +115,10 @@ public class ImageAnalysisController : ControllerBase Besides the winning label, the prediction carries the score of every label (`Scores`) and the description of the model that produced it (`ModelInfo`: name, checksum, version, labels) - enough to store with a file which model judged it and how. -- **Labels** are read from the `Labels.txt` entry that training writes into the model file. A model saved without it (one not trained with this library) gets its labels from the loaded model, in the order of its scores. -- **`Scores` is `null`** when the labels are not known or do not match the scores one to one. -- **`ModelInfo` is `null`** when `ImageClassification:ModelFilePath` is not configured or the file cannot be read. The pool decides where the model is loaded from, so a prediction does not depend on that file. +- **Both belong to the model that made the prediction.** The labels are the ones the loaded model names its scores with. The file at `ImageClassification:ModelFilePath` is described once for every loaded model, when that model is first used. When the file is replaced and the pool does not reload it (`watchForChanges: false`), predictions keep the labels and the description of the model that still makes them. +- **`Scores` is `null`** when the model does not name its scores or the names do not match them one to one. +- **`ModelInfo` is `null`** when `ImageClassification:ModelFilePath` is not configured or the file cannot be read, when the pool replaced the model while the prediction ran, and with your own `IPredictionEnginePoolAdapter`, because the model behind it cannot be told apart from the file. The pool decides where the model is loaded from, so a prediction never depends on that file. +- **`GetModelInfo()`** describes the file as it is now. Its labels come from the `Labels.txt` entry that training writes; a file saved without it (one not trained with this library) gets the labels of the loaded model. - **The checksum** of the model file is computed once and again only when the file's size or write time changes, so describing the model does not slow predictions down. ### Model training @@ -149,7 +150,7 @@ Training reads the files with the extension `.jpg` or `.png` from the source dir | `IImageClassificationService` | Interface | `Predict(byte[], fileName)`, `Train(images, folder, dest)`, `GetModelInfo()` | | `IPredictionEnginePoolAdapter` | Interface | Abstraction over the ML.NET `PredictionEnginePool` | | `ModelInfo` | Class | Model metadata: name, checksum, version, labels | -| `ImagePrediction` | Class | Prediction result: `PredictedLabel`, `PredictedScore`, `FileName`, `Scores` (label -> score for every label; `null` when the labels are not known) and `ModelInfo` (`null` when `ModelFilePath` is not configured or unreadable) | +| `ImagePrediction` | Class | Prediction result: `PredictedLabel`, `PredictedScore`, `FileName`, `Scores` (label -> score for every label; `null` when the model does not name its scores) and `ModelInfo` (the model that made the prediction; `null` when it cannot be described) | | `InMemoryImageData` | Class | Model input data: the image as `byte[]` | | `ImagePredictionScore` | Class | Raw model output: `Score` (per class), `PredictedLabel` | | `ImageClassificationOptions` | Class | Options bound from the `ImageClassification` section: `ModelFilePath`, `TrainingRoot`, `ModelsRoot`, `MaxImageBytes` | @@ -217,8 +218,8 @@ var result = await _mediator.Send(new ClassifyImage }); // result.ImagePrediction.PredictedLabel — the predicted class // result.ImagePrediction.PredictedScore — confidence (0-1) -// result.ImagePrediction.Scores — label -> score for every label; null when the labels are not known -// result.ImagePrediction.ModelInfo — Name, Checksum, Version, Labels; null without a readable ModelFilePath +// result.ImagePrediction.Scores — label -> score for every label; null when the model does not name its scores +// result.ImagePrediction.ModelInfo — Name, Checksum, Version, Labels of the model that predicted; null when it cannot be described ``` ### Model training @@ -237,7 +238,8 @@ var result = await _mediator.Send(new TrainImageClassificationModel - The model must be a ZIP file (ML.NET format) - The `ImageClassification` configuration section is required — a missing section throws `InvalidOperationException` when the options are first used - The model version and labels are stored in the archive as separate `Version.txt` and `Labels.txt` entries -- A model without `Labels.txt` (not trained with this library) gets its labels from the loaded model +- Scores and ModelInfo of a prediction describe the model that made it, not the current content of the model file +- GetModelInfo() describes the file; without `Labels.txt` (a model not trained with this library) its labels come from the loaded model - Check ImagePrediction.Scores and ImagePrediction.ModelInfo for null before using them - Training folder: each subfolder = one class, folder name = label - PredictionEnginePool is thread-safe — safe for concurrent use diff --git a/docs/Libraries/MediatR/ML.md b/docs/Libraries/MediatR/ML.md index 10ba7db3..3f13a331 100644 --- a/docs/Libraries/MediatR/ML.md +++ b/docs/Libraries/MediatR/ML.md @@ -115,9 +115,10 @@ public class ImageAnalysisController : ControllerBase Oprócz zwycięskiej etykiety predykcja zawiera wynik każdej etykiety (`Scores`) i opis modelu, który ją wydał (`ModelInfo`: nazwa, checksum, wersja, etykiety) - tyle, ile trzeba, żeby zapisać przy pliku, który model go ocenił i jak. -- **Etykiety** są czytane z wpisu `Labels.txt`, który trening zapisuje w pliku modelu. Model zapisany bez niego (nietrenowany tą biblioteką) dostaje etykiety z załadowanego modelu, w kolejności jego wyników. -- **`Scores` ma wartość `null`**, gdy etykiety nie są znane albo nie odpowiadają wynikom jeden do jednego. -- **`ModelInfo` ma wartość `null`**, gdy `ImageClassification:ModelFilePath` nie jest ustawione albo pliku nie da się odczytać. O tym, skąd ładowany jest model, decyduje pula, więc predykcja nie zależy od tego pliku. +- **Jedno i drugie należy do modelu, który wykonał predykcję.** Etykiety to te, którymi załadowany model nazywa swoje wyniki. Plik z `ImageClassification:ModelFilePath` jest opisywany raz dla każdego załadowanego modelu, przy jego pierwszym użyciu. Gdy plik zostanie podmieniony, a pula go nie przeładuje (`watchForChanges: false`), predykcje zachowują etykiety i opis modelu, który nadal je wykonuje. +- **`Scores` ma wartość `null`**, gdy model nie nazywa swoich wyników albo nazwy nie odpowiadają im jeden do jednego. +- **`ModelInfo` ma wartość `null`**, gdy `ImageClassification:ModelFilePath` nie jest ustawione albo pliku nie da się odczytać, gdy pula podmieniła model w trakcie predykcji oraz przy własnej implementacji `IPredictionEnginePoolAdapter`, bo modelu za nią nie da się odróżnić od pliku. O tym, skąd ładowany jest model, decyduje pula, więc predykcja nigdy nie zależy od tego pliku. +- **`GetModelInfo()`** opisuje plik w jego obecnym stanie. Etykiety bierze z wpisu `Labels.txt`, który zapisuje trening; plik zapisany bez niego (nietrenowany tą biblioteką) dostaje etykiety załadowanego modelu. - **Checksum** pliku modelu jest liczony raz i ponownie dopiero wtedy, gdy zmieni się rozmiar albo czas zapisu pliku, więc opis modelu nie spowalnia predykcji. ### Trening modelu @@ -149,7 +150,7 @@ Trening czyta pliki z rozszerzeniem `.jpg` lub `.png` z katalogu źródłowego i | `IImageClassificationService` | Interfejs | `Predict(byte[], fileName)`, `Train(images, folder, dest)`, `GetModelInfo()` | | `IPredictionEnginePoolAdapter` | Interfejs | Abstrakcja nad ML.NET `PredictionEnginePool` | | `ModelInfo` | Klasa | Metadane modelu: nazwa, checksum, wersja, etykiety | -| `ImagePrediction` | Klasa | Wynik predykcji: `PredictedLabel`, `PredictedScore`, `FileName`, `Scores` (etykieta -> wynik dla każdej etykiety; `null`, gdy etykiety nie są znane) i `ModelInfo` (`null`, gdy `ModelFilePath` nie jest ustawione albo pliku nie da się odczytać) | +| `ImagePrediction` | Klasa | Wynik predykcji: `PredictedLabel`, `PredictedScore`, `FileName`, `Scores` (etykieta -> wynik dla każdej etykiety; `null`, gdy model nie nazywa swoich wyników) i `ModelInfo` (model, który wykonał predykcję; `null`, gdy nie da się go opisać) | | `InMemoryImageData` | Klasa | Dane wejściowe do modelu: obraz jako `byte[]` | | `ImagePredictionScore` | Klasa | Surowy wynik modelu: `Score` (per klasa), `PredictedLabel` | | `ImageClassificationOptions` | Klasa | Opcje wiązane z sekcji `ImageClassification`: `ModelFilePath`, `TrainingRoot`, `ModelsRoot`, `MaxImageBytes` | @@ -217,8 +218,8 @@ var result = await _mediator.Send(new ClassifyImage }); // result.ImagePrediction.PredictedLabel — przewidywana klasa // result.ImagePrediction.PredictedScore — pewność (0-1) -// result.ImagePrediction.Scores — etykieta -> wynik dla każdej etykiety; null, gdy etykiety nie są znane -// result.ImagePrediction.ModelInfo — Name, Checksum, Version, Labels; null bez czytelnego ModelFilePath +// result.ImagePrediction.Scores — etykieta -> wynik dla każdej etykiety; null, gdy model nie nazywa swoich wyników +// result.ImagePrediction.ModelInfo — Name, Checksum, Version, Labels modelu, który wykonał predykcję; null, gdy nie da się go opisać ``` ### Trening modelu @@ -237,7 +238,8 @@ var result = await _mediator.Send(new TrainImageClassificationModel - Model musi być plikiem ZIP (ML.NET format) - Sekcja konfiguracji `ImageClassification` jest wymagana — jej brak powoduje `InvalidOperationException` przy pierwszym użyciu opcji - Wersja i etykiety modelu są zapisywane w archiwum jako osobne wpisy `Version.txt` i `Labels.txt` -- Model bez `Labels.txt` (nietrenowany tą biblioteką) dostaje etykiety z załadowanego modelu +- Scores i ModelInfo predykcji opisują model, który ją wykonał, a nie obecną zawartość pliku modelu +- GetModelInfo() opisuje plik; bez `Labels.txt` (model nietrenowany tą biblioteką) etykiety pochodzą z załadowanego modelu - Przed użyciem sprawdź, czy ImagePrediction.Scores i ImagePrediction.ModelInfo nie mają wartości null - Folder treningowy: każdy podfolder = jedna klasa, nazwa folderu = etykieta - PredictionEnginePool jest thread-safe — bezpieczne współbieżne użycie diff --git a/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ClassificationService.cs b/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ClassificationService.cs index 9b13b492..346c82cc 100644 --- a/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ClassificationService.cs +++ b/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ClassificationService.cs @@ -3,6 +3,7 @@ using System.Diagnostics; using System.IO; using System.Linq; +using System.Runtime.CompilerServices; using System.Text; using Microsoft.ML; using Microsoft.ML.Data; @@ -22,6 +23,11 @@ public class ImageClassificationService : IImageClassificationService private readonly IPredictionEnginePoolAdapter predictionEnginePool; private readonly IModelInfoService modelInfoService; + // The description of the model file, kept for as long as the loaded model it was read for lives. When the + // file is replaced and the pool does not reload it, predictions keep the description of the model that + // still makes them instead of taking on that of the new file. + private static readonly ConditionalWeakTable descriptions = new(); + /// /// Initializes a new instance of . /// @@ -61,25 +67,43 @@ public ModelInfo GetModelInfo() /// () and the description of the model (). /// /// - /// is when the labels of the model are not known - /// or do not match its scores one to one. is - /// when ImageClassification:ModelFilePath is not configured or the file cannot be read: the pool decides - /// where the model is loaded from, so a prediction does not depend on that file. + /// Both belong to the model that made the prediction, not to whatever the model file holds at that moment. + /// The labels are the ones the loaded model names its scores with, and the file is described once for every + /// loaded model, when that model is first used. + /// is when the model does not name its scores or + /// the names do not match the scores one to one. is + /// when ImageClassification:ModelFilePath is not configured, the file cannot be + /// read, the pool replaced the model while the prediction ran, or the adapter is not the one this library + /// registers, because the model behind another adapter cannot be told apart from the file. /// public ImagePrediction Predict(byte[] image, string? fileName) { var imageData = new InMemoryImageData(image, null, fileName); - ImagePredictionScore prediction = predictionEnginePool.Predict(imageData); + + ImagePredictionScore prediction; + string[] labels; + object? model = null; + if (predictionEnginePool is IModelBoundPredictionEngine modelBound) + { + var result = modelBound.PredictWithModel(imageData); + prediction = result.Prediction; + labels = result.Labels; + model = result.Model; + } + else + { + prediction = predictionEnginePool.Predict(imageData); + labels = predictionEnginePool.GetLabels() ?? Array.Empty(); + } + var scores = prediction.Score ?? throw new InvalidOperationException("The model returned no scores."); - var predictedScore = scores.Max(); - var labels = GetLabels(); ImagePrediction imagePrediction = new ImagePrediction() { - PredictedScore = predictedScore, + PredictedScore = scores.Max(), FileName = fileName, PredictedLabel = prediction.PredictedLabel, - ModelInfo = DescribeModel(labels), + ModelInfo = model == null ? null : DescribeModel(model, labels), Scores = MapScores(labels, scores) } ; @@ -87,8 +111,8 @@ public ImagePrediction Predict(byte[] image, string? fileName) } - // Labels in the order of the model's scores: the Labels.txt entry that training writes into the model - // file or, for a model saved without it, the slot names of the loaded model. + // The labels of the model file: its Labels.txt entry or, for a file saved without it, the labels of the + // model the pool has loaded. private string[] GetLabels() { var labels = modelInfoService.Labels; @@ -100,26 +124,29 @@ private string[] GetLabels() return predictionEnginePool.GetLabels() ?? Array.Empty(); } - private ModelInfo? DescribeModel(string[] labels) + private ModelInfo? DescribeModel(object model, string[] labels) { - if (string.IsNullOrWhiteSpace(modelInfoService.ModelFilePath)) + var path = modelInfoService.ModelFilePath; + if (string.IsNullOrWhiteSpace(path)) { return null; } - try + if (!descriptions.TryGetValue(model, out var description) || !string.Equals(description.Path, path, StringComparison.Ordinal)) { - return new ModelInfo( - modelInfoService.ModelFileName, - modelInfoService.ModelChecksum, - modelInfoService.ModelVersion, - labels - ); - } - catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) - { - return null; + try + { + description = new ModelFileDescription(path, modelInfoService.ModelFileName, modelInfoService.ModelChecksum, modelInfoService.ModelVersion); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return null; + } + + descriptions.AddOrUpdate(model, description); } + + return new ModelInfo(description.Name, description.Checksum, description.Version, labels); } private static Dictionary? MapScores(string[] labels, float[] scores) @@ -141,6 +168,25 @@ private string[] GetLabels() return result; } + private sealed class ModelFileDescription + { + public ModelFileDescription(string path, string? name, string checksum, string version) + { + Path = path; + Name = name; + Checksum = checksum; + Version = version; + } + + public string Path { get; } + + public string? Name { get; } + + public string Checksum { get; } + + public string Version { get; } + } + /// /// Trains an image classification model using the provided image dataset and saves it to disk. /// diff --git a/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ModelBoundPrediction.cs b/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ModelBoundPrediction.cs new file mode 100644 index 00000000..117a8bcb --- /dev/null +++ b/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ModelBoundPrediction.cs @@ -0,0 +1,42 @@ +namespace TailoredApps.Shared.MediatR.ImageClassification.Infrastructure; + +/// +/// A prediction together with what ties it to the model that made it. +/// +/// The output prediction type produced by the engine. +internal readonly struct ModelBoundPrediction +{ + public ModelBoundPrediction(TPrediction prediction, string[] labels, object? model) + { + Prediction = prediction; + Labels = labels; + Model = model; + } + + /// The prediction. + public TPrediction Prediction { get; } + + /// + /// The labels of the engine that made the prediction, in the order of its scores; empty when the model + /// does not name its scores. + /// + public string[] Labels { get; } + + /// + /// The model the pool held before and after the prediction, used only as its identity; + /// when the pool replaced the model while the prediction ran. + /// + public object? Model { get; } +} + +/// +/// Implemented by the adapter this library registers: one call that predicts and reports which model did it, +/// so that labels and the model description are never taken from another model than the one that scored. +/// +/// The input data type for the prediction engine. +/// The output prediction type produced by the engine. +internal interface IModelBoundPredictionEngine +{ + /// Runs a prediction and returns it with the labels and the identity of the model that made it. + ModelBoundPrediction PredictWithModel(TData example); +} diff --git a/src/TailoredApps.Shared.MediatR.ML/Infrastructure/PredictionEnginePoolAdapter.cs b/src/TailoredApps.Shared.MediatR.ML/Infrastructure/PredictionEnginePoolAdapter.cs index aee38bcf..623bc20c 100644 --- a/src/TailoredApps.Shared.MediatR.ML/Infrastructure/PredictionEnginePoolAdapter.cs +++ b/src/TailoredApps.Shared.MediatR.ML/Infrastructure/PredictionEnginePoolAdapter.cs @@ -1,6 +1,7 @@ using System; using System.Linq; using Microsoft.Extensions.ML; +using Microsoft.ML; using Microsoft.ML.Data; using TailoredApps.Shared.MediatR.ImageClassification.Interfaces.Infrastructure; @@ -13,7 +14,7 @@ namespace TailoredApps.Shared.MediatR.ImageClassification.Infrastructure; /// /// The input data type for the prediction engine. /// The output prediction type produced by the engine. -public class PredictionEnginePoolAdapter : IPredictionEnginePoolAdapter +public class PredictionEnginePoolAdapter : IPredictionEnginePoolAdapter, IModelBoundPredictionEngine where TData : class where TPrediction : class, new() { @@ -41,15 +42,7 @@ public string[] GetLabels() var predictionEngine = predictionEnginePool.GetPredictionEngine(); try { - var score = predictionEngine.OutputSchema.GetColumnOrNull("Score"); - if (score == null || score.Value.Annotations.Schema.GetColumnOrNull("SlotNames") == null) - { - return Array.Empty(); - } - - var labelBuffer = new VBuffer>(); - score.Value.Annotations.GetValue("SlotNames", ref labelBuffer); - return labelBuffer.DenseValues().Select(l => l.ToString()).ToArray(); + return ReadLabels(predictionEngine.OutputSchema); } finally { @@ -59,6 +52,42 @@ public string[] GetLabels() } } + /// + /// Runs a prediction and reports the labels of the engine that made it and the model the pool held meanwhile. + /// + ModelBoundPrediction IModelBoundPredictionEngine.PredictWithModel(TData example) + { + var modelBefore = predictionEnginePool.GetModel(); + var predictionEngine = predictionEnginePool.GetPredictionEngine(); + try + { + var prediction = predictionEngine.Predict(example); + var labels = ReadLabels(predictionEngine.OutputSchema); + var modelAfter = predictionEnginePool.GetModel(); + + // A pool that watches its file can replace the model at any moment. When it did so during this + // call, it is not known which of the two models the engine belonged to. + return new ModelBoundPrediction(prediction, labels, ReferenceEquals(modelBefore, modelAfter) ? modelBefore : null); + } + finally + { + predictionEnginePool.ReturnPredictionEngine(predictionEngine); + } + } + + private static string[] ReadLabels(DataViewSchema schema) + { + var score = schema.GetColumnOrNull("Score"); + if (score == null || score.Value.Annotations.Schema.GetColumnOrNull("SlotNames") == null) + { + return Array.Empty(); + } + + var labelBuffer = new VBuffer>(); + score.Value.Annotations.GetValue("SlotNames", ref labelBuffer); + return labelBuffer.DenseValues().Select(l => l.ToString()).ToArray(); + } + /// /// Runs a prediction on the provided input example using the pooled prediction engine. /// diff --git a/src/TailoredApps.Shared.MediatR.ML/README.md b/src/TailoredApps.Shared.MediatR.ML/README.md index 77894659..26376a67 100644 --- a/src/TailoredApps.Shared.MediatR.ML/README.md +++ b/src/TailoredApps.Shared.MediatR.ML/README.md @@ -80,10 +80,16 @@ The `ImageClassification` section: - `ClassifyImage` throws `ArgumentException` for empty content, for content over `MaxImageBytes` and for content that does not start with a JPEG or PNG signature. - The returned `ImagePrediction` has `FileName`, `PredictedLabel` and `PredictedScore`, the score of every label - in `Scores` and the description of the model in `ModelInfo`. Labels come from the `Labels.txt` entry of the - model file; a model saved without it (not trained with this library) gets them from the loaded model. - `Scores` is `null` when the labels are not known or do not match the scores one to one. `ModelInfo` is `null` - when `ModelFilePath` is not configured or the file cannot be read; the prediction itself does not need it. + in `Scores` and the description of the model in `ModelInfo`. Both belong to the model that made the + prediction: the labels are the ones the loaded model names its scores with, and the file at `ModelFilePath` + is described once for every loaded model, when that model is first used. A file replaced without the pool + reloading it (`watchForChanges: false`) therefore does not change what a prediction reports. +- `Scores` is `null` when the model does not name its scores or the names do not match them one to one. + `ModelInfo` is `null` when `ModelFilePath` is not configured or cannot be read, when the pool replaced the + model while the prediction ran, and with your own `IPredictionEnginePoolAdapter` (the model behind it cannot + be told apart from the file). The prediction itself never depends on that file. +- `IImageClassificationService.GetModelInfo()` describes the file as it is now. Its labels come from the + `Labels.txt` entry; a file saved without it (not trained with this library) gets the labels of the loaded model. - The checksum of a model file is computed once and again only when the file's size or write time changes. - Training paths are resolved against `TrainingRoot` and `ModelsRoot`. A path outside its root throws `ArgumentException`; a root that is not configured throws `InvalidOperationException`. diff --git a/tests/TailoredApps.Shared.MediatR.ML.Tests/ImageClassificationServiceTests.cs b/tests/TailoredApps.Shared.MediatR.ML.Tests/ImageClassificationServiceTests.cs index 5cace505..ed330946 100644 --- a/tests/TailoredApps.Shared.MediatR.ML.Tests/ImageClassificationServiceTests.cs +++ b/tests/TailoredApps.Shared.MediatR.ML.Tests/ImageClassificationServiceTests.cs @@ -22,7 +22,7 @@ public ImageClassificationServiceTests() } [Fact] - public void When_Model_Has_No_Known_Labels_And_No_Configured_File_Predict_Should_Leave_Scores_And_ModelInfo_Null() + public void When_Model_Does_Not_Name_Its_Scores_Predict_Should_Leave_Scores_And_ModelInfo_Null() { // arrange var imageBytes = new byte[] { 1, 2, 3 }; @@ -46,15 +46,37 @@ public void When_Model_Has_No_Known_Labels_And_No_Configured_File_Predict_Should } [Fact] - public void When_Model_File_Has_Labels_Predict_Should_Return_Every_Score_And_The_Model_Description() + public void When_Adapter_Is_Not_The_One_The_Library_Registers_Predict_Should_Return_Scores_Without_Describing_The_File() { - // arrange - var labels = new[] { "blue", "green", "red" }; - SetupModelFile(labels); - SetupPrediction("green", 0.1f, 0.7f, 0.2f); + // arrange: the model behind a foreign adapter cannot be told apart from the file, so it is not described + SetupModelFile(new[] { "circle", "square", "triangle" }); + predictionEnginePoolMock.Setup(p => p.GetLabels()).Returns(new[] { "blue", "green", "red" }); + SetupPrediction("blue", 0.6f, 0.3f, 0.1f); + + // act + var prediction = sut.Predict(new byte[] { 1, 2, 3 }, "testblue.png"); + + // assert + Assert.NotNull(prediction.Scores); + Assert.Equal(0.6f, prediction.Scores["blue"]); + Assert.Equal(0.3f, prediction.Scores["green"]); + Assert.Equal(0.1f, prediction.Scores["red"]); + Assert.Null(prediction.ModelInfo); + modelInfoServiceMock.VerifyGet(m => m.ModelChecksum, Times.Never); + modelInfoServiceMock.VerifyGet(m => m.Labels, Times.Never); + } + + [Fact] + public void When_Predict_Is_Called_Should_Return_Every_Score_And_The_Description_Of_The_Model_That_Made_It() + { + // arrange: the file's own Labels.txt says something else than the loaded model + var loaded = new ModelBoundAdapter { Labels = new[] { "blue", "green", "red" } }; + loaded.Returns("green", 0.1f, 0.7f, 0.2f); + SetupModelFile(new[] { "circle", "square", "triangle" }); + var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); // act - var prediction = sut.Predict(new byte[] { 1, 2, 3 }, "testgreen.png"); + var prediction = service.Predict(new byte[] { 1, 2, 3 }, "testgreen.png"); // assert Assert.Equal("green", prediction.PredictedLabel); @@ -68,40 +90,88 @@ public void When_Model_File_Has_Labels_Predict_Should_Return_Every_Score_And_The Assert.Equal("image.zip", prediction.ModelInfo.Name); Assert.Equal("abc123", prediction.ModelInfo.Checksum); Assert.Equal("20260820.101010", prediction.ModelInfo.Version); - Assert.Same(labels, prediction.ModelInfo.Labels); - predictionEnginePoolMock.Verify(p => p.GetLabels(), Times.Never); + Assert.Equal(new[] { "blue", "green", "red" }, prediction.ModelInfo.Labels); } [Fact] - public void When_Model_File_Has_No_Labels_Predict_Should_Take_Them_From_The_Loaded_Model() + public void When_Model_File_Is_Replaced_But_The_Loaded_Model_Stays_Predict_Should_Keep_Describing_The_Loaded_Model() { // arrange - var labels = new[] { "blue", "green", "red" }; - SetupModelFile(Array.Empty()); - predictionEnginePoolMock.Setup(p => p.GetLabels()).Returns(labels); - SetupPrediction("red", 0.05f, 0.15f, 0.8f); + var loaded = new ModelBoundAdapter { Labels = new[] { "blue", "green", "red" } }; + loaded.Returns("green", 0.1f, 0.7f, 0.2f); + SetupModelFile(new[] { "blue", "green", "red" }); + var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); + service.Predict(new byte[] { 1, 2, 3 }, "first.png"); - // act - var prediction = sut.Predict(new byte[] { 1, 2, 3 }, "testred.png"); + // act: another file takes the place of the model file; the pool still holds the model it loaded + modelInfoServiceMock.SetupGet(m => m.ModelChecksum).Returns("replaced"); + modelInfoServiceMock.SetupGet(m => m.ModelVersion).Returns("20270101.000000"); + modelInfoServiceMock.SetupGet(m => m.Labels).Returns(new[] { "red", "green", "blue" }); + var prediction = service.Predict(new byte[] { 1, 2, 3 }, "second.png"); + + // assert + Assert.NotNull(prediction.ModelInfo); + Assert.Equal("abc123", prediction.ModelInfo.Checksum); + Assert.Equal("20260820.101010", prediction.ModelInfo.Version); + Assert.Equal(0.1f, prediction.Scores["blue"]); + Assert.Equal(0.2f, prediction.Scores["red"]); + } + + [Fact] + public void When_Pool_Loads_Another_Model_Predict_Should_Describe_The_File_Again() + { + // arrange + var loaded = new ModelBoundAdapter { Labels = new[] { "blue", "green", "red" } }; + loaded.Returns("green", 0.1f, 0.7f, 0.2f); + SetupModelFile(new[] { "blue", "green", "red" }); + var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); + service.Predict(new byte[] { 1, 2, 3 }, "first.png"); + + // act: the file changed and the pool reloaded it + modelInfoServiceMock.SetupGet(m => m.ModelChecksum).Returns("replaced"); + modelInfoServiceMock.SetupGet(m => m.ModelVersion).Returns("20270101.000000"); + loaded.Model = new object(); + loaded.Labels = new[] { "circle", "square", "triangle" }; + loaded.Returns("square", 0.2f, 0.5f, 0.3f); + var prediction = service.Predict(new byte[] { 1, 2, 3 }, "second.png"); // assert - Assert.NotNull(prediction.Scores); - Assert.Equal(0.05f, prediction.Scores["blue"]); - Assert.Equal(0.15f, prediction.Scores["green"]); - Assert.Equal(0.8f, prediction.Scores["red"]); Assert.NotNull(prediction.ModelInfo); - Assert.Same(labels, prediction.ModelInfo.Labels); + Assert.Equal("replaced", prediction.ModelInfo.Checksum); + Assert.Equal("20270101.000000", prediction.ModelInfo.Version); + Assert.Equal(new[] { "circle", "square", "triangle" }, prediction.ModelInfo.Labels); + Assert.Equal(0.5f, prediction.Scores["square"]); + } + + [Fact] + public void When_Pool_Replaces_The_Model_During_A_Prediction_Predict_Should_Not_Describe_Any_Model() + { + // arrange + var loaded = new ModelBoundAdapter { Labels = new[] { "blue", "green", "red" }, Model = null }; + loaded.Returns("green", 0.1f, 0.7f, 0.2f); + SetupModelFile(new[] { "blue", "green", "red" }); + var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); + + // act + var prediction = service.Predict(new byte[] { 1, 2, 3 }, "testgreen.png"); + + // assert: the scores carry the labels of the engine that made them; the file is not attributed + Assert.NotNull(prediction.Scores); + Assert.Equal(0.7f, prediction.Scores["green"]); + Assert.Null(prediction.ModelInfo); + modelInfoServiceMock.VerifyGet(m => m.ModelChecksum, Times.Never); } [Fact] public void When_Model_File_Is_Not_Configured_Predict_Should_Return_Scores_Without_Reading_The_File() { // arrange - predictionEnginePoolMock.Setup(p => p.GetLabels()).Returns(new[] { "blue", "green", "red" }); - SetupPrediction("blue", 0.6f, 0.3f, 0.1f); + var loaded = new ModelBoundAdapter { Labels = new[] { "blue", "green", "red" } }; + loaded.Returns("blue", 0.6f, 0.3f, 0.1f); + var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); // act - var prediction = sut.Predict(new byte[] { 1, 2, 3 }, "testblue.png"); + var prediction = service.Predict(new byte[] { 1, 2, 3 }, "testblue.png"); // assert Assert.NotNull(prediction.Scores); @@ -112,32 +182,40 @@ public void When_Model_File_Is_Not_Configured_Predict_Should_Return_Scores_Witho } [Fact] - public void When_Model_File_Cannot_Be_Read_Predict_Should_Still_Return_The_Prediction() + public void When_Model_File_Cannot_Be_Read_Predict_Should_Still_Return_The_Prediction_And_Describe_The_Model_Once_It_Can() { // arrange + var loaded = new ModelBoundAdapter { Labels = new[] { "blue", "green", "red" } }; + loaded.Returns("green", 0.1f, 0.7f, 0.2f); SetupModelFile(new[] { "blue", "green", "red" }); modelInfoServiceMock.SetupGet(m => m.ModelChecksum).Throws(new FileNotFoundException("no model")); - SetupPrediction("green", 0.1f, 0.7f, 0.2f); + var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); // act - var prediction = sut.Predict(new byte[] { 1, 2, 3 }, "testgreen.png"); + var withoutFile = service.Predict(new byte[] { 1, 2, 3 }, "first.png"); + modelInfoServiceMock.SetupGet(m => m.ModelChecksum).Returns("abc123"); + var withFile = service.Predict(new byte[] { 1, 2, 3 }, "second.png"); // assert - Assert.Equal("green", prediction.PredictedLabel); - Assert.Equal(0.7f, prediction.PredictedScore); - Assert.NotNull(prediction.Scores); - Assert.Null(prediction.ModelInfo); + Assert.Equal("green", withoutFile.PredictedLabel); + Assert.Equal(0.7f, withoutFile.PredictedScore); + Assert.NotNull(withoutFile.Scores); + Assert.Null(withoutFile.ModelInfo); + Assert.NotNull(withFile.ModelInfo); + Assert.Equal("abc123", withFile.ModelInfo.Checksum); } [Fact] public void When_Labels_Do_Not_Match_The_Scores_Predict_Should_Leave_Scores_Null() { // arrange + var loaded = new ModelBoundAdapter { Labels = new[] { "blue", "green" } }; + loaded.Returns("red", 0.1f, 0.2f, 0.7f); SetupModelFile(new[] { "blue", "green" }); - SetupPrediction("red", 0.1f, 0.2f, 0.7f); + var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); // act - var prediction = sut.Predict(new byte[] { 1, 2, 3 }, "testred.png"); + var prediction = service.Predict(new byte[] { 1, 2, 3 }, "testred.png"); // assert Assert.Equal("red", prediction.PredictedLabel); @@ -150,11 +228,12 @@ public void When_Labels_Do_Not_Match_The_Scores_Predict_Should_Leave_Scores_Null public void When_A_Label_Repeats_Predict_Should_Leave_Scores_Null() { // arrange - SetupModelFile(new[] { "blue", "blue", "red" }); - SetupPrediction("red", 0.1f, 0.2f, 0.7f); + var loaded = new ModelBoundAdapter { Labels = new[] { "blue", "blue", "red" } }; + loaded.Returns("red", 0.1f, 0.2f, 0.7f); + var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); // act - var prediction = sut.Predict(new byte[] { 1, 2, 3 }, "testred.png"); + var prediction = service.Predict(new byte[] { 1, 2, 3 }, "testred.png"); // assert Assert.Equal(0.7f, prediction.PredictedScore); @@ -249,4 +328,33 @@ private void SetupPrediction(string predictedLabel, params float[] scores) .Setup(p => p.Predict(It.IsAny())) .Returns(new ImagePredictionScore { PredictedLabel = predictedLabel, Score = scores }); } + + /// + /// Stands in for the adapter the library registers: it reports which model made a prediction. + /// + private sealed class ModelBoundAdapter : + IPredictionEnginePoolAdapter, + IModelBoundPredictionEngine + { + private ImagePredictionScore prediction; + + /// The model the pool holds; null plays a pool that replaced it during the prediction. + public object Model { get; set; } = new object(); + + public string[] Labels { get; set; } = Array.Empty(); + + public void Returns(string predictedLabel, params float[] scores) + { + prediction = new ImagePredictionScore { PredictedLabel = predictedLabel, Score = scores }; + } + + public string[] GetLabels() => Labels; + + public ImagePredictionScore Predict(InMemoryImageData example) => prediction; + + public ModelBoundPrediction PredictWithModel(InMemoryImageData example) + { + return new ModelBoundPrediction(prediction, Labels, Model); + } + } } diff --git a/tests/TailoredApps.Shared.MediatR.ML.Tests/PredictionEnginePoolAdapterTests.cs b/tests/TailoredApps.Shared.MediatR.ML.Tests/PredictionEnginePoolAdapterTests.cs index bddff95e..4dc097aa 100644 --- a/tests/TailoredApps.Shared.MediatR.ML.Tests/PredictionEnginePoolAdapterTests.cs +++ b/tests/TailoredApps.Shared.MediatR.ML.Tests/PredictionEnginePoolAdapterTests.cs @@ -3,9 +3,11 @@ using System.Linq; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.ML; +using Microsoft.Extensions.Options; using Microsoft.ML; using Microsoft.ML.Data; using TailoredApps.Shared.MediatR.ImageClassification.Infrastructure; +using TailoredApps.Shared.MediatR.ImageClassification.Interfaces.Domain.Models; using TailoredApps.Shared.MediatR.ImageClassification.Interfaces.Infrastructure; using Xunit; @@ -79,6 +81,62 @@ public void When_Model_Scores_Are_Not_Named_GetLabels_Should_Return_Empty_Array( Assert.Empty(labels); } + [Fact] + public void When_Predicting_With_The_Model_Should_Return_The_Labels_And_The_Model_Of_The_Engine() + { + // arrange + using var provider = BuildProvider(SaveClassifier()); + var sut = (IModelBoundPredictionEngine) + provider.GetRequiredService>(); + + // act + var first = sut.PredictWithModel(new ColorSample { Red = 0.95f, Green = 0.1f, Blue = 0.05f }); + var second = sut.PredictWithModel(new ColorSample { Red = 0.05f, Green = 0.9f, Blue = 0.1f }); + + // assert + Assert.Equal("red", first.Prediction.PredictedLabel); + Assert.Equal("green", second.Prediction.PredictedLabel); + Assert.Equal(new[] { "blue", "green", "red" }, first.Labels); + Assert.NotNull(first.Model); + Assert.Same(first.Model, second.Model); + } + + [Fact] + public void When_Model_File_Is_Replaced_Without_A_Reload_Prediction_Should_Keep_Labels_And_Description_Of_The_Loaded_Model() + { + // arrange: a model of colours is loaded once; the pool does not watch its file + var path = SaveFileNameClassifier("model.zip", "blue", "green", "red"); + var modelHelper = new ModelHelper(); + var loadedVersion = modelHelper.AddVersion(path); + var loadedChecksum = modelHelper.GetChecksum(path); + + var services = new ServiceCollection(); + services.AddPredictionEnginePool() + .FromFile(path, watchForChanges: false) + .AddAdapter(); + using var provider = services.BuildServiceProvider(); + var adapter = provider.GetRequiredService>(); + var options = Options.Create(new ImageClassificationOptions { ModelFilePath = path }); + var sut = new ImageClassificationService(adapter, new ModelInfoService(options, modelHelper)); + var before = sut.Predict(new byte[] { 1 }, "red-7.png"); + + // act: a model of shapes, with as many labels, takes the file's place + SaveFileNameClassifier("model.zip", "circle", "square", "triangle"); + modelHelper.AddLabels(path, new[] { "circle", "square", "triangle" }); + var after = sut.Predict(new byte[] { 1 }, "red-8.png"); + + // assert: the scores still belong to the colours, and so does the description + Assert.NotEqual(loadedChecksum, modelHelper.GetChecksum(path)); + Assert.Equal("red", before.PredictedLabel); + Assert.Equal("red", after.PredictedLabel); + Assert.Equal(new[] { "blue", "green", "red" }, after.Scores.Keys.ToArray()); + Assert.Equal(after.PredictedScore, after.Scores["red"]); + Assert.Equal(loadedChecksum, before.ModelInfo.Checksum); + Assert.Equal(loadedChecksum, after.ModelInfo.Checksum); + Assert.Equal(loadedVersion, after.ModelInfo.Version); + Assert.Equal(new[] { "blue", "green", "red" }, after.ModelInfo.Labels); + } + private ServiceProvider BuildProvider(string modelPath) where TPrediction : class, new() { var services = new ServiceCollection(); @@ -112,6 +170,24 @@ private string SaveRegression() return Save(mlContext, pipeline.Fit(data), data.Schema, "regression.zip"); } + // A classifier over the input type of the library, small enough to train in a test: it tells the label + // from the file name and ignores the image bytes. + private string SaveFileNameClassifier(string fileName, params string[] labels) + { + var mlContext = new MLContext(seed: 1); + var samples = labels + .SelectMany(label => Enumerable.Range(0, 30).Select(i => new InMemoryImageData(new byte[] { 1 }, label, $"{label}-{i}.png"))) + .ToArray(); + var data = mlContext.Data.LoadFromEnumerable(samples); + var pipeline = mlContext.Transforms.Conversion + .MapValueToKey("LabelAsKey", nameof(InMemoryImageData.Label), keyOrdinality: Microsoft.ML.Transforms.ValueToKeyMappingEstimator.KeyOrdinality.ByValue) + .Append(mlContext.Transforms.Text.FeaturizeText("Features", nameof(InMemoryImageData.FileName))) + .Append(mlContext.MulticlassClassification.Trainers.SdcaMaximumEntropy("LabelAsKey", "Features")) + .Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel", "PredictedLabel")); + + return Save(mlContext, pipeline.Fit(data), data.Schema, fileName); + } + private string Save(MLContext mlContext, ITransformer model, DataViewSchema schema, string fileName) { var path = Path.Combine(workFolder, fileName);