From 9f0dd6709c2386f4e336b33c9f283855c054fa9a Mon Sep 17 00:00:00 2001 From: nieprzecietny Date: Wed, 2 Dec 2026 01:48:36 +0100 Subject: [PATCH 1/4] fix(ml): scores of every label and the model description in a prediction The 3.0 counterpart of #91 (release/2.1, released as 2.1.1), ported to TailoredApps.Shared.Mediator.ML. ClassifyImage returned only the winning label: ImagePrediction.Scores and ModelInfo were left null, and a model saved without the Labels.txt entry had no labels at all. - ImageClassificationService.Predict fills Scores (label -> score) and ModelInfo, and both belong to the model that made the prediction. The labels are read from the engine that made it; 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 keeps the labels and the description of the model that still predicts. - Scores stays null when the model does not name its scores or the names do not match them one to one. ModelInfo stays null when ModelFilePath is not configured or cannot be read, when the pool replaced the model while the prediction ran, and with an adapter other than the library's. - GetModelInfo() describes the file as it is now; without Labels.txt its labels come from the loaded model. - PredictionEnginePoolAdapter predicts and reports the labels and the model in one call (an internal contract). GetLabels returns the engine to the pool and answers with an empty array for a model whose scores are not named. - ModelHelper keeps the checksum of a model file until its size or write time changes, and reads the version and the labels with read-only, shared access. No public API changes. Tests and docs are ported with the code. --- docs-en/Libraries/Mediator/ML.md | 20 +- docs/Libraries/Mediator/ML.md | 20 +- .../Infrastructure/ClassificationService.cs | 133 ++++++++- .../Infrastructure/ModelBoundPrediction.cs | 42 +++ .../Infrastructure/ModelHelper.cs | 31 ++- .../PredictionEnginePoolAdapter.cs | 55 +++- src/TailoredApps.Shared.Mediator.ML/README.md | 17 +- .../ImageClassificationServiceTests.cs | 260 +++++++++++++++++- .../ModelHelperTests.cs | 104 +++++++ .../PredictionEnginePoolAdapterTests.cs | 236 ++++++++++++++++ 10 files changed, 893 insertions(+), 25 deletions(-) create mode 100644 src/TailoredApps.Shared.Mediator.ML/Infrastructure/ModelBoundPrediction.cs create mode 100644 tests/TailoredApps.Shared.Mediator.ML.Tests/PredictionEnginePoolAdapterTests.cs diff --git a/docs-en/Libraries/Mediator/ML.md b/docs-en/Libraries/Mediator/ML.md index 720ea07..dd96954 100644 --- a/docs-en/Libraries/Mediator/ML.md +++ b/docs-en/Libraries/Mediator/ML.md @@ -104,12 +104,23 @@ 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. + +- **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 ```csharp @@ -139,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` and `ModelInfo` are not filled by `ClassifyImage` | +| `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` | @@ -207,6 +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 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 @@ -225,6 +238,9 @@ 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 +- 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 - PredictedScore ∈ [0,1] — the closer to 1, the higher the model's confidence diff --git a/docs/Libraries/Mediator/ML.md b/docs/Libraries/Mediator/ML.md index 114bd04..52e17d9 100644 --- a/docs/Libraries/Mediator/ML.md +++ b/docs/Libraries/Mediator/ML.md @@ -104,12 +104,23 @@ 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. + +- **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 ```csharp @@ -139,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` i `ModelInfo` nie są wypełniane przez `ClassifyImage` | +| `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` | @@ -207,6 +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 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 @@ -225,6 +238,9 @@ 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` +- 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 - PredictedScore ∈ [0,1] — im bliżej 1, tym wyższe zaufanie modelu diff --git a/src/TailoredApps.Shared.Mediator.ML/Infrastructure/ClassificationService.cs b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/ClassificationService.cs index 9396eff..29f0e31 100644 --- a/src/TailoredApps.Shared.Mediator.ML/Infrastructure/ClassificationService.cs +++ b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/ClassificationService.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.IO; using System.Linq; +using System.Runtime.CompilerServices; using System.Text; using Microsoft.ML; using Microsoft.ML.Data; @@ -21,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 . /// @@ -36,13 +43,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 +62,131 @@ 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 (). + /// + /// + /// 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); - // ModelInfo modelInfo = GetModelInfo(); + + 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."); ImagePrediction imagePrediction = new ImagePrediction() { - PredictedScore = (prediction.Score ?? throw new InvalidOperationException("The model returned no scores.")).Max(), + PredictedScore = scores.Max(), 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 = model == null ? null : DescribeModel(model, labels), + Scores = MapScores(labels, scores) } ; return imagePrediction; } + // 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; + if (labels != null && labels.Length > 0) + { + return labels; + } + + return predictionEnginePool.GetLabels() ?? Array.Empty(); + } + + private ModelInfo? DescribeModel(object model, string[] labels) + { + var path = modelInfoService.ModelFilePath; + if (string.IsNullOrWhiteSpace(path)) + { + return null; + } + + if (!descriptions.TryGetValue(model, out var description) || !string.Equals(description.Path, path, StringComparison.Ordinal)) + { + 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) + { + 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; + } + + 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.Mediator.ML/Infrastructure/ModelBoundPrediction.cs b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/ModelBoundPrediction.cs new file mode 100644 index 0000000..4855d63 --- /dev/null +++ b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/ModelBoundPrediction.cs @@ -0,0 +1,42 @@ +namespace TailoredApps.Shared.Mediator.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.Mediator.ML/Infrastructure/ModelHelper.cs b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/ModelHelper.cs index 7508703..2b5b985 100644 --- a/src/TailoredApps.Shared.Mediator.ML/Infrastructure/ModelHelper.cs +++ b/src/TailoredApps.Shared.Mediator.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.Mediator.ML/Infrastructure/PredictionEnginePoolAdapter.cs b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/PredictionEnginePoolAdapter.cs index 9efb882..277af30 100644 --- a/src/TailoredApps.Shared.Mediator.ML/Infrastructure/PredictionEnginePoolAdapter.cs +++ b/src/TailoredApps.Shared.Mediator.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.Mediator.ImageClassification.Interfaces.Infrastructure; @@ -13,7 +14,7 @@ namespace TailoredApps.Shared.Mediator.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() { @@ -32,12 +33,58 @@ 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); + try + { + return ReadLabels(predictionEngine.OutputSchema); + } + 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); + } + } + + /// + /// 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(); } diff --git a/src/TailoredApps.Shared.Mediator.ML/README.md b/src/TailoredApps.Shared.Mediator.ML/README.md index 161cda2..7a515b3 100644 --- a/src/TailoredApps.Shared.Mediator.ML/README.md +++ b/src/TailoredApps.Shared.Mediator.ML/README.md @@ -41,6 +41,8 @@ using TailoredApps.Shared.Mediator.ImageClassification.Domain.DataModel.Message. 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 { @@ -77,8 +79,19 @@ The `ImageClassification` section: - Built on [ForkForward.Mediator](https://www.nuget.org/packages/ForkForward.Mediator), a fork of MediatR 12.5.0 under the Apache-2.0 licence, not on the MediatR package: requests and handlers use the `ForkForward.Mediator` namespace and the mediator is registered with `AddMediator(...)`. In 2.x this package was named `TailoredApps.Shared.MediatR.ML`. - 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`. 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`. - 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.Mediator.ML.Tests/ImageClassificationServiceTests.cs b/tests/TailoredApps.Shared.Mediator.ML.Tests/ImageClassificationServiceTests.cs index 10d7012..c4a63c8 100644 --- a/tests/TailoredApps.Shared.Mediator.ML.Tests/ImageClassificationServiceTests.cs +++ b/tests/TailoredApps.Shared.Mediator.ML.Tests/ImageClassificationServiceTests.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using Moq; using TailoredApps.Shared.Mediator.ImageClassification.Infrastructure; using TailoredApps.Shared.Mediator.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_Does_Not_Name_Its_Scores_Predict_Should_Leave_Scores_And_ModelInfo_Null() { // arrange var imageBytes = new byte[] { 1, 2, 3 }; @@ -44,6 +45,201 @@ public void When_Predict_Is_Called_Should_Map_Prediction_To_ImagePrediction() Assert.Null(prediction.ModelInfo); } + [Fact] + public void When_Adapter_Is_Not_The_One_The_Library_Registers_Predict_Should_Return_Scores_Without_Describing_The_File() + { + // 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 = service.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.Equal(new[] { "blue", "green", "red" }, prediction.ModelInfo.Labels); + } + + [Fact] + public void When_Model_File_Is_Replaced_But_The_Loaded_Model_Stays_Predict_Should_Keep_Describing_The_Loaded_Model() + { + // 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: 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.ModelInfo); + 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 + 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 = service.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_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")); + var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); + + // act + 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", 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" }); + var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); + + // act + var prediction = service.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 + 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 = service.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 +294,67 @@ 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 }); + } + + /// + /// 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.Mediator.ML.Tests/ModelHelperTests.cs b/tests/TailoredApps.Shared.Mediator.ML.Tests/ModelHelperTests.cs index eeeebb3..31c24ca 100644 --- a/tests/TailoredApps.Shared.Mediator.ML.Tests/ModelHelperTests.cs +++ b/tests/TailoredApps.Shared.Mediator.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.Mediator.ML.Tests/PredictionEnginePoolAdapterTests.cs b/tests/TailoredApps.Shared.Mediator.ML.Tests/PredictionEnginePoolAdapterTests.cs new file mode 100644 index 0000000..b4b0c9f --- /dev/null +++ b/tests/TailoredApps.Shared.Mediator.ML.Tests/PredictionEnginePoolAdapterTests.cs @@ -0,0 +1,236 @@ +using System; +using System.IO; +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.Mediator.ImageClassification.Infrastructure; +using TailoredApps.Shared.Mediator.ImageClassification.Interfaces.Domain.Models; +using TailoredApps.Shared.Mediator.ImageClassification.Interfaces.Infrastructure; +using Xunit; + +namespace TailoredApps.Shared.Mediator.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); + } + + [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(); + 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"); + } + + // 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); + 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 151a8f0e745c097baa8b5394ffa2f718a616e287 Mon Sep 17 00:00:00 2001 From: nieprzecietny Date: Wed, 2 Dec 2026 02:07:09 +0100 Subject: [PATCH 2/4] fix(ml): describe the model from the bytes it is loaded from Review of the previous commit: the description of the model file was read when a loaded model was first used. A file replaced between the loading of the pool and its first classification was then described as the model that predicts, and that description stayed for as long as the model lived. - FromModelFile(path, watchForChanges = true) is the library's own loader for the pool. It reads the checksum, the version and the model through one open file and records the description for that model instance, so a description can only be that of the bytes the model came from. With watchForChanges it loads the file again when it changes; a file that cannot be loaded leaves the current model in use. - ImagePrediction.ModelInfo comes only from that record. A model loaded in another way (the FromFile of ML.NET, a URI) has no ModelInfo: no file can be proven to be the model that predicted. Scores are not affected. - The registration examples, the demo and the 3.0 upgrade guide use FromModelFile. Tests against a real pool: the file replaced after loading and before the first prediction, replaced without a reload, replaced while watched, made unreadable while watched, and a model loaded with FromFile. --- docs-en/Libraries/Mediator/ML.md | 12 +- docs-en/Migration/v3.md | 20 ++ docs/Libraries/Mediator/ML.md | 12 +- docs/Migration/v3.md | 19 ++ .../Startup.cs | 2 +- .../AddPredictionEngineExtension.cs | 38 +++ .../Infrastructure/ClassificationService.cs | 57 +--- .../DescribedFileModelLoader.cs | 116 +++++++++ .../Infrastructure/LoadedModelDescriptions.cs | 46 ++++ .../Infrastructure/ModelHelper.cs | 32 ++- src/TailoredApps.Shared.Mediator.ML/README.md | 18 +- .../ImageClassificationServiceTests.cs | 112 +++----- .../ModelFileLoadingTests.cs | 246 ++++++++++++++++++ .../PredictionEnginePoolAdapterTests.cs | 56 ---- 14 files changed, 573 insertions(+), 213 deletions(-) create mode 100644 src/TailoredApps.Shared.Mediator.ML/Infrastructure/DescribedFileModelLoader.cs create mode 100644 src/TailoredApps.Shared.Mediator.ML/Infrastructure/LoadedModelDescriptions.cs create mode 100644 tests/TailoredApps.Shared.Mediator.ML.Tests/ModelFileLoadingTests.cs diff --git a/docs-en/Libraries/Mediator/ML.md b/docs-en/Libraries/Mediator/ML.md index dd96954..3a89701 100644 --- a/docs-en/Libraries/Mediator/ML.md +++ b/docs-en/Libraries/Mediator/ML.md @@ -41,12 +41,12 @@ builder.Services.AddPredictionEngine(config => { config.RegisterMachineLearningModel(pool => { - pool.FromFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!); + pool.FromModelFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!); }); }); ``` -`AddPredictionEngine` registers `IImageClassificationService`, `IModelInfoService` and `IModelHelper` (scoped) and binds `ImageClassificationOptions`. It does not register the mediator handlers - that is what scanning the library assembly is for. `RegisterMachineLearningModel` adds the ML.NET `PredictionEnginePool`; where the model is loaded from is decided by the pool builder (`FromFile` above). Register the model without a name: predictions use the default model of the pool. +`AddPredictionEngine` registers `IImageClassificationService`, `IModelInfoService` and `IModelHelper` (scoped) and binds `ImageClassificationOptions`. It does not register the mediator handlers - that is what scanning the library assembly is for. `RegisterMachineLearningModel` adds the ML.NET `PredictionEnginePool`; where the model is loaded from is decided by the pool builder (`FromModelFile` above). `FromModelFile(path, watchForChanges = true)` is the loader of this library: it describes the model (file name, checksum, version) from the same bytes it loads it from, which is what a prediction later reports in `ModelInfo`. Register the model without a name: predictions use the default model of the pool. The types live in the namespace `TailoredApps.Shared.Mediator.ImageClassification`, not under the package name. @@ -115,9 +115,9 @@ 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. -- **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. +- **Both belong to the model that made the prediction.** The labels are the ones the loaded model names its scores with. The description (file name, checksum, version) is recorded by `FromModelFile` when it loads the model, through the same open file, so it cannot be that of another file. Replacing the file later does not change what the predictions of an already loaded model report; with `watchForChanges` the pool loads the new file, and its predictions carry the new description. - **`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. +- **`ModelInfo` is `null`** when the model was loaded in another way (the `FromFile` of ML.NET, a URI), when the pool replaced the model while the prediction ran, and with your own `IPredictionEnginePoolAdapter`. In each of these cases no file can be proven to be the model that predicted, and a description read from the configured path could belong to another 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. @@ -154,6 +154,7 @@ Training reads the files with the extension `.jpg` or `.png` from the source dir | `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` | +| `AddPredictionEngineExtension.FromModelFile` | Ext. method | Loads the default model of the pool from a file (optionally watching it) and records its description from the same bytes; required for `ImagePrediction.ModelInfo` | | `AddPredictionEngineExtension.AddPredictionEngine` | Ext. method | Registers `IImageClassificationService`, `IModelInfoService`, `IModelHelper` and the options in DI (not the mediator handlers) | | `PredictionEngineServiceConfiguration.RegisterMachineLearningModel` | Method | Adds the ML.NET `PredictionEnginePool` and its adapter; called inside `AddPredictionEngine` | @@ -196,7 +197,7 @@ builder.Services.AddMediator(cfg => }); builder.Services.AddPredictionEngine(config => config.RegisterMachineLearningModel(pool => - pool.FromFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!))); + pool.FromModelFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!))); ``` ### What gets configured @@ -239,6 +240,7 @@ var result = await _mediator.Send(new TrainImageClassificationModel - 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 - Scores and ModelInfo of a prediction describe the model that made it, not the current content of the model file +- Load the model with pool.FromModelFile(path): with the FromFile of ML.NET a prediction has no ModelInfo - 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 diff --git a/docs-en/Migration/v3.md b/docs-en/Migration/v3.md index b832a60..461d115 100644 --- a/docs-en/Migration/v3.md +++ b/docs-en/Migration/v3.md @@ -78,6 +78,24 @@ The members marked `[Obsolete]` in 2.x are gone. The 2.x compiler warned about e The old configuration key is detected on purpose: if it were only ignored, a sandbox setup (`ApiUrl` holding the sandbox address) would, after the upgrade, silently connect to the production default of `ServiceUrl`. +### Image classification describes the model it loaded + +Since 2.1.1 a prediction carries the description of the model in `ImagePrediction.ModelInfo` (file name, checksum, version). In 2.x +that description was read from the configured model file when a loaded model was first used. In 3.0 it is recorded while the model is +loaded, from the same bytes, by the loader of the library: + +```csharp +// 2.x +pool.FromFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!); + +// 3.0 +pool.FromModelFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!); +``` + +With the `FromFile` of ML.NET the model still loads and `Scores` are still filled, but `ModelInfo` is `null`: a description read +afterwards could belong to another file than the one the model came from. `FromModelFile(path, watchForChanges = true)` watches the +file like `FromFile` does. + ### New packages for minimal APIs Two new packages of their own - they change nothing in the existing ones and nothing has to be migrated: @@ -122,6 +140,7 @@ Apart from that, the libraries have no change in 3.0 that requires code modifica | 7 | Stripe: handle an outage with `catch (HttpRequestException)` and a refusal with `PaymentStatus == Rejected`; remove `catch (StripeException)` around `RegisterPayment` and `GetStatus` | A Stripe outage bypasses the old `catch (StripeException)` block, and a refusal is no longer an exception and goes unhandled | | 8 | Review alerts and queries that count Error entries or `error.type` for 4xx answers | An alert on "validation errors" stops firing | | 9 | Replace `UtcTimeOfDaty` with `UtcTimeOfDay`, `AddExceptionHAndlingFilterAttribute` with `AddExceptionHandlingFilterAttribute`, and the `ApiUrl` key of the PayNow and Tpay configuration with `ServiceUrl` | A compile error, or a host that does not start | +| 10 | Image classification: replace `pool.FromFile(...)` with `pool.FromModelFile(...)` | `ImagePrediction.ModelInfo` is `null`, with no error | --- @@ -217,6 +236,7 @@ You are upgrading a .NET 10 or .NET 11 application from the TailoredApps.Shared. - The names and members of IRequest, IRequestHandler, IPipelineBehavior, IMediator, ISender, INotification do not change - Stripe: replace catch (StripeException) around RegisterPayment/GetStatus with catch (HttpRequestException) (outage) and a check of PaymentStatus == Rejected (refusal) - Alerts that count Error entries for validation failures stop working: validation is logged at Information level +- Image classification: pool.FromFile(path) -> pool.FromModelFile(path); with FromFile ImagePrediction.ModelInfo is null - UtcTimeOfDaty -> UtcTimeOfDay; AddExceptionHAndlingFilterAttribute -> AddExceptionHandlingFilterAttribute; in appsettings*.json, environment variables and secrets: Payments:Providers:PayNow:ApiUrl and Payments:Providers:Tpay:ApiUrl -> ServiceUrl (the old key stops the host from starting) ### Configuration diff --git a/docs/Libraries/Mediator/ML.md b/docs/Libraries/Mediator/ML.md index 52e17d9..c4ae821 100644 --- a/docs/Libraries/Mediator/ML.md +++ b/docs/Libraries/Mediator/ML.md @@ -41,12 +41,12 @@ builder.Services.AddPredictionEngine(config => { config.RegisterMachineLearningModel(pool => { - pool.FromFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!); + pool.FromModelFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!); }); }); ``` -`AddPredictionEngine` rejestruje `IImageClassificationService`, `IModelInfoService` i `IModelHelper` (scoped) oraz wiąże `ImageClassificationOptions`. Nie rejestruje handlerów mediatora — do tego służy skanowanie assembly biblioteki. `RegisterMachineLearningModel` dodaje `PredictionEnginePool` z ML.NET; o tym, skąd ładowany jest model, decyduje builder poola (powyżej `FromFile`). Model rejestruj bez nazwy: predykcje korzystają z domyślnego modelu poola. +`AddPredictionEngine` rejestruje `IImageClassificationService`, `IModelInfoService` i `IModelHelper` (scoped) oraz wiąże `ImageClassificationOptions`. Nie rejestruje handlerów mediatora — do tego służy skanowanie assembly biblioteki. `RegisterMachineLearningModel` dodaje `PredictionEnginePool` z ML.NET; o tym, skąd ładowany jest model, decyduje builder poola (powyżej `FromModelFile`). `FromModelFile(path, watchForChanges = true)` to loader tej biblioteki: opisuje model (nazwa pliku, checksum, wersja) na podstawie tych samych bajtów, z których go ładuje, i to ten opis predykcja zwraca potem w `ModelInfo`. Model rejestruj bez nazwy: predykcje korzystają z domyślnego modelu poola. Typy znajdują się w przestrzeni nazw `TailoredApps.Shared.Mediator.ImageClassification`, a nie pod nazwą pakietu. @@ -115,9 +115,9 @@ 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. -- **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. +- **Jedno i drugie należy do modelu, który wykonał predykcję.** Etykiety to te, którymi załadowany model nazywa swoje wyniki. Opis (nazwa pliku, checksum, wersja) zapisuje `FromModelFile` w chwili ładowania modelu, przez ten sam otwarty plik, więc nie może dotyczyć innego pliku. Późniejsza podmiana pliku nie zmienia tego, co zwracają predykcje już załadowanego modelu; z `watchForChanges` pula ładuje nowy plik, a jego predykcje mają nowy opis. - **`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. +- **`ModelInfo` ma wartość `null`**, gdy model załadowano w inny sposób (`FromFile` z ML.NET, URI), gdy pula podmieniła model w trakcie predykcji oraz przy własnej implementacji `IPredictionEnginePoolAdapter`. W każdym z tych przypadków nie da się wykazać, że dany plik jest modelem, który wykonał predykcję, a opis odczytany ze skonfigurowanej ścieżki mógłby dotyczyć innego 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. @@ -154,6 +154,7 @@ Trening czyta pliki z rozszerzeniem `.jpg` lub `.png` z katalogu źródłowego i | `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` | +| `AddPredictionEngineExtension.FromModelFile` | Metoda rozsz. | Ładuje domyślny model puli z pliku (opcjonalnie go obserwując) i zapisuje jego opis z tych samych bajtów; wymagane dla `ImagePrediction.ModelInfo` | | `AddPredictionEngineExtension.AddPredictionEngine` | Metoda ext. | Rejestruje w DI `IImageClassificationService`, `IModelInfoService`, `IModelHelper` i opcje (bez handlerów mediatora) | | `PredictionEngineServiceConfiguration.RegisterMachineLearningModel` | Metoda | Dodaje `PredictionEnginePool` z ML.NET i jego adapter; wywoływana wewnątrz `AddPredictionEngine` | @@ -196,7 +197,7 @@ builder.Services.AddMediator(cfg => }); builder.Services.AddPredictionEngine(config => config.RegisterMachineLearningModel(pool => - pool.FromFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!))); + pool.FromModelFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!))); ``` ### Co jest konfigurowane @@ -239,6 +240,7 @@ var result = await _mediator.Send(new TrainImageClassificationModel - 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` - Scores i ModelInfo predykcji opisują model, który ją wykonał, a nie obecną zawartość pliku modelu +- Ładuj model przez pool.FromModelFile(path): z FromFile z ML.NET predykcja nie ma ModelInfo - 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 diff --git a/docs/Migration/v3.md b/docs/Migration/v3.md index 6d2b586..459174f 100644 --- a/docs/Migration/v3.md +++ b/docs/Migration/v3.md @@ -78,6 +78,23 @@ Składowe oznaczone w 2.x jako `[Obsolete]` zostały usunięte. Kompilator 2.x o Stary klucz konfiguracji jest wykrywany celowo: gdyby był tylko pomijany, konfiguracja sandboxu (`ApiUrl` z adresem sandboxu) po aktualizacji łączyłaby się po cichu z produkcyjnym adresem domyślnym `ServiceUrl`. +### Klasyfikacja obrazów opisuje model, który załadowała + +Od 2.1.1 predykcja zawiera opis modelu w `ImagePrediction.ModelInfo` (nazwa pliku, checksum, wersja). W 2.x opis był czytany ze +skonfigurowanego pliku modelu przy pierwszym użyciu załadowanego modelu. W 3.0 zapisuje go loader biblioteki w chwili ładowania modelu, +z tych samych bajtów: + +```csharp +// 2.x +pool.FromFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!); + +// 3.0 +pool.FromModelFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!); +``` + +Z `FromFile` z ML.NET model nadal się ładuje, a `Scores` są wypełniane, ale `ModelInfo` ma wartość `null`: opis odczytany później mógłby +dotyczyć innego pliku niż ten, z którego pochodzi model. `FromModelFile(path, watchForChanges = true)` obserwuje plik tak jak `FromFile`. + ### Nowe paczki dla minimal API Dwie nowe, osobne paczki — nic nie zmieniają w istniejących i niczego nie trzeba migrować: @@ -121,6 +138,7 @@ Poza tym biblioteki nie mają w 3.0 zmian wymagających modyfikacji kodu. | 7 | Stripe: obsłużyć awarię przez `catch (HttpRequestException)`, a odmowę przez `PaymentStatus == Rejected`; usunąć `catch (StripeException)` wokół `RegisterPayment` i `GetStatus` | Awaria Stripe omija dotychczasowy blok `catch (StripeException)`, a odmowa nie jest wyjątkiem i zostaje nieobsłużona | | 8 | Przejrzeć alerty i zapytania, które liczą wpisy Error lub `error.type` dla odpowiedzi 4xx | Alert na „błędy walidacji” przestaje się uruchamiać | | 9 | Zamienić `UtcTimeOfDaty` na `UtcTimeOfDay`, `AddExceptionHAndlingFilterAttribute` na `AddExceptionHandlingFilterAttribute`, a w konfiguracji PayNow i Tpay klucz `ApiUrl` na `ServiceUrl` | Błąd kompilacji albo host, który nie startuje | +| 10 | Klasyfikacja obrazów: zamienić `pool.FromFile(...)` na `pool.FromModelFile(...)` | `ImagePrediction.ModelInfo` ma wartość `null`, bez błędu | --- @@ -216,6 +234,7 @@ Aktualizujesz aplikację .NET 10 lub .NET 11 z paczek TailoredApps.Shared.* 2.x - Nazwy i składowe IRequest, IRequestHandler, IPipelineBehavior, IMediator, ISender, INotification pozostają bez zmian - Stripe: catch (StripeException) wokół RegisterPayment/GetStatus zastąp catch (HttpRequestException) (awaria) i sprawdzeniem PaymentStatus == Rejected (odmowa) - Alerty liczące wpisy Error dla błędów walidacji przestaną działać: walidacja jest logowana na poziomie Information +- Klasyfikacja obrazów: pool.FromFile(path) -> pool.FromModelFile(path); z FromFile ImagePrediction.ModelInfo ma wartość null - UtcTimeOfDaty -> UtcTimeOfDay; AddExceptionHAndlingFilterAttribute -> AddExceptionHandlingFilterAttribute; w appsettings*.json, zmiennych środowiskowych i sekretach: Payments:Providers:PayNow:ApiUrl i Payments:Providers:Tpay:ApiUrl -> ServiceUrl (stary klucz zatrzymuje start hosta) ### Konfiguracja diff --git a/samples/TailoredApps.Shared.Demo.WebApi/Startup.cs b/samples/TailoredApps.Shared.Demo.WebApi/Startup.cs index ad1625f..3af659a 100644 --- a/samples/TailoredApps.Shared.Demo.WebApi/Startup.cs +++ b/samples/TailoredApps.Shared.Demo.WebApi/Startup.cs @@ -152,7 +152,7 @@ public void ConfigureServices(IServiceCollection services) if (imageClassification) { services.AddPredictionEngine(engine => - engine.RegisterMachineLearningModel(pool => pool.FromFile(imageModel!))); + engine.RegisterMachineLearningModel(pool => pool.FromModelFile(imageModel!))); } // ── Email: messages built from templates; the console provider prints them instead of sending ─────── diff --git a/src/TailoredApps.Shared.Mediator.ML/Infrastructure/AddPredictionEngineExtension.cs b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/AddPredictionEngineExtension.cs index 61e54a9..fc4fc29 100644 --- a/src/TailoredApps.Shared.Mediator.ML/Infrastructure/AddPredictionEngineExtension.cs +++ b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/AddPredictionEngineExtension.cs @@ -1,6 +1,8 @@ using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.ML; +using Microsoft.Extensions.Options; +using TailoredApps.Shared.Mediator.ImageClassification.Domain.DataModel.Models; using TailoredApps.Shared.Mediator.ImageClassification.Interfaces.Infrastructure; using TailoredApps.Shared.Mediator.ML.Infrastructure; using static TailoredApps.Shared.Mediator.ImageClassification.Infrastructure.ImageClassificationOptions; @@ -29,6 +31,42 @@ public static PredictionEnginePoolBuilder AddAdapter + /// Loads the default model of the pool from a file and describes it from the same bytes. Predictions of + /// a model loaded this way carry : the name of the file, its + /// checksum and its version, as they were when this model was loaded. + /// + /// The input data type for the prediction engine. + /// The output prediction type produced by the engine. + /// The prediction engine pool builder to extend. + /// The model file. + /// + /// Whether the pool loads the file again when it changes. Each loaded model keeps its own description. + /// + /// The original instance for chaining. + /// + /// With the FromFile of ML.NET the model is loaded by code that does not describe it, and a + /// description read later could belong to another file, so those predictions have no + /// . + /// + public static PredictionEnginePoolBuilder FromModelFile(this PredictionEnginePoolBuilder builder, string filePath, bool watchForChanges = true) + where TData : class + where TPrediction : class, new() + { + ArgumentNullException.ThrowIfNull(builder); + ArgumentException.ThrowIfNullOrWhiteSpace(filePath); + + builder.Services.AddLogging(); + builder.Services.AddTransient(); + builder.Services.AddOptions>(Options.DefaultName) + .Configure((options, loader) => + { + loader.Start(filePath, watchForChanges); + options.ModelLoader = loader; + }); + return builder; + } + /// /// Registers all image classification services, model helper, and prediction engine configuration /// into the dependency injection container. diff --git a/src/TailoredApps.Shared.Mediator.ML/Infrastructure/ClassificationService.cs b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/ClassificationService.cs index 29f0e31..5fefa87 100644 --- a/src/TailoredApps.Shared.Mediator.ML/Infrastructure/ClassificationService.cs +++ b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/ClassificationService.cs @@ -1,9 +1,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.IO; using System.Linq; -using System.Runtime.CompilerServices; using System.Text; using Microsoft.ML; using Microsoft.ML.Data; @@ -23,11 +21,6 @@ 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 . /// @@ -68,13 +61,13 @@ public ModelInfo GetModelInfo() /// /// /// 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. + /// The labels are the ones the loaded model names its scores with. The description is the one recorded + /// when that model was loaded, from the same bytes, by a pool configured with FromModelFile. /// 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. + /// when the model was loaded in another way (the FromFile of ML.NET, a URI), + /// when the pool replaced the model while the prediction ran, and when the adapter is not the one this + /// library registers: in each of these cases no file can be proven to be the model that predicted. /// public ImagePrediction Predict(byte[] image, string? fileName) { @@ -103,7 +96,7 @@ public ImagePrediction Predict(byte[] image, string? fileName) PredictedScore = scores.Max(), FileName = fileName, PredictedLabel = prediction.PredictedLabel, - ModelInfo = model == null ? null : DescribeModel(model, labels), + ModelInfo = DescribeModel(model, labels), Scores = MapScores(labels, scores) } ; @@ -124,28 +117,13 @@ private string[] GetLabels() return predictionEnginePool.GetLabels() ?? Array.Empty(); } - private ModelInfo? DescribeModel(object model, string[] labels) + private static ModelInfo? DescribeModel(object? model, string[] labels) { - var path = modelInfoService.ModelFilePath; - if (string.IsNullOrWhiteSpace(path)) + if (model == null || !LoadedModelDescriptions.TryGet(model, out var description)) { return null; } - if (!descriptions.TryGetValue(model, out var description) || !string.Equals(description.Path, path, StringComparison.Ordinal)) - { - 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); } @@ -168,25 +146,6 @@ 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.Mediator.ML/Infrastructure/DescribedFileModelLoader.cs b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/DescribedFileModelLoader.cs new file mode 100644 index 0000000..32cbc0d --- /dev/null +++ b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/DescribedFileModelLoader.cs @@ -0,0 +1,116 @@ +using System; +using System.IO; +using System.Threading; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.ML; +using Microsoft.Extensions.Options; +using Microsoft.Extensions.Primitives; +using Microsoft.ML; + +namespace TailoredApps.Shared.Mediator.ImageClassification.Infrastructure; + +/// +/// Loads the model of a prediction engine pool from a file and describes it from the same bytes: the +/// checksum, the version and the model itself are read through one open file, so the description cannot be +/// that of another file than the one the model came from. +/// +internal sealed class DescribedFileModelLoader : ModelLoader, IDisposable +{ + private readonly MLContext context; + private readonly ILogger logger; + private readonly object reloadLock = new(); + private string? filePath; + private FileSystemWatcher? watcher; + private CancellationTokenSource reloadSource = new(); + private ITransformer? model; + private string? checksum; + + public DescribedFileModelLoader(IOptions contextOptions, ILogger logger) + { + context = contextOptions.Value.MLContext; + this.logger = logger; + } + + /// Loads the model and, when asked to, starts watching its file. + public void Start(string modelFilePath, bool watchForChanges) + { + filePath = Path.GetFullPath(modelFilePath); + (model, checksum) = Load(filePath); + + if (watchForChanges) + { + watcher = new FileSystemWatcher(Path.GetDirectoryName(filePath)!, Path.GetFileName(filePath)); + watcher.Changed += (_, _) => Reload(); + watcher.Created += (_, _) => Reload(); + watcher.Renamed += (_, _) => Reload(); + watcher.EnableRaisingEvents = true; + } + } + + /// + public override ITransformer GetModel() + { + return model ?? throw new InvalidOperationException("The model loader has not been started."); + } + + /// + public override IChangeToken GetReloadToken() + { + return new CancellationChangeToken(reloadSource.Token); + } + + /// + public void Dispose() + { + watcher?.Dispose(); + } + + private (ITransformer Model, string Checksum) Load(string path) + { + // One handle for all three reads. Other readers are let in, writers are not; where the system does + // not enforce that, a file replaced by renaming still leaves this handle on the bytes it opened. + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); + var loadedChecksum = ModelHelper.ComputeChecksum(stream); + stream.Position = 0; + var version = ModelHelper.ReadVersion(stream); + stream.Position = 0; + var loaded = context.Model.Load(stream, out _); + + LoadedModelDescriptions.Set(loaded, new LoadedModelDescription(Path.GetFileName(path), loadedChecksum, version)); + return (loaded, loadedChecksum); + } + + private void Reload() + { + lock (reloadLock) + { + try + { + // The watcher reports one write several times; the same bytes are not loaded again. + if (string.Equals(ReadChecksum(filePath!), checksum, StringComparison.Ordinal)) + { + return; + } + + (model, checksum) = Load(filePath!); + } + catch (Exception exception) + { + // Most often the file is still being written: the watcher reports again when the writer is + // done, and until then the pool keeps the model it has. + logger.LogWarning(exception, "The model file {ModelFile} could not be reloaded; the loaded model stays in use.", Path.GetFileName(filePath)); + return; + } + } + + var previous = Interlocked.Exchange(ref reloadSource, new CancellationTokenSource()); + previous.Cancel(); + previous.Dispose(); + } + + private static string ReadChecksum(string path) + { + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); + return ModelHelper.ComputeChecksum(stream); + } +} diff --git a/src/TailoredApps.Shared.Mediator.ML/Infrastructure/LoadedModelDescriptions.cs b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/LoadedModelDescriptions.cs new file mode 100644 index 0000000..f9c1fb5 --- /dev/null +++ b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/LoadedModelDescriptions.cs @@ -0,0 +1,46 @@ +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace TailoredApps.Shared.Mediator.ImageClassification.Infrastructure; + +/// +/// What identifies a model file: read from the same bytes the model was loaded from. +/// +internal sealed class LoadedModelDescription +{ + public LoadedModelDescription(string name, string checksum, string version) + { + Name = name; + Checksum = checksum; + Version = version; + } + + /// The name of the file the model was loaded from. + public string Name { get; } + + /// The checksum of the bytes the model was loaded from. + public string Checksum { get; } + + /// The version stored in those bytes, or UNKNOWN. + public string Version { get; } +} + +/// +/// The descriptions of the models loaded by , by model. A description +/// lives exactly as long as its model, so a prediction can only be given the description of the model that +/// made it. +/// +internal static class LoadedModelDescriptions +{ + private static readonly ConditionalWeakTable descriptions = new(); + + public static void Set(object model, LoadedModelDescription description) + { + descriptions.AddOrUpdate(model, description); + } + + public static bool TryGet(object model, [NotNullWhen(true)] out LoadedModelDescription? description) + { + return descriptions.TryGetValue(model, out description); + } +} diff --git a/src/TailoredApps.Shared.Mediator.ML/Infrastructure/ModelHelper.cs b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/ModelHelper.cs index 2b5b985..1ab9556 100644 --- a/src/TailoredApps.Shared.Mediator.ML/Infrastructure/ModelHelper.cs +++ b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/ModelHelper.cs @@ -107,13 +107,33 @@ public string GetChecksum(string modelFilePath) return known.Checksum; } - using var md5 = MD5.Create(); using var stream = File.OpenRead(modelFilePath); - var checksum = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", string.Empty).ToLower(); + var checksum = ComputeChecksum(stream); checksums[file.FullName] = (file.Length, file.LastWriteTimeUtc, checksum); return checksum; } + // The lowercase MD5 of everything from the current position of the stream to its end. + internal static string ComputeChecksum(Stream stream) + { + using var md5 = MD5.Create(); + return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", string.Empty).ToLower(); + } + + // The version entry of a model archive, or UNKNOWN when it has none. The stream stays open. + internal static string ReadVersion(Stream stream) + { + using ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Read, leaveOpen: true); + ZipArchiveEntry? zipArchiveEntry = archive.GetEntry(versionFileName); + if (zipArchiveEntry != null) + { + using StreamReader streamReader = new StreamReader(zipArchiveEntry.Open()); + return streamReader.ReadLine() ?? "UNKNOWN"; + } + + return "UNKNOWN"; + } + /// /// Reads the version string from the model zip archive. /// @@ -126,13 +146,7 @@ public string GetVersion(string modelFilePath) try { using FileStream fileStream = OpenForReading(modelFilePath); - using ZipArchive archive = new ZipArchive(fileStream, ZipArchiveMode.Read); - ZipArchiveEntry? zipArchiveEntry = archive.GetEntry(versionFileName); - if (zipArchiveEntry != null) - { - using StreamReader streamReader = new StreamReader(zipArchiveEntry.Open()); - return streamReader.ReadLine() ?? "UNKNOWN"; - } + return ReadVersion(fileStream); } catch (Exception) { diff --git a/src/TailoredApps.Shared.Mediator.ML/README.md b/src/TailoredApps.Shared.Mediator.ML/README.md index 7a515b3..43bac38 100644 --- a/src/TailoredApps.Shared.Mediator.ML/README.md +++ b/src/TailoredApps.Shared.Mediator.ML/README.md @@ -26,12 +26,13 @@ builder.Services.AddMediator(cfg => builder.Services.AddPredictionEngine(engine => engine.RegisterMachineLearningModel(pool => - pool.FromFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!))); + pool.FromModelFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!))); ``` `AddPredictionEngine` registers `IImageClassificationService`, `IModelInfoService` and `IModelHelper` (scoped) and binds `ImageClassificationOptions`. `RegisterMachineLearningModel` adds the ML.NET `PredictionEnginePool`; -where the model is loaded from is decided by the pool builder you configure (`FromFile` above), not by the options. +where the model is loaded from is decided by the pool builder you configure (`FromModelFile` above), not by the +options. `FromModelFile` is the loader of this library: it describes the model from the same bytes it loads it from. ## Usage @@ -82,13 +83,14 @@ The `ImageClassification` section: 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`. 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. + prediction: the labels are the ones the loaded model names its scores with, and the description (file name, + checksum, version) is recorded by `FromModelFile` when it loads the model, from the same bytes. Replacing + the file later does not change what the predictions of an already loaded model report; with + `watchForChanges` the pool loads the new file and its predictions carry the new description. - `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. + `ModelInfo` is `null` when the model was loaded in another way (the `FromFile` of ML.NET, a URI), when the + pool replaced the model while the prediction ran, and with your own `IPredictionEnginePoolAdapter`: in each + case no file can be proven to be the model that predicted. - `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. diff --git a/tests/TailoredApps.Shared.Mediator.ML.Tests/ImageClassificationServiceTests.cs b/tests/TailoredApps.Shared.Mediator.ML.Tests/ImageClassificationServiceTests.cs index c4a63c8..77dcedc 100644 --- a/tests/TailoredApps.Shared.Mediator.ML.Tests/ImageClassificationServiceTests.cs +++ b/tests/TailoredApps.Shared.Mediator.ML.Tests/ImageClassificationServiceTests.cs @@ -1,5 +1,4 @@ using System; -using System.IO; using Moq; using TailoredApps.Shared.Mediator.ImageClassification.Infrastructure; using TailoredApps.Shared.Mediator.ImageClassification.Interfaces.Domain.Models; @@ -46,9 +45,9 @@ public void When_Model_Does_Not_Name_Its_Scores_Predict_Should_Leave_Scores_And_ } [Fact] - public void When_Adapter_Is_Not_The_One_The_Library_Registers_Predict_Should_Return_Scores_Without_Describing_The_File() + public void When_Adapter_Is_Not_The_One_The_Library_Registers_Predict_Should_Return_Scores_Without_A_Model_Description() { - // arrange: the model behind a foreign adapter cannot be told apart from the file, so it is not described + // arrange: the model behind a foreign adapter cannot be identified, so no file is attributed to it SetupModelFile(new[] { "circle", "square", "triangle" }); predictionEnginePoolMock.Setup(p => p.GetLabels()).Returns(new[] { "blue", "green", "red" }); SetupPrediction("blue", 0.6f, 0.3f, 0.1f); @@ -67,11 +66,12 @@ public void When_Adapter_Is_Not_The_One_The_Library_Registers_Predict_Should_Ret } [Fact] - public void When_Predict_Is_Called_Should_Return_Every_Score_And_The_Description_Of_The_Model_That_Made_It() + public void When_Predict_Is_Called_Should_Return_Every_Score_And_The_Description_Recorded_When_The_Model_Was_Loaded() { - // arrange: the file's own Labels.txt says something else than the loaded model + // arrange: the configured file says something else than the loaded model, in every respect var loaded = new ModelBoundAdapter { Labels = new[] { "blue", "green", "red" } }; loaded.Returns("green", 0.1f, 0.7f, 0.2f); + LoadedModelDescriptions.Set(loaded.Model, new LoadedModelDescription("colours.zip", "loaded-checksum", "20260820.101010")); SetupModelFile(new[] { "circle", "square", "triangle" }); var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); @@ -87,60 +87,57 @@ public void When_Predict_Is_Called_Should_Return_Every_Score_And_The_Description 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("colours.zip", prediction.ModelInfo.Name); + Assert.Equal("loaded-checksum", prediction.ModelInfo.Checksum); Assert.Equal("20260820.101010", prediction.ModelInfo.Version); Assert.Equal(new[] { "blue", "green", "red" }, prediction.ModelInfo.Labels); + modelInfoServiceMock.VerifyGet(m => m.ModelChecksum, Times.Never); + modelInfoServiceMock.VerifyGet(m => m.ModelVersion, Times.Never); + modelInfoServiceMock.VerifyGet(m => m.Labels, Times.Never); } [Fact] - public void When_Model_File_Is_Replaced_But_The_Loaded_Model_Stays_Predict_Should_Keep_Describing_The_Loaded_Model() + public void When_Model_Was_Not_Described_When_It_Was_Loaded_Predict_Should_Leave_ModelInfo_Null() { - // arrange + // arrange: a model loaded in a way that does not describe it, next to a configured model file 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: 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"); + // act + var prediction = service.Predict(new byte[] { 1, 2, 3 }, "testgreen.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"]); + // assert: the file is not attributed to the model, however plausible it looks + 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_Pool_Loads_Another_Model_Predict_Should_Describe_The_File_Again() + public void When_Pool_Loads_Another_Model_Predict_Should_Return_The_Description_Of_That_Model() { // arrange var loaded = new ModelBoundAdapter { Labels = new[] { "blue", "green", "red" } }; loaded.Returns("green", 0.1f, 0.7f, 0.2f); - SetupModelFile(new[] { "blue", "green", "red" }); + LoadedModelDescriptions.Set(loaded.Model, new LoadedModelDescription("model.zip", "first", "20260820.101010")); var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); - service.Predict(new byte[] { 1, 2, 3 }, "first.png"); + var before = 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"); + // act: the pool reloaded the file 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"); + LoadedModelDescriptions.Set(loaded.Model, new LoadedModelDescription("model.zip", "second", "20270101.000000")); + var after = service.Predict(new byte[] { 1, 2, 3 }, "second.png"); // assert - Assert.NotNull(prediction.ModelInfo); - 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"]); + Assert.Equal("first", before.ModelInfo.Checksum); + Assert.Equal("second", after.ModelInfo.Checksum); + Assert.Equal("20270101.000000", after.ModelInfo.Version); + Assert.Equal(new[] { "circle", "square", "triangle" }, after.ModelInfo.Labels); + Assert.Equal(0.5f, after.Scores["square"]); } [Fact] @@ -149,60 +146,15 @@ public void When_Pool_Replaces_The_Model_During_A_Prediction_Predict_Should_Not_ // 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: the scores carry the labels of the engine that made them; no model is named 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 - 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 = service.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_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")); - var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); - - // act - 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", 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] @@ -211,7 +163,7 @@ 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" }); + LoadedModelDescriptions.Set(loaded.Model, new LoadedModelDescription("model.zip", "abc123", "20260820.101010")); var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); // act diff --git a/tests/TailoredApps.Shared.Mediator.ML.Tests/ModelFileLoadingTests.cs b/tests/TailoredApps.Shared.Mediator.ML.Tests/ModelFileLoadingTests.cs new file mode 100644 index 0000000..fe4f323 --- /dev/null +++ b/tests/TailoredApps.Shared.Mediator.ML.Tests/ModelFileLoadingTests.cs @@ -0,0 +1,246 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.ML; +using Microsoft.Extensions.Options; +using Microsoft.ML; +using TailoredApps.Shared.Mediator.ImageClassification.Domain.DataModel.Models; +using TailoredApps.Shared.Mediator.ImageClassification.Infrastructure; +using TailoredApps.Shared.Mediator.ImageClassification.Interfaces.Domain.Models; +using TailoredApps.Shared.Mediator.ImageClassification.Interfaces.Infrastructure; +using Xunit; + +namespace TailoredApps.Shared.Mediator.ML.Tests; + +/// +/// The whole path from a model file to a prediction, against a real prediction engine pool: which model a +/// prediction says it came from when the file is loaded, replaced, reloaded or loaded in another way. +/// The models are small classifiers trained here; they tell the label from the file name. +/// +public class ModelFileLoadingTests : IDisposable +{ + private static readonly string[] Colours = { "blue", "green", "red" }; + private static readonly string[] Shapes = { "circle", "square", "triangle" }; + + private readonly ModelHelper modelHelper = new ModelHelper(); + private readonly string workFolder; + private readonly string modelPath; + + public ModelFileLoadingTests() + { + workFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(workFolder); + modelPath = Path.Combine(workFolder, "model.zip"); + } + + public void Dispose() + { + if (Directory.Exists(workFolder)) + { + Directory.Delete(workFolder, recursive: true); + } + } + + [Fact] + public void When_Model_Is_Loaded_With_FromModelFile_Prediction_Should_Describe_The_Loaded_File() + { + // arrange + var version = SaveModel(modelPath, Colours); + var checksum = modelHelper.GetChecksum(modelPath); + using var provider = BuildProvider(pool => pool.FromModelFile(modelPath, watchForChanges: false)); + var sut = CreateService(provider); + + // act + var prediction = sut.Predict(new byte[] { 1 }, "red-7.png"); + + // assert + Assert.Equal("red", prediction.PredictedLabel); + Assert.Equal(Colours, prediction.Scores.Keys.ToArray()); + Assert.Equal(prediction.PredictedScore, prediction.Scores["red"]); + Assert.NotNull(prediction.ModelInfo); + Assert.Equal("model.zip", prediction.ModelInfo.Name); + Assert.Equal(checksum, prediction.ModelInfo.Checksum); + Assert.Equal(version, prediction.ModelInfo.Version); + Assert.Equal(Colours, prediction.ModelInfo.Labels); + } + + [Fact] + public void When_Model_File_Is_Replaced_After_Loading_But_Before_The_First_Prediction_Should_Describe_The_Loaded_Model() + { + // arrange: the pool loads the colours; nothing has been classified yet + var version = SaveModel(modelPath, Colours); + var checksum = modelHelper.GetChecksum(modelPath); + using var provider = BuildProvider(pool => pool.FromModelFile(modelPath, watchForChanges: false)); + var sut = CreateService(provider); + + // act: the shapes take the file's place, with their own version and labels, and only then comes + // the first classification + ReplaceModel(Shapes); + var prediction = sut.Predict(new byte[] { 1 }, "red-7.png"); + + // assert: the colours predicted, and it is the colours that are described + Assert.NotEqual(checksum, modelHelper.GetChecksum(modelPath)); + Assert.Equal("red", prediction.PredictedLabel); + Assert.Equal(Colours, prediction.Scores.Keys.ToArray()); + Assert.Equal(checksum, prediction.ModelInfo.Checksum); + Assert.Equal(version, prediction.ModelInfo.Version); + Assert.Equal(Colours, prediction.ModelInfo.Labels); + } + + [Fact] + public void When_Model_File_Is_Replaced_Without_A_Reload_Predictions_Should_Keep_Describing_The_Loaded_Model() + { + // arrange + SaveModel(modelPath, Colours); + var checksum = modelHelper.GetChecksum(modelPath); + using var provider = BuildProvider(pool => pool.FromModelFile(modelPath, watchForChanges: false)); + var sut = CreateService(provider); + var before = sut.Predict(new byte[] { 1 }, "red-7.png"); + + // act + ReplaceModel(Shapes); + var after = sut.Predict(new byte[] { 1 }, "red-8.png"); + + // assert + Assert.Equal(checksum, before.ModelInfo.Checksum); + Assert.Equal(checksum, after.ModelInfo.Checksum); + Assert.Equal("red", after.PredictedLabel); + Assert.Equal(Colours, after.Scores.Keys.ToArray()); + } + + [Fact] + public void When_Watched_Model_File_Is_Replaced_Predictions_Should_Move_To_The_New_Model_With_Its_Own_Description() + { + // arrange + SaveModel(modelPath, Colours); + var firstChecksum = modelHelper.GetChecksum(modelPath); + using var provider = BuildProvider(pool => pool.FromModelFile(modelPath, watchForChanges: true)); + var sut = CreateService(provider); + Assert.Equal(firstChecksum, sut.Predict(new byte[] { 1 }, "red-7.png").ModelInfo.Checksum); + + // act + var secondVersion = ReplaceModel(Shapes); + var secondChecksum = modelHelper.GetChecksum(modelPath); + ImagePrediction prediction = null; + var watch = Stopwatch.StartNew(); + while (watch.Elapsed < TimeSpan.FromSeconds(30)) + { + prediction = sut.Predict(new byte[] { 1 }, "square-3.png"); + if (prediction.ModelInfo != null && prediction.ModelInfo.Checksum == secondChecksum) + { + break; + } + + Thread.Sleep(100); + } + + // assert: never a mix of one model's scores with the other's description + Assert.NotNull(prediction.ModelInfo); + Assert.Equal(secondChecksum, prediction.ModelInfo.Checksum); + Assert.Equal(secondVersion, prediction.ModelInfo.Version); + Assert.Equal(Shapes, prediction.ModelInfo.Labels); + Assert.Equal(Shapes, prediction.Scores.Keys.ToArray()); + Assert.Equal("square", prediction.PredictedLabel); + } + + [Fact] + public void When_Watched_Model_File_Becomes_Unreadable_Predictions_Should_Stay_With_The_Loaded_Model() + { + // arrange + SaveModel(modelPath, Colours); + var checksum = modelHelper.GetChecksum(modelPath); + using var provider = BuildProvider(pool => pool.FromModelFile(modelPath, watchForChanges: true)); + var sut = CreateService(provider); + sut.Predict(new byte[] { 1 }, "red-7.png"); + + // act: something that is not a model lands in the file + File.WriteAllText(modelPath, "not a model"); + Thread.Sleep(1500); + var prediction = sut.Predict(new byte[] { 1 }, "red-8.png"); + + // assert + Assert.Equal("red", prediction.PredictedLabel); + Assert.Equal(checksum, prediction.ModelInfo.Checksum); + } + + [Fact] + public void When_Model_Is_Loaded_With_FromFile_Prediction_Should_Have_Scores_But_No_Model_Description() + { + // arrange: loaded by ML.NET, which does not describe what it loads, with the same file configured + SaveModel(modelPath, Colours); + using var provider = BuildProvider(pool => pool.FromFile(modelPath, watchForChanges: false)); + var sut = CreateService(provider); + + // act + var prediction = sut.Predict(new byte[] { 1 }, "red-7.png"); + + // assert + Assert.Equal("red", prediction.PredictedLabel); + Assert.Equal(Colours, prediction.Scores.Keys.ToArray()); + Assert.Null(prediction.ModelInfo); + } + + [Fact] + public void When_FromModelFile_Is_Given_No_Path_Should_Throw_ArgumentException() + { + // arrange + var builder = new ServiceCollection().AddPredictionEnginePool(); + + // act & assert + Assert.Throws(() => builder.FromModelFile(null)); + Assert.Throws(() => builder.FromModelFile(" ")); + } + + private static ServiceProvider BuildProvider(Action> load) + { + var services = new ServiceCollection(); + load(services.AddPredictionEnginePool().AddAdapter()); + return services.BuildServiceProvider(); + } + + private ImageClassificationService CreateService(ServiceProvider provider) + { + var adapter = provider.GetRequiredService>(); + var options = Options.Create(new ImageClassificationOptions { ModelFilePath = modelPath }); + return new ImageClassificationService(adapter, new ModelInfoService(options, modelHelper)); + } + + // Writes the next model beside the model file and moves it into place, the way a deployment replaces a + // file: readers see either the old file or the new one, never a half-written one. + private string ReplaceModel(string[] labels) + { + var next = Path.Combine(workFolder, "next.zip"); + var version = SaveModel(next, labels, versionOffset: TimeSpan.FromDays(1)); + modelHelper.AddLabels(next, labels); + File.Move(next, modelPath, overwrite: true); + return version; + } + + private string SaveModel(string path, string[] labels, TimeSpan versionOffset = default) + { + 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")); + mlContext.Model.Save(pipeline.Fit(data), data.Schema, path); + + // AddVersion stamps the current second; two models saved within one second still get different versions. + var version = (DateTime.Now + versionOffset).ToString("yyyyMMdd.HHmmss"); + using (var archive = System.IO.Compression.ZipFile.Open(path, System.IO.Compression.ZipArchiveMode.Update)) + using (var writer = new StreamWriter(archive.CreateEntry("Version.txt").Open())) + { + writer.WriteLine(version); + } + + return version; + } +} diff --git a/tests/TailoredApps.Shared.Mediator.ML.Tests/PredictionEnginePoolAdapterTests.cs b/tests/TailoredApps.Shared.Mediator.ML.Tests/PredictionEnginePoolAdapterTests.cs index b4b0c9f..97cffb9 100644 --- a/tests/TailoredApps.Shared.Mediator.ML.Tests/PredictionEnginePoolAdapterTests.cs +++ b/tests/TailoredApps.Shared.Mediator.ML.Tests/PredictionEnginePoolAdapterTests.cs @@ -3,11 +3,9 @@ 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.Mediator.ImageClassification.Infrastructure; -using TailoredApps.Shared.Mediator.ImageClassification.Interfaces.Domain.Models; using TailoredApps.Shared.Mediator.ImageClassification.Interfaces.Infrastructure; using Xunit; @@ -101,42 +99,6 @@ public void When_Predicting_With_The_Model_Should_Return_The_Labels_And_The_Mode 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(); @@ -170,24 +132,6 @@ 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); From 03efb267fc967fbe109b65bdebdbe1948784eae0 Mon Sep 17 00:00:00 2001 From: nieprzecietny Date: Wed, 2 Dec 2026 02:21:53 +0100 Subject: [PATCH 3/4] fix(ml): replace a watched model atomically for predictions, retry a reload that failed Review of the previous commit, both about a watched model file (watchForChanges): - A prediction could pair the scores of the old model with the description of the new one. The loader handed out the new model before the pool, called back through the reload token, built its new engines, so for a moment the pool's model and its engines belonged to different models. An engine borrowed before the replacement was also put back among the new engines and kept predicting with the old model. Predictions (every call that borrows an engine) now run on the shared side of a gate and the replacement, with the pool's callback, on its exclusive side: a prediction sees the model and the engines of one generation, and no engine of the previous model survives the replacement. - A reload that failed was tried again only when the system reported another change. A writer that keeps the file open after its last write leaves no such change, and the old model stayed in use for good. The loader now comes back on its own, with growing delays, for about a minute after the last reported change. Tests, both failing before this change: four threads classifying while the file is replaced (no prediction mixes two models, and afterwards 200 predictions in a row come from the new one), and a file written in place through an exclusive handle that stays open after the last write. --- docs-en/Libraries/Mediator/ML.md | 2 +- docs/Libraries/Mediator/ML.md | 2 +- .../DescribedFileModelLoader.cs | 102 +++++++++++++-- .../Infrastructure/LoadedModelDescriptions.cs | 43 +++++++ .../PredictionEnginePoolAdapter.cs | 58 +++++---- src/TailoredApps.Shared.Mediator.ML/README.md | 5 +- .../ModelFileLoadingTests.cs | 116 +++++++++++++++++- 7 files changed, 286 insertions(+), 42 deletions(-) diff --git a/docs-en/Libraries/Mediator/ML.md b/docs-en/Libraries/Mediator/ML.md index 3a89701..e83c2c9 100644 --- a/docs-en/Libraries/Mediator/ML.md +++ b/docs-en/Libraries/Mediator/ML.md @@ -115,7 +115,7 @@ 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. -- **Both belong to the model that made the prediction.** The labels are the ones the loaded model names its scores with. The description (file name, checksum, version) is recorded by `FromModelFile` when it loads the model, through the same open file, so it cannot be that of another file. Replacing the file later does not change what the predictions of an already loaded model report; with `watchForChanges` the pool loads the new file, and its predictions carry the new description. +- **Both belong to the model that made the prediction.** The labels are the ones the loaded model names its scores with. The description (file name, checksum, version) is recorded by `FromModelFile` when it loads the model, through the same open file, so it cannot be that of another file. Replacing the file later does not change what the predictions of an already loaded model report; with `watchForChanges` the pool loads the new file, and its predictions carry the new description. A prediction never combines the scores of one model with the description of the other, also while the file is being replaced under load. A file that cannot be read yet (still being written, or held by its writer) is tried again for about a minute after the last change; until it loads, the loaded model stays in use. - **`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 the model was loaded in another way (the `FromFile` of ML.NET, a URI), when the pool replaced the model while the prediction ran, and with your own `IPredictionEnginePoolAdapter`. In each of these cases no file can be proven to be the model that predicted, and a description read from the configured path could belong to another 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. diff --git a/docs/Libraries/Mediator/ML.md b/docs/Libraries/Mediator/ML.md index c4ae821..d0005ef 100644 --- a/docs/Libraries/Mediator/ML.md +++ b/docs/Libraries/Mediator/ML.md @@ -115,7 +115,7 @@ 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. -- **Jedno i drugie należy do modelu, który wykonał predykcję.** Etykiety to te, którymi załadowany model nazywa swoje wyniki. Opis (nazwa pliku, checksum, wersja) zapisuje `FromModelFile` w chwili ładowania modelu, przez ten sam otwarty plik, więc nie może dotyczyć innego pliku. Późniejsza podmiana pliku nie zmienia tego, co zwracają predykcje już załadowanego modelu; z `watchForChanges` pula ładuje nowy plik, a jego predykcje mają nowy opis. +- **Jedno i drugie należy do modelu, który wykonał predykcję.** Etykiety to te, którymi załadowany model nazywa swoje wyniki. Opis (nazwa pliku, checksum, wersja) zapisuje `FromModelFile` w chwili ładowania modelu, przez ten sam otwarty plik, więc nie może dotyczyć innego pliku. Późniejsza podmiana pliku nie zmienia tego, co zwracają predykcje już załadowanego modelu; z `watchForChanges` pula ładuje nowy plik, a jego predykcje mają nowy opis. Predykcja nigdy nie łączy wyników jednego modelu z opisem drugiego, także gdy plik jest podmieniany pod obciążeniem. Plik, którego nie da się jeszcze odczytać (nadal zapisywany albo trzymany przez piszącego), jest próbowany ponownie przez około minutę od ostatniej zmiany; dopóki się nie załaduje, w użyciu zostaje załadowany model. - **`Scores` ma wartość `null`**, gdy model nie nazywa swoich wyników albo nazwy nie odpowiadają im jeden do jednego. - **`ModelInfo` ma wartość `null`**, gdy model załadowano w inny sposób (`FromFile` z ML.NET, URI), gdy pula podmieniła model w trakcie predykcji oraz przy własnej implementacji `IPredictionEnginePoolAdapter`. W każdym z tych przypadków nie da się wykazać, że dany plik jest modelem, który wykonał predykcję, a opis odczytany ze skonfigurowanej ścieżki mógłby dotyczyć innego 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. diff --git a/src/TailoredApps.Shared.Mediator.ML/Infrastructure/DescribedFileModelLoader.cs b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/DescribedFileModelLoader.cs index 32cbc0d..659cdd5 100644 --- a/src/TailoredApps.Shared.Mediator.ML/Infrastructure/DescribedFileModelLoader.cs +++ b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/DescribedFileModelLoader.cs @@ -16,11 +16,26 @@ namespace TailoredApps.Shared.Mediator.ImageClassification.Infrastructure; /// internal sealed class DescribedFileModelLoader : ModelLoader, IDisposable { + // After the last change reported for the file: about a minute of attempts in all. + private static readonly TimeSpan[] RetryDelays = + { + TimeSpan.FromMilliseconds(500), + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(4), + TimeSpan.FromSeconds(8), + TimeSpan.FromSeconds(15), + TimeSpan.FromSeconds(30), + }; + private readonly MLContext context; private readonly ILogger logger; private readonly object reloadLock = new(); private string? filePath; private FileSystemWatcher? watcher; + private Timer? retryTimer; + private int failedAttempts; + private volatile bool disposed; private CancellationTokenSource reloadSource = new(); private ITransformer? model; private string? checksum; @@ -39,10 +54,11 @@ public void Start(string modelFilePath, bool watchForChanges) if (watchForChanges) { + retryTimer = new Timer(_ => Reload(), null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); watcher = new FileSystemWatcher(Path.GetDirectoryName(filePath)!, Path.GetFileName(filePath)); - watcher.Changed += (_, _) => Reload(); - watcher.Created += (_, _) => Reload(); - watcher.Renamed += (_, _) => Reload(); + watcher.Changed += (_, _) => OnFileChanged(); + watcher.Created += (_, _) => OnFileChanged(); + watcher.Renamed += (_, _) => OnFileChanged(); watcher.EnableRaisingEvents = true; } } @@ -62,7 +78,9 @@ public override IChangeToken GetReloadToken() /// public void Dispose() { + disposed = true; watcher?.Dispose(); + retryTimer?.Dispose(); } private (ITransformer Model, string Checksum) Load(string path) @@ -80,32 +98,94 @@ public void Dispose() return (loaded, loadedChecksum); } + // A change reported by the system is new information: the attempts start over. + private void OnFileChanged() + { + Interlocked.Exchange(ref failedAttempts, 0); + Reload(); + } + private void Reload() { + if (disposed) + { + return; + } + lock (reloadLock) { + ITransformer loaded; + string loadedChecksum; try { - // The watcher reports one write several times; the same bytes are not loaded again. + // One write is reported several times; the same bytes are not loaded again. if (string.Equals(ReadChecksum(filePath!), checksum, StringComparison.Ordinal)) { + Interlocked.Exchange(ref failedAttempts, 0); return; } - (model, checksum) = Load(filePath!); + (loaded, loadedChecksum) = Load(filePath!); } catch (Exception exception) { - // Most often the file is still being written: the watcher reports again when the writer is - // done, and until then the pool keeps the model it has. - logger.LogWarning(exception, "The model file {ModelFile} could not be reloaded; the loaded model stays in use.", Path.GetFileName(filePath)); + RetryLater(exception); return; } + + Interlocked.Exchange(ref failedAttempts, 0); + Publish(loaded, loadedChecksum); + } + } + + // The loader starts handing out the new model and the pool, called back through the reload token, builds + // its new engines: both inside the gate, so no prediction sees one without the other. + private void Publish(ITransformer loaded, string loadedChecksum) + { + CancellationTokenSource? previous = null; + try + { + LoadedModelGate.Replace(() => + { + model = loaded; + checksum = loadedChecksum; + previous = Interlocked.Exchange(ref reloadSource, new CancellationTokenSource()); + previous.Cancel(); + }); + } + catch (Exception exception) + { + // Thrown by a callback registered on the reload token, after the model was replaced. + logger.LogError(exception, "A reload callback of the model file {ModelFile} failed.", Path.GetFileName(filePath)); + } + finally + { + previous?.Dispose(); + } + } + + // Most often the file is still being written, or its writer still holds it. No further change may be + // reported once the writer lets go, so the loader comes back on its own; until it succeeds the pool keeps + // the model it has. + private void RetryLater(Exception exception) + { + var attempt = Interlocked.Increment(ref failedAttempts); + if (attempt > RetryDelays.Length || retryTimer == null || disposed) + { + logger.LogWarning(exception, "The model file {ModelFile} could not be reloaded; the loaded model stays in use until the file changes again.", Path.GetFileName(filePath)); + return; } - var previous = Interlocked.Exchange(ref reloadSource, new CancellationTokenSource()); - previous.Cancel(); - previous.Dispose(); + var delay = RetryDelays[attempt - 1]; + logger.LogDebug(exception, "The model file {ModelFile} could not be reloaded; next attempt in {Delay}.", Path.GetFileName(filePath), delay); + try + { + retryTimer.Change(delay, Timeout.InfiniteTimeSpan); + } + catch (ObjectDisposedException) + { + // Disposed between the check and the call: nothing left to retry for. + } } private static string ReadChecksum(string path) diff --git a/src/TailoredApps.Shared.Mediator.ML/Infrastructure/LoadedModelDescriptions.cs b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/LoadedModelDescriptions.cs index f9c1fb5..1ef64c0 100644 --- a/src/TailoredApps.Shared.Mediator.ML/Infrastructure/LoadedModelDescriptions.cs +++ b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/LoadedModelDescriptions.cs @@ -1,5 +1,7 @@ +using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; +using System.Threading; namespace TailoredApps.Shared.Mediator.ImageClassification.Infrastructure; @@ -44,3 +46,44 @@ public static bool TryGet(object model, [NotNullWhen(true)] out LoadedModelDescr return descriptions.TryGetValue(model, out description); } } + +/// +/// Keeps a prediction and the replacement of a model apart. A pool replaces its model in two steps (the loader +/// starts handing out the new model, then the pool builds new engines), and an engine borrowed before the +/// replacement would be put back among the new ones. Predictions run on the shared side of this gate, a +/// replacement on the exclusive side: a prediction sees the model and the engines of one generation, and no +/// engine of the previous model survives the replacement. +/// +internal static class LoadedModelGate +{ + // Recursion is allowed because the pool's reload callbacks run inside the replacement, on its thread. + private static readonly ReaderWriterLockSlim gate = new(LockRecursionPolicy.SupportsRecursion); + + /// Runs a prediction, or anything else that borrows an engine. + public static T Predict(Func prediction) + { + gate.EnterReadLock(); + try + { + return prediction(); + } + finally + { + gate.ExitReadLock(); + } + } + + /// Replaces a model: waits for the predictions under way and holds back new ones meanwhile. + public static void Replace(Action replacement) + { + gate.EnterWriteLock(); + try + { + replacement(); + } + finally + { + gate.ExitWriteLock(); + } + } +} diff --git a/src/TailoredApps.Shared.Mediator.ML/Infrastructure/PredictionEnginePoolAdapter.cs b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/PredictionEnginePoolAdapter.cs index 277af30..bb6b369 100644 --- a/src/TailoredApps.Shared.Mediator.ML/Infrastructure/PredictionEnginePoolAdapter.cs +++ b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/PredictionEnginePoolAdapter.cs @@ -39,17 +39,20 @@ public PredictionEnginePoolAdapter(PredictionEnginePool pred /// public string[] GetLabels() { - var predictionEngine = predictionEnginePool.GetPredictionEngine(); - try + return LoadedModelGate.Predict(() => { - return ReadLabels(predictionEngine.OutputSchema); - } - 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); - } + var predictionEngine = predictionEnginePool.GetPredictionEngine(); + try + { + return ReadLabels(predictionEngine.OutputSchema); + } + 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); + } + }); } /// @@ -57,22 +60,25 @@ public string[] GetLabels() /// ModelBoundPrediction IModelBoundPredictionEngine.PredictWithModel(TData example) { - var modelBefore = predictionEnginePool.GetModel(); - var predictionEngine = predictionEnginePool.GetPredictionEngine(); - try + return LoadedModelGate.Predict(() => { - 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); - } + // Inside the gate a model loaded with FromModelFile cannot be replaced, so the model read here is + // the one the borrowed engine was built from. Comparing it before and after covers loaders that do + // not take part in the gate: a change in between means the engine's model is not known. + var modelBefore = predictionEnginePool.GetModel(); + var predictionEngine = predictionEnginePool.GetPredictionEngine(); + try + { + var prediction = predictionEngine.Predict(example); + var labels = ReadLabels(predictionEngine.OutputSchema); + var modelAfter = predictionEnginePool.GetModel(); + return new ModelBoundPrediction(prediction, labels, ReferenceEquals(modelBefore, modelAfter) ? modelBefore : null); + } + finally + { + predictionEnginePool.ReturnPredictionEngine(predictionEngine); + } + }); } private static string[] ReadLabels(DataViewSchema schema) @@ -95,6 +101,6 @@ private static string[] ReadLabels(DataViewSchema schema) /// The prediction result of type . public TPrediction Predict(TData example) { - return predictionEnginePool.Predict(example); + return LoadedModelGate.Predict(() => predictionEnginePool.Predict(example)); } } diff --git a/src/TailoredApps.Shared.Mediator.ML/README.md b/src/TailoredApps.Shared.Mediator.ML/README.md index 43bac38..8a7d0b2 100644 --- a/src/TailoredApps.Shared.Mediator.ML/README.md +++ b/src/TailoredApps.Shared.Mediator.ML/README.md @@ -86,7 +86,10 @@ The `ImageClassification` section: prediction: the labels are the ones the loaded model names its scores with, and the description (file name, checksum, version) is recorded by `FromModelFile` when it loads the model, from the same bytes. Replacing the file later does not change what the predictions of an already loaded model report; with - `watchForChanges` the pool loads the new file and its predictions carry the new description. + `watchForChanges` the pool loads the new file and its predictions carry the new description. A prediction + never combines the scores of one model with the description of the other, also while the file is being + replaced. A file that cannot be read yet (still being written, or held by its writer) is tried again for + about a minute after the last change; until it loads, the loaded model stays in use. - `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 the model was loaded in another way (the `FromFile` of ML.NET, a URI), when the pool replaced the model while the prediction ran, and with your own `IPredictionEnginePoolAdapter`: in each diff --git a/tests/TailoredApps.Shared.Mediator.ML.Tests/ModelFileLoadingTests.cs b/tests/TailoredApps.Shared.Mediator.ML.Tests/ModelFileLoadingTests.cs index fe4f323..54c1aa2 100644 --- a/tests/TailoredApps.Shared.Mediator.ML.Tests/ModelFileLoadingTests.cs +++ b/tests/TailoredApps.Shared.Mediator.ML.Tests/ModelFileLoadingTests.cs @@ -1,8 +1,10 @@ using System; +using System.Collections.Concurrent; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; +using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.ML; using Microsoft.Extensions.Options; @@ -166,6 +168,109 @@ public void When_Watched_Model_File_Becomes_Unreadable_Predictions_Should_Stay_W Assert.Equal(checksum, prediction.ModelInfo.Checksum); } + [Fact] + public async Task When_Watched_Model_File_Is_Replaced_Under_Load_No_Prediction_Should_Mix_Two_Models() + { + // arrange: the colours are loaded and four threads classify without a pause + SaveModel(modelPath, Colours); + var coloursChecksum = modelHelper.GetChecksum(modelPath); + var (next, _) = PrepareNextModel(Shapes); + var shapesChecksum = modelHelper.GetChecksum(next); + using var provider = BuildProvider(pool => pool.FromModelFile(modelPath, watchForChanges: true)); + var sut = CreateService(provider); + sut.Predict(new byte[] { 1 }, "red-7.png"); + + var mixed = new ConcurrentQueue(); + var shapesSeen = 0; + using var stop = new CancellationTokenSource(); + var workers = Enumerable.Range(0, 4).Select(_ => Task.Run(() => + { + while (!stop.IsCancellationRequested) + { + var prediction = sut.Predict(new byte[] { 1 }, "red-7.png"); + var ofColours = prediction.Scores.Keys.SequenceEqual(Colours); + var expected = ofColours ? coloursChecksum : shapesChecksum; + if (prediction.ModelInfo == null || prediction.ModelInfo.Checksum != expected) + { + mixed.Enqueue($"scores of {(ofColours ? "colours" : "shapes")} with {prediction.ModelInfo?.Checksum ?? "no description"}"); + } + + if (!ofColours) + { + Interlocked.Increment(ref shapesSeen); + } + } + })).ToArray(); + + // act: the shapes take the file's place while the threads run + Thread.Sleep(300); + File.Move(next, modelPath, overwrite: true); + var watch = Stopwatch.StartNew(); + while (Volatile.Read(ref shapesSeen) == 0 && watch.Elapsed < TimeSpan.FromSeconds(30)) + { + Thread.Sleep(50); + } + + Thread.Sleep(500); + stop.Cancel(); + await Task.WhenAll(workers); + + // assert: every prediction named the model that made it, and none of the old engines is left + Assert.True(shapesSeen > 0, "The replaced model file was not loaded."); + Assert.Empty(mixed); + for (var i = 0; i < 200; i++) + { + var prediction = sut.Predict(new byte[] { 1 }, "red-7.png"); + Assert.Equal(Shapes, prediction.Scores.Keys.ToArray()); + Assert.Equal(shapesChecksum, prediction.ModelInfo.Checksum); + } + } + + [Fact] + public void When_Writer_Still_Holds_The_Watched_File_The_New_Model_Should_Be_Loaded_Once_It_Lets_Go() + { + // arrange + SaveModel(modelPath, Colours); + var coloursChecksum = modelHelper.GetChecksum(modelPath); + var (next, shapesVersion) = PrepareNextModel(Shapes); + var shapesChecksum = modelHelper.GetChecksum(next); + var shapesBytes = File.ReadAllBytes(next); + using var provider = BuildProvider(pool => pool.FromModelFile(modelPath, watchForChanges: true)); + var sut = CreateService(provider); + sut.Predict(new byte[] { 1 }, "red-7.png"); + + // act: the file is written in place through a handle that shares nothing and stays open after its last + // write, so every change the system reports finds the file locked + ImagePrediction whileLocked; + using (var writer = new FileStream(modelPath, FileMode.Create, FileAccess.Write, FileShare.None)) + { + writer.Write(shapesBytes); + writer.Flush(flushToDisk: true); + Thread.Sleep(2500); + whileLocked = sut.Predict(new byte[] { 1 }, "red-7.png"); + } + + ImagePrediction afterwards = null; + var watch = Stopwatch.StartNew(); + while (watch.Elapsed < TimeSpan.FromSeconds(40)) + { + afterwards = sut.Predict(new byte[] { 1 }, "square-3.png"); + if (afterwards.ModelInfo != null && afterwards.ModelInfo.Checksum == shapesChecksum) + { + break; + } + + Thread.Sleep(100); + } + + // assert + Assert.Equal(coloursChecksum, whileLocked.ModelInfo.Checksum); + Assert.Equal(Colours, whileLocked.Scores.Keys.ToArray()); + Assert.Equal(shapesChecksum, afterwards.ModelInfo.Checksum); + Assert.Equal(shapesVersion, afterwards.ModelInfo.Version); + Assert.Equal(Shapes, afterwards.Scores.Keys.ToArray()); + } + [Fact] public void When_Model_Is_Loaded_With_FromFile_Prediction_Should_Have_Scores_But_No_Model_Description() { @@ -211,12 +316,19 @@ private ImageClassificationService CreateService(ServiceProvider provider) // Writes the next model beside the model file and moves it into place, the way a deployment replaces a // file: readers see either the old file or the new one, never a half-written one. private string ReplaceModel(string[] labels) + { + var (next, version) = PrepareNextModel(labels); + File.Move(next, modelPath, overwrite: true); + return version; + } + + // The next model, complete, beside the model file. + private (string Path, string Version) PrepareNextModel(string[] labels) { var next = Path.Combine(workFolder, "next.zip"); var version = SaveModel(next, labels, versionOffset: TimeSpan.FromDays(1)); modelHelper.AddLabels(next, labels); - File.Move(next, modelPath, overwrite: true); - return version; + return (next, version); } private string SaveModel(string path, string[] labels, TimeSpan versionOffset = default) From ae42d64d6a1ab04d65614400a80f80fa161d962a Mon Sep 17 00:00:00 2001 From: nieprzecietny Date: Wed, 2 Dec 2026 02:35:23 +0100 Subject: [PATCH 4/4] fix(ml): watch the model file before the first load, release it on dispose - Review of the previous commit: the file was loaded first and watched afterwards, so a file replaced while the first load ran was never reported and the pool kept the outdated model until the next change. Watching now starts before the first load, and the first load holds the lock every reload takes: a change reported meanwhile waits for the load and is then compared with what was loaded. - Dispose waits for a reload under way. With the retries added in the previous commit an attempt could still have the model file open after the service provider was disposed; a test deleting its folder right after that failed once in six runs. Tests: a missing model file and a missing directory are reported as such, with and without watching. The model loading tests were run sixteen times on both frameworks without a failure. The window of the first point cannot be opened from outside the loader, so it has no test of its own. --- docs-en/Libraries/Mediator/ML.md | 2 +- docs/Libraries/Mediator/ML.md | 2 +- .../DescribedFileModelLoader.cs | 43 +++++++++++++++---- src/TailoredApps.Shared.Mediator.ML/README.md | 4 +- .../ModelFileLoadingTests.cs | 25 +++++++++++ 5 files changed, 65 insertions(+), 11 deletions(-) diff --git a/docs-en/Libraries/Mediator/ML.md b/docs-en/Libraries/Mediator/ML.md index e83c2c9..0af0cf8 100644 --- a/docs-en/Libraries/Mediator/ML.md +++ b/docs-en/Libraries/Mediator/ML.md @@ -115,7 +115,7 @@ 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. -- **Both belong to the model that made the prediction.** The labels are the ones the loaded model names its scores with. The description (file name, checksum, version) is recorded by `FromModelFile` when it loads the model, through the same open file, so it cannot be that of another file. Replacing the file later does not change what the predictions of an already loaded model report; with `watchForChanges` the pool loads the new file, and its predictions carry the new description. A prediction never combines the scores of one model with the description of the other, also while the file is being replaced under load. A file that cannot be read yet (still being written, or held by its writer) is tried again for about a minute after the last change; until it loads, the loaded model stays in use. +- **Both belong to the model that made the prediction.** The labels are the ones the loaded model names its scores with. The description (file name, checksum, version) is recorded by `FromModelFile` when it loads the model, through the same open file, so it cannot be that of another file. Replacing the file later does not change what the predictions of an already loaded model report; with `watchForChanges` the pool loads the new file, and its predictions carry the new description. A prediction never combines the scores of one model with the description of the other, also while the file is being replaced under load. A file that cannot be read yet (still being written, or held by its writer) is tried again for about a minute after the last change; until it loads, the loaded model stays in use. Watching starts before the first load, so a file replaced while the application starts is picked up as well, and disposing the service provider leaves the file closed. - **`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 the model was loaded in another way (the `FromFile` of ML.NET, a URI), when the pool replaced the model while the prediction ran, and with your own `IPredictionEnginePoolAdapter`. In each of these cases no file can be proven to be the model that predicted, and a description read from the configured path could belong to another 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. diff --git a/docs/Libraries/Mediator/ML.md b/docs/Libraries/Mediator/ML.md index d0005ef..792b46c 100644 --- a/docs/Libraries/Mediator/ML.md +++ b/docs/Libraries/Mediator/ML.md @@ -115,7 +115,7 @@ 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. -- **Jedno i drugie należy do modelu, który wykonał predykcję.** Etykiety to te, którymi załadowany model nazywa swoje wyniki. Opis (nazwa pliku, checksum, wersja) zapisuje `FromModelFile` w chwili ładowania modelu, przez ten sam otwarty plik, więc nie może dotyczyć innego pliku. Późniejsza podmiana pliku nie zmienia tego, co zwracają predykcje już załadowanego modelu; z `watchForChanges` pula ładuje nowy plik, a jego predykcje mają nowy opis. Predykcja nigdy nie łączy wyników jednego modelu z opisem drugiego, także gdy plik jest podmieniany pod obciążeniem. Plik, którego nie da się jeszcze odczytać (nadal zapisywany albo trzymany przez piszącego), jest próbowany ponownie przez około minutę od ostatniej zmiany; dopóki się nie załaduje, w użyciu zostaje załadowany model. +- **Jedno i drugie należy do modelu, który wykonał predykcję.** Etykiety to te, którymi załadowany model nazywa swoje wyniki. Opis (nazwa pliku, checksum, wersja) zapisuje `FromModelFile` w chwili ładowania modelu, przez ten sam otwarty plik, więc nie może dotyczyć innego pliku. Późniejsza podmiana pliku nie zmienia tego, co zwracają predykcje już załadowanego modelu; z `watchForChanges` pula ładuje nowy plik, a jego predykcje mają nowy opis. Predykcja nigdy nie łączy wyników jednego modelu z opisem drugiego, także gdy plik jest podmieniany pod obciążeniem. Plik, którego nie da się jeszcze odczytać (nadal zapisywany albo trzymany przez piszącego), jest próbowany ponownie przez około minutę od ostatniej zmiany; dopóki się nie załaduje, w użyciu zostaje załadowany model. Obserwowanie zaczyna się przed pierwszym ładowaniem, więc plik podmieniony w trakcie startu aplikacji też zostanie załadowany, a po zwolnieniu dostawcy usług plik jest zamknięty. - **`Scores` ma wartość `null`**, gdy model nie nazywa swoich wyników albo nazwy nie odpowiadają im jeden do jednego. - **`ModelInfo` ma wartość `null`**, gdy model załadowano w inny sposób (`FromFile` z ML.NET, URI), gdy pula podmieniła model w trakcie predykcji oraz przy własnej implementacji `IPredictionEnginePoolAdapter`. W każdym z tych przypadków nie da się wykazać, że dany plik jest modelem, który wykonał predykcję, a opis odczytany ze skonfigurowanej ścieżki mógłby dotyczyć innego 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. diff --git a/src/TailoredApps.Shared.Mediator.ML/Infrastructure/DescribedFileModelLoader.cs b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/DescribedFileModelLoader.cs index 659cdd5..e5e54b1 100644 --- a/src/TailoredApps.Shared.Mediator.ML/Infrastructure/DescribedFileModelLoader.cs +++ b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/DescribedFileModelLoader.cs @@ -50,16 +50,33 @@ public DescribedFileModelLoader(IOptions contextOptions, ILogger Reload(), null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); - watcher = new FileSystemWatcher(Path.GetDirectoryName(filePath)!, Path.GetFileName(filePath)); - watcher.Changed += (_, _) => OnFileChanged(); - watcher.Created += (_, _) => OnFileChanged(); - watcher.Renamed += (_, _) => OnFileChanged(); - watcher.EnableRaisingEvents = true; + // Without the directory there is nothing to watch; the load below reports what is missing. + if (watchForChanges && Directory.Exists(directory)) + { + retryTimer = new Timer(_ => Reload(), null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); + watcher = new FileSystemWatcher(directory, Path.GetFileName(filePath)); + watcher.Changed += (_, _) => OnFileChanged(); + watcher.Created += (_, _) => OnFileChanged(); + watcher.Renamed += (_, _) => OnFileChanged(); + watcher.EnableRaisingEvents = true; + } + + try + { + (model, checksum) = Load(filePath); + } + catch + { + Dispose(); + throw; + } } } @@ -81,6 +98,11 @@ public void Dispose() disposed = true; watcher?.Dispose(); retryTimer?.Dispose(); + + // A reload under way finishes first: when this returns, the loader no longer has the file open. + lock (reloadLock) + { + } } private (ITransformer Model, string Checksum) Load(string path) @@ -114,6 +136,11 @@ private void Reload() lock (reloadLock) { + if (disposed) + { + return; + } + ITransformer loaded; string loadedChecksum; try diff --git a/src/TailoredApps.Shared.Mediator.ML/README.md b/src/TailoredApps.Shared.Mediator.ML/README.md index 8a7d0b2..4c0f3a7 100644 --- a/src/TailoredApps.Shared.Mediator.ML/README.md +++ b/src/TailoredApps.Shared.Mediator.ML/README.md @@ -89,7 +89,9 @@ The `ImageClassification` section: `watchForChanges` the pool loads the new file and its predictions carry the new description. A prediction never combines the scores of one model with the description of the other, also while the file is being replaced. A file that cannot be read yet (still being written, or held by its writer) is tried again for - about a minute after the last change; until it loads, the loaded model stays in use. + about a minute after the last change; until it loads, the loaded model stays in use. Watching starts + before the first load, so a file replaced while the application starts is picked up as well, and disposing + the service provider leaves the file closed. - `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 the model was loaded in another way (the `FromFile` of ML.NET, a URI), when the pool replaced the model while the prediction ran, and with your own `IPredictionEnginePoolAdapter`: in each diff --git a/tests/TailoredApps.Shared.Mediator.ML.Tests/ModelFileLoadingTests.cs b/tests/TailoredApps.Shared.Mediator.ML.Tests/ModelFileLoadingTests.cs index 54c1aa2..47ee168 100644 --- a/tests/TailoredApps.Shared.Mediator.ML.Tests/ModelFileLoadingTests.cs +++ b/tests/TailoredApps.Shared.Mediator.ML.Tests/ModelFileLoadingTests.cs @@ -288,6 +288,31 @@ public void When_Model_Is_Loaded_With_FromFile_Prediction_Should_Have_Scores_But Assert.Null(prediction.ModelInfo); } + [Theory] + [InlineData(true)] + [InlineData(false)] + public void When_Model_File_Does_Not_Exist_The_Pool_Should_Report_The_Missing_File(bool watchForChanges) + { + // arrange + using var provider = BuildProvider(pool => pool.FromModelFile(modelPath, watchForChanges)); + + // act & assert: the file is opened when the pool is first asked for + Assert.Throws(() => CreateService(provider)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void When_Model_Directory_Does_Not_Exist_The_Pool_Should_Report_The_Missing_Directory(bool watchForChanges) + { + // arrange + var missing = Path.Combine(workFolder, "missing", "model.zip"); + using var provider = BuildProvider(pool => pool.FromModelFile(missing, watchForChanges)); + + // act & assert + Assert.Throws(() => CreateService(provider)); + } + [Fact] public void When_FromModelFile_Is_Given_No_Path_Should_Throw_ArgumentException() {