Skip to content

fix(model): preserve dynamic batches in UniNet exports - #3978

Draft
rajeshgangireddy wants to merge 4 commits into
open-edge-platform:mainfrom
rajeshgangireddy:fix/model/uninet-dynamic-batch
Draft

rajeshgangireddy wants to merge 4 commits into
open-edge-platform:mainfrom
rajeshgangireddy:fix/model/uninet-dynamic-batch

Conversation

@rajeshgangireddy

@rajeshgangireddy rajeshgangireddy commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

📝 Description

UniNet exports fixed the input batch size at two, so OpenVINO rejected single images. Splitting the student outputs with chunk(2) specialized the batch dimension; slicing at the input batch size keeps it dynamic. An explicit batch bound also lets the CUDA exporter prove the batch-norm constraint for the stacked inputs. Re-export existing models to pick up the fix.

Dynamic exports exposed an overflow in OpenVINO's Intel GPU f16 ReduceL2 kernel when squaring large UniNet features. Power-of-two scaling before cosine similarity keeps the inputs to the reduction small without changing the model's cosine similarity on the tested Torch paths.

This PR is part of the series of fixes from the full OpenVINO compatibility check tracked in #3941.

Validation

Torch accuracy. Compared unchanged main (bfda30ee) with the patch (6f2a8dfb) on an RTX 3090. All 15 pairs (30 fits) used four epochs, 256×256 evaluation inputs, and train batch size 8, with matched splits and initial weights. Categories: toothbrush, bottle, transistor, carpet, leather. Seeds: 42, 123, 3407. All fitted states and all four metrics matched exactly.

Metric Mean before Mean after Max absolute paired delta
Image F1 0.77369 0.77369 0
Image AUROC 0.56902 0.56902 0
Pixel F1 0.18138 0.18138 0
Pixel AUROC 0.75823 0.75823 0

OpenVINO. Independently fitted one MVTec AD toothbrush checkpoint on each of CUDA and XPU for one epoch. The original OpenVINO IRs rejected batch 1. The new IRs accepted batches 1, 2, and 3 on Intel GPU without CPU fallback, using the same fitted checkpoints and 20 held-out images. Worst case across both training origins and all three batch sizes (OpenVINO 2026.4.1):

Export Score MAE vs. Torch Map MAE vs. Torch Label agreement
FP32 and FP16 0.00482 0.00100 100%
Weight-only INT8 0.01549 0.00767 100%
FP32, INFERENCE_PRECISION_HINT=f32 5.0e-7 4.2e-7 100%

Cold TorchInferencer predictions were bit-identical before and after the patch on each of CPU, CUDA, and XPU. Under default OpenVINO execution, batch-versus-single map MAE stayed below 1e-4; the largest absolute map difference versus Torch was 0.115 for weight-only INT8. The batch bound limits UniNet to 32,767 input images per batch, including in eager mode. PTQ and ACQ are out of scope.

  • python -m pytest -q -p no:cacheprovider tests/unit/models/image/uninet tests/unit/deploy --disable-warnings --tb=short — 50 passed, 2 XPU cases skipped in the CUDA environment. The dynamic-batch test fails on unchanged main (fixed batch of 2). The large-feature GPU case fails if only the scaling is removed from the dynamic export.
  • python -m pytest -q -p no:cacheprovider tests/unit/models/image/uninet/test_lightning_model.py tests/unit/deploy --disable-warnings --tb=short — 45 passed, 2 CUDA cases skipped in the XPU environment.
  • python -m pytest tests/integration/model/test_models.py -k uni_net -q --disable-warnings -p no:cacheprovider --junitxml=../artifacts/uninet-batch-integration-xpu.xml — all 8 UniNet integration cases passed in the XPU environment.
  • bash runner/run_batch_accuracy.sh UniNet uninet-batch "$MVTEC_ROOT" — all 30 fits and the paired comparison passed (local validation harness; MVTEC_ROOT is the MVTec AD dataset root).
  • TREES=uninet-batch bash runner/run_batch_deployment.sh UniNet uninet-batch — all 10 rerun stages passed; same-checkpoint comparison against bfda30ee passed the FP32, FP16, and weight-only INT8 gates at batches 1–3.
  • prek run --files CHANGELOG.md docs/source/markdown/guides/reference/deploy/index.md src/anomalib/models/image/uninet/torch_model.py tests/unit/models/image/uninet/test_lightning_model.py — passed.
  • prek run --all-files — same notebook and nbQA failures as unchanged main, plus nbQA's existing noqa-comment notice on the two new # noqa comments.
  • git diff --check — passed. The full pytest tests/ suite was not run locally.

✨ Changes

Select what type of change your PR is:

  • 🚀 New feature (non-breaking change which adds functionality)
  • 🐞 Bug fix (non-breaking change which fixes an issue)
  • 🔄 Refactor (non-breaking change which refactors the code base)
  • ⚡ Performance improvements
  • 🎨 Style changes (code style/formatting)
  • 🧪 Tests (adding/modifying tests)
  • 📚 Documentation update
  • 📦 Build system changes
  • 🚧 CI/CD configuration
  • 🔧 Chore (general maintenance)
  • 🔒 Security update
  • 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)

✅ Checklist

Before you submit your pull request, please make sure you have completed the following steps:

  • 📚 I have made the necessary updates to the documentation (if applicable).
  • 🧪 I have written tests that support my changes and prove that my fix is effective or my feature works (if applicable).
  • 🏷️ My PR title follows conventional commit format.

For more information about code review checklists, see the Code Review Checklist.

Signed-off-by: rajeshgangireddy <rajesh.gangireddy@intel.com>
CUDA batch norm adds a 2 * batch <= 65535 guard on the stacked teacher features, which torch.export cannot report for a dynamic batch. Bound the batch with torch._check so the guard is statically true.

Signed-off-by: rajeshgangireddy <rajesh.gangireddy@intel.com>
OpenVINO's dynamic-shape Intel GPU ReduceL2 kernel squares f16 values and overflows when UniNet features exceed 256. Scale each feature vector by an exact power of two before cosine similarity, which leaves eager results unchanged.

Signed-off-by: rajeshgangireddy <rajesh.gangireddy@intel.com>
Copilot AI balanced review requested due to automatic review settings December 1, 2026 10:06

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The float16 scaling calculation can overflow for finite features at 65,504, zeroing channel vectors and causing incorrect cosine similarities or NaNs during half-precision inference.

1 open issue
What changed in this PR

This PR addresses UniNet export issues from #3941, enabling single-image and dynamic-batch OpenVINO inference while reducing overflow in Intel GPU cosine-similarity calculations.

Changes:

  • Replace batch splitting with input-sized slices and add an explicit batch bound.
  • Scale feature vectors by powers of two before computing cosine similarity.
  • Add export and numerical regression tests, plus re-export guidance and a changelog entry.
File Description
tests/​unit/​models/​image/​uninet/​test_lightning_model.py Add scaling, dynamic-batch export, and Intel GPU regression tests.
src/​anomalib/​models/​image/​uninet/​torch_model.py Preserve dynamic batches and scale features before cosine similarity.
docs/​source/​markdown/​guides/​reference/​deploy/​index.md Advise re-exporting affected UniNet models.
CHANGELOG.md Record the UniNet dynamic-batch export fix.

Review effort: Balanced

Comment on lines +46 to +47
peak = features.abs().amax(dim=1, keepdim=True).clamp_min(1.0)
return features / torch.exp2(torch.floor(torch.log2(peak)))
Signed-off-by: rajeshgangireddy <rajesh.gangireddy@intel.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants