Repository navigation
fix(ml): scores of every label and the model description in a prediction (3.0) - #92
nieprzecietny wants to merge 4 commits into
Conversation
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.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
If the model file is replaced after PredictWithModel returns but before this first description is read, the prediction uses the old model while ModelChecksum and ModelVersion describe the replacement. The adapter's before/after model comparison has already finished, so it cannot detect this change, and caching the description under the old model makes subsequent predictions retain the incorrect identity. The same mismatch occurs if the file changes between loading the pool and its first classification with watchForChanges: false. Capture metadata alongside model loading, or leave ModelInfo null when the file cannot be verified as belonging to the predicting model.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #92 +/- ##
==========================================
+ Coverage 92.95% 93.03% +0.07%
==========================================
Files 140 143 +3
Lines 4869 4207 -662
Branches 538 560 +22
==========================================
- Hits 4526 3914 -612
+ Misses 216 159 -57
- Partials 127 134 +7 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
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.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
With concurrent predictions during a watched reload, this comparison can attribute an old model's prediction to the replacement. The new loader assigns model in DescribedFileModelLoader.Reload before cancelling the reload token, leaving a window where both GetModel() calls return the replacement but GetPredictionEngine() still rents from the old pool. ML.NET's GetModel() implementation reads directly from the loader, whereas the engine pool changes through the reload callback. Thus reference equality does not establish engine identity, and ModelInfo can contain the replacement's checksum/version alongside the old model's scores. Bind identity to the engine's generation, or synchronize publication and prediction so this intermediate state cannot be observed.
When a producer updates the watched file in place and keeps an exclusive writable handle open after its final write, all change notifications can be handled while ReadChecksum or Load still fails with a sharing violation. Returning here permanently loses that update: closing the writer does not guarantee another Changed event, and the inspected .NET Linux watcher implementation handles modification events rather than close-write events. The service can therefore keep predicting with the old model indefinitely despite watchForChanges: true. Schedule a delayed retry for transient failures instead of relying solely on another filesystem notification.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…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.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
If a deployment replaces the model after Load opens the original file but before the watcher is enabled, the pool retains the original model and misses the replacement notification. No retry is scheduled in this case, so even with watchForChanges: true, predictions can use the outdated model indefinitely until another file change occurs. Establish watching before the initial load with appropriate synchronization, or recheck the file after enabling the watcher to reconcile changes made during startup.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…spose - 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.
What
The 3.0 counterpart of #91, which went to
release/2.1and was released as 2.1.1.masterhad the same commented-out code inTailoredApps.Shared.Mediator.ML:ClassifyImagereturned only the winning label,ImagePrediction.ScoresandModelInfowerenull, and a model saved without theLabels.txtentry had no labels.Four commits:
TailoredApps.Shared.MediatR.*->TailoredApps.Shared.Mediator.*,docs/Libraries/MediatR->docs/Libraries/Mediator).Changes
FromModelFile(path, watchForChanges = true)(new, onPredictionEnginePoolBuilder) 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.watchForChangesit loads the file again when it changes. Watching starts before the first load, which holds the lock every reload takes, so a file replaced while the application starts is not missed.Disposewaits for a reload under way, so the file is closed when the service provider has been disposed.ImageClassificationService.PredictfillsScores(label -> score) andModelInfo, and both belong to the model that made the prediction.ModelInfois the description recorded byFromModelFilefor that model. Replacing the file later does not change what the predictions of an already loaded model report.Scoresstaysnullwhen the model does not name its scores or the names do not match them one to one.ModelInfostaysnullwhen the model was loaded in another way (theFromFileof ML.NET, a URI) and with an adapter other than the library's. In each case no file can be proven to be the model that predicted.GetModelInfo()describes the configured file as it is now; for a file withoutLabels.txtits labels come from the loaded model.PredictionEnginePoolAdapter.GetLabelsreturns the engine to the pool and answers with an empty array for a model whose scores are not named, instead of throwing.ModelHelper.GetChecksumkeeps the checksum of a model file until its size or write time changes.GetVersion/GetLabelsopen the file with read-only, shared access.What an application has to change
pool.FromFile(...)->pool.FromModelFile(...). WithFromFilethe model still loads andScoresare filled, butModelInfoisnull. The 3.0 upgrade guide has the entry and a checklist row; the registration examples and the demo useFromModelFile.This differs from 2.1.1, where
ModelInfois read from the configured file when a loaded model is first used. The gap the first review describes (a file replaced between loading and the first classification) is still there in 2.1.1.Checks
mkdocs build --strictpasses for both sites.dotnet build TailoredApps.Shared.slnx -c Release -p:ValidatePublicApi=true: 0 errors, 0 warnings.dotnet test TailoredApps.Shared.slnx -c Release: every project passes onnet10.0andnet11.0;Mediator.ML.Tests117 passed, 1 skipped (the training test that was already skipped); the integration tests of the demo pass withFromModelFile.ModelFileLoadingTestsrun against a realPredictionEnginePool, with small models trained in the test:FromFile;Labels.txt, three images, on Windows and inmcr.microsoft.com/dotnet/aspnet:11.0(model mounted read-only):TailoredApps.Shared.MediatR.ImageClassification1.1.0 and the released 2.1.1 return for these images;ModelInfo.Checksumequals the MD5 of the file, and the version is the one stored in it;Docs
docs/Libraries/Mediator/ML.md,docs-en/Libraries/Mediator/ML.md, the packageREADME.mdand bothMigration/v3.mdpages.