diff --git a/docs-en/Libraries/Mediator/ML.md b/docs-en/Libraries/Mediator/ML.md index 720ea07..0af0cf8 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. @@ -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 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. +- **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,10 +150,11 @@ 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` | +| `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` | @@ -185,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 @@ -207,6 +219,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 +239,10 @@ 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 +- 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 - 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-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 114bd04..792b46c 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. @@ -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. 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. +- **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,10 +150,11 @@ 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` | +| `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` | @@ -185,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 @@ -207,6 +219,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 +239,10 @@ 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 +- Ł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 - 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/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 9396eff..5fefa87 100644 --- a/src/TailoredApps.Shared.Mediator.ML/Infrastructure/ClassificationService.cs +++ b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/ClassificationService.cs @@ -36,13 +36,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 +55,97 @@ 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. 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 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) { 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 = 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 static ModelInfo? DescribeModel(object? model, string[] labels) + { + if (model == null || !LoadedModelDescriptions.TryGet(model, out var description)) + { + return null; + } + + 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; + } + /// /// 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..e5e54b1 --- /dev/null +++ b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/DescribedFileModelLoader.cs @@ -0,0 +1,223 @@ +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 +{ + // 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; + + 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); + var directory = Path.GetDirectoryName(filePath); + + // Watching starts before the first load, and the first load holds the lock every reload takes. A file + // replaced while the first load runs is therefore reported, waits for the load to finish and is then + // compared with what was loaded; started the other way round, that change would never be seen. + lock (reloadLock) + { + // 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; + } + } + } + + /// + 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() + { + 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) + { + // 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); + } + + // 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) + { + if (disposed) + { + return; + } + + ITransformer loaded; + string loadedChecksum; + try + { + // 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; + } + + (loaded, loadedChecksum) = Load(filePath!); + } + catch (Exception exception) + { + 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 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) + { + 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..1ef64c0 --- /dev/null +++ b/src/TailoredApps.Shared.Mediator.ML/Infrastructure/LoadedModelDescriptions.cs @@ -0,0 +1,89 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Threading; + +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); + } +} + +/// +/// 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/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..1ab9556 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,40 @@ public void AddLabels(string modelFilePath, string[] labels) /// A lowercase hexadecimal string representing the MD5 hash of the file. public string GetChecksum(string modelFilePath) { - using var md5 = MD5.Create(); + 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 stream = File.OpenRead(modelFilePath); - var checksum = md5.ComputeHash(stream); - return BitConverter.ToString(checksum).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"; } /// @@ -109,14 +145,8 @@ public string GetVersion(string modelFilePath) { try { - using FileStream fileStream = new FileStream(modelFilePath, FileMode.Open); - 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"; - } + using FileStream fileStream = OpenForReading(modelFilePath); + return ReadVersion(fileStream); } catch (Exception) { @@ -136,7 +166,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 +181,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..bb6b369 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,64 @@ 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() { + return LoadedModelGate.Predict(() => + { + 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); + } + }); + } + + /// + /// 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) + { + return LoadedModelGate.Predict(() => + { + // 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) + { + var score = schema.GetColumnOrNull("Score"); + if (score == null || score.Value.Annotations.Schema.GetColumnOrNull("SlotNames") == null) + { + return Array.Empty(); + } + var labelBuffer = new VBuffer>(); - var predictionEngine = predictionEnginePool.GetPredictionEngine(); - predictionEngine.OutputSchema["Score"].Annotations.GetValue("SlotNames", ref labelBuffer); + score.Value.Annotations.GetValue("SlotNames", ref labelBuffer); return labelBuffer.DenseValues().Select(l => l.ToString()).ToArray(); } @@ -48,6 +101,6 @@ public string[] GetLabels() /// 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 161cda2..4c0f3a7 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 @@ -41,6 +42,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 +80,25 @@ 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 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. 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. 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 + 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. - 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..77dcedc 100644 --- a/tests/TailoredApps.Shared.Mediator.ML.Tests/ImageClassificationServiceTests.cs +++ b/tests/TailoredApps.Shared.Mediator.ML.Tests/ImageClassificationServiceTests.cs @@ -21,7 +21,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 +44,154 @@ 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_A_Model_Description() + { + // 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); + + // 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_Recorded_When_The_Model_Was_Loaded() + { + // 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); + + // 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("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_Was_Not_Described_When_It_Was_Loaded_Predict_Should_Leave_ModelInfo_Null() + { + // 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); + + // act + var prediction = service.Predict(new byte[] { 1, 2, 3 }, "testgreen.png"); + + // 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_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); + LoadedModelDescriptions.Set(loaded.Model, new LoadedModelDescription("model.zip", "first", "20260820.101010")); + var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); + var before = service.Predict(new byte[] { 1, 2, 3 }, "first.png"); + + // 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); + LoadedModelDescriptions.Set(loaded.Model, new LoadedModelDescription("model.zip", "second", "20270101.000000")); + var after = service.Predict(new byte[] { 1, 2, 3 }, "second.png"); + + // assert + 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] + 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); + 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; no model is named + Assert.NotNull(prediction.Scores); + Assert.Equal(0.7f, prediction.Scores["green"]); + Assert.Null(prediction.ModelInfo); + } + + [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); + LoadedModelDescriptions.Set(loaded.Model, new LoadedModelDescription("model.zip", "abc123", "20260820.101010")); + 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 +246,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/ModelFileLoadingTests.cs b/tests/TailoredApps.Shared.Mediator.ML.Tests/ModelFileLoadingTests.cs new file mode 100644 index 0000000..47ee168 --- /dev/null +++ b/tests/TailoredApps.Shared.Mediator.ML.Tests/ModelFileLoadingTests.cs @@ -0,0 +1,383 @@ +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; +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 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() + { + // 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); + } + + [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() + { + // 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, 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); + return (next, 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/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..97cffb9 --- /dev/null +++ b/tests/TailoredApps.Shared.Mediator.ML.Tests/PredictionEnginePoolAdapterTests.cs @@ -0,0 +1,180 @@ +using System; +using System.IO; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.ML; +using Microsoft.ML; +using Microsoft.ML.Data; +using TailoredApps.Shared.Mediator.ImageClassification.Infrastructure; +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); + } + + private ServiceProvider BuildProvider(string modelPath) where TPrediction : class, new() + { + var services = new ServiceCollection(); + services.AddPredictionEnginePool() + .FromFile(modelPath, watchForChanges: false) + .AddAdapter(); + return services.BuildServiceProvider(); + } + + private string SaveClassifier() + { + var mlContext = new MLContext(seed: 1); + var data = mlContext.Data.LoadFromEnumerable(Samples()); + var pipeline = mlContext.Transforms.Conversion + .MapValueToKey("LabelAsKey", nameof(ColorSample.Label), keyOrdinality: Microsoft.ML.Transforms.ValueToKeyMappingEstimator.KeyOrdinality.ByValue) + .Append(mlContext.Transforms.Concatenate("Features", nameof(ColorSample.Red), nameof(ColorSample.Green), nameof(ColorSample.Blue))) + .Append(mlContext.MulticlassClassification.Trainers.SdcaMaximumEntropy("LabelAsKey", "Features")) + .Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel", "PredictedLabel")); + + return Save(mlContext, pipeline.Fit(data), data.Schema, "classifier.zip"); + } + + private string SaveRegression() + { + var mlContext = new MLContext(seed: 1); + var data = mlContext.Data.LoadFromEnumerable(Samples()); + var pipeline = mlContext.Transforms + .Concatenate("Features", nameof(ColorSample.Red), nameof(ColorSample.Green), nameof(ColorSample.Blue)) + .Append(mlContext.Regression.Trainers.Sdca(nameof(ColorSample.Brightness), "Features")); + + return Save(mlContext, pipeline.Fit(data), data.Schema, "regression.zip"); + } + + private string Save(MLContext mlContext, ITransformer model, DataViewSchema schema, string fileName) + { + var path = Path.Combine(workFolder, fileName); + mlContext.Model.Save(model, schema, path); + return path; + } + + private static ColorSample[] Samples() + { + var random = new Random(1); + float High() => 0.8f + (float)random.NextDouble() * 0.2f; + float Low() => (float)random.NextDouble() * 0.2f; + + return Enumerable.Range(0, 40).SelectMany(_ => new[] + { + new ColorSample { Red = High(), Green = Low(), Blue = Low(), Label = "red", Brightness = 0.3f }, + new ColorSample { Red = Low(), Green = High(), Blue = Low(), Label = "green", Brightness = 0.6f }, + new ColorSample { Red = Low(), Green = Low(), Blue = High(), Label = "blue", Brightness = 0.1f }, + }).ToArray(); + } + + public class ColorSample + { + public float Red { get; set; } + + public float Green { get; set; } + + public float Blue { get; set; } + + public string Label { get; set; } + + public float Brightness { get; set; } + } + + public class ColorPrediction + { + public string PredictedLabel { get; set; } + + public float[] Score { get; set; } + } + + public class BrightnessPrediction + { + public float Score { get; set; } + } +}