Publish selected FP32 HEMIT benchmark weights and inference package
Browse filesFiles changed (15)
- .gitattributes-34
- LICENSEAdded+32
- README.mdAdded+117
- THIRD_PARTY_NOTICES.mdAdded+15
- UPSTREAM_NOTICE.mdAdded+35
- architecture.pyAdded+60
- config.jsonAdded+53
- evaluation.jsonAdded+145
- inference.pyAdded+59
- model.safetensorsAdded+3
- predict.pyAdded+50
- release_evidence.jsonAdded+54
- requirements.txtAdded+5
- training_summary.jsonAdded+65
- weight_export.jsonAdded+16
123456789101112131415161718192021222324126272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text1234567891011121314151617181920212223242526272829303132BSD 3-Clause License
Copyright (c) 2025, Tushar KatariaAll rights reserved.
This repository is adapted from LIIF (https://github.com/yinboc/liif),Copyright (c) 2020, Yinbo Chen, also released under the BSD 3-Clause License.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLEFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117---license: bsd-3-clauselibrary_name: pytorchpipeline_tag: image-to-imagetags:- virtual-staining- histopathology- hemit- image-to-image- benchmark- safetensors---
# ImplicitStainer CNN — HEMIT benchmark adaptation
Selected prediction weights trained by the Virtual Staining Benchmark on HEMIT.Input is RGB H&E; output is three independent numerical fluorescence intensitychannels in **DAPI, CD3, panCK** order. This release contains the selected FP32inference weights and a self-contained loader. No pretrained foundation networkis needed for inference.
Released EDSR/CNN variant: width 64, 16 residual blocks and learned coordinate MLPs. This is the CNN variant, not the Swin/hybrid variant.
This is a disclosed benchmark adaptation of the published architecture, not anauthor checkpoint or a reproduction of the paper's training setting or scores.See [the benchmark](https://thomasdekerf.github.io/virtual-staining-benchmark/), `training_summary.json`, and `release_evidence.json`.
## Use
Install the download client with `python -m pip install huggingface_hub`,then download the release files:
```pythonfrom huggingface_hub import snapshot_download
snapshot_download( repo_id="thomasdekerf/implicitstainer-hemit", local_dir="implicitstainer-hemit",)```
Enter the downloaded directory with `cd implicitstainer-hemit`, then run:
```bashpython -m pip install -r requirements.txtpython predict.py --input he_image.png --output prediction.npy --preview preview.png```
For GPU inference append `--device cuda`. The default uses CPU. The input must bestored uint8 RGB and at least 256×256 native pixels. The loader takes a fixedcenter 256 crop, divides by 255, and never resizes or fits stain normalization.Physical pixel size is not asserted. Predictions outside the released datasetor native sampling require separate validation.
`prediction.npy` is an HWC float32 array in DAPI/CD3/panCK order, clamped to [0, 1]exactly as in benchmark evaluation. `prediction.raw.npy` preserves the unclampedmodel forward output. `prediction.json` records channel order and crop coordinates.The optional preview is three grayscale intensity panels using a fixed [0, 1]display range; the numerical stack is not an RGB tissue image.
Python loading after downloading the files:
```pythonfrom inference import load_model, load_rgb_center_crop, predict_tensor
model = load_model(device="cpu")rgb, crop = load_rgb_center_crop("he_image.png")raw_nchw = predict_tensor(model, rgb)benchmark_nchw = raw_nchw.clamp(0, 1)```
## Training and evaluation
- Seed 42; train 3,717, validation 630 and test 945 author fields.- Splits are disjoint by released author field identity. Patient/whole-slide mappings are unavailable, so independent patient-level disjointness is not certified.- Native 256 random training crops; fixed center 256 held-out crops; no resizing.- Training reached 96,000 optimizer updates, protecting the 80,000-update benchmark reference horizon and then observing 8 fresh full-validation checks without improvement.- Selected checkpoint: update 38,000; minimum full-validation LPIPS. TEST did not select weights.- Four-GPU native update/resume gate and native adequacy were verified.
Full test split (945 fields), from the original selected-checkpoint evaluation:
| Metric | Value ||---|---:|| Numerical mIF PSNR | 27.523707 || Numerical mIF 11×11 box SSIM | 0.699224 || LPIPS on normalized intensity stack | 0.209927 || Numerical mIF MAE | 0.024497 |
Full validation, test and per-channel values are in `evaluation.json`. LPIPS isan operational image-feature distance on the normalized three-channel stack,not a validated biological or clinical stain score. Intensities use the releaseduint8 / 255 codec, without physical fluorescence calibration.
## Channel convention and provenance
Output channels are already in the benchmark's canonical DAPI/CD3/panCK order;do not permute the model output. Ingestion converted the original raw TIFFpanCK/CD3/DAPI storage order using indices [2, 1, 0]. This numerical mapping isdocumented in retained decoder/probe, named channel statistics and ingestion QC;it is separate from the display colour or marker listing in a dataset README.See `release_evidence.json` for source hashes and references.
## Scope and license
For research image translation. This model has no established diagnostic orclinical grading use. Dataset source, author attribution and terms appear in`THIRD_PARTY_NOTICES.md`; code terms are retained in `LICENSE` and`UPSTREAM_NOTICE.md`. No source tissue images are included in this repository.
HEMIT: Chang Bian, Beth Phillips, Tim Cootes and Martin Fergie (2024), Mendeley Data,version 1, [DOI 10.17632/3gx53zm49d.1](https://data.mendeley.com/datasets/3gx53zm49d/1),CC BY 4.0. Original architecture: IMPLICITSTAINER: Resolution Agnostic Data-Efficient Virtual Staining Using Neural Implicit Functions,https://arxiv.org/abs/2505.09831.123456789101112131415# Attribution and scope
Architecture source: https://github.com/tushaarkataria/ImplicitStainer/tree/8cbebebd47cf78e372aa844c691a34986f726316The exact benchmark constructor is retained in architecture.py with sourceSHA25623615aa92f7e5322755f7bf9fd161f73c28fd4582b4fcd2bceead3e5936f5090. See LICENSE and UPSTREAM_NOTICE.md for retained terms.
HEMIT dataset: Chang Bian, Beth Phillips, Tim Cootes and Martin Fergie,HEMIT: H&E to Multiplex-immunohistochemistry Image Translation with Dual-BranchPix2pix Generator, Mendeley Data, version1,2024. DOI:10.17632/3gx53zm49d.1.Dataset source: https://data.mendeley.com/datasets/3gx53zm49d/1, licensed CC BY4.0.No source tissue images or separate pretrained foundation checkpoints are included.
This checkpoint was trained for the Virtual Staining Benchmark. It is not anauthor-released pretrained checkpoint or a claim to reproduce paper-reported scores.Training feature networks are not inference dependencies and are not redistributed.1234567891011121314151617181920212223242526272829303132333435# HEMIT release note
This checkpoint uses three RGB H&E inputs and three numerical fluorescenceoutputs in DAPI/CD3/panCK order, as specified by config.json. The historicalarchitecture notice retained verbatim below describes the earlier ORION use ofthe same configurable constructor; its 17-input-channel description does notdescribe this HEMIT checkpoint. The source license file named in that notice isprovided here as LICENSE. Perceptual feature networks used during training orevaluation are not inference dependencies and are not included.
---
# ImplicitStainer CNN adaptation
Architecture source: https://github.com/tushaarkataria/ImplicitStainer,`models/implicitstainer.py`, `models/edsr.py`, `models/mlp.py`,`configs/train-he2ihc/train_he_to_ihc_liif.yaml`.Copyright 2025 Tushar Kataria; adapted upstream from LIIF (Yinbo Chen, 2020).BSD-3-Clause license retained in IMPLICITSTAINER_LICENSE.txt.
The implemented recipe is the released YAML's CNN configuration: EDSR baseline,16 residual blocks, width64, learned 2-to-64 coordinate MLP and concatenated128-to-RGB MLP, each four 256-wide PReLU hidden layers. The released query functionuses nearest sampling and absolute coordinates, not four-way LIIF ensembling.Input changes to17 channels. Output stays RGB. Coordinate queries are chunkedwithout changing the dense spatial objective. Disabled RGB MeanShift modulesand unused flags are omitted. No pretrained encoder is used.
Reference objective is signed SmoothL1 with author MONAI Generative perceptualterms (AlexNet, VGG, ResNet50), each weight1. These require the optional`monai-generative` runtime and pretrained feature weights. The explicit ORIONvariant uses the common multiscale/LPIPS recipe instead. Optimizer/schedule inthe common ORION trainer differ from the author Adam/epoch milestones.The Swin/hybrid encoder is not included in this CNN recipe and must not beclaimed as tested. Source commit is in the priority audit.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960"""CNN variant of the released ImplicitStainer coordinate regressor.
See IMPLICITSTAINER_NOTICE.md. The released query_rgb uses nearest featuresampling plus learned absolute coordinates; it does not execute LIIF's four-waylocal ensemble despite retaining that constructor flag."""import torchfrom torch import nnfrom torch.nn import functional as F
class ResidualBlock(nn.Module): def __init__(self, width, scale=1.): super().__init__() self.body = nn.Sequential(nn.Conv2d(width,width,3,padding=1),nn.ReLU(), nn.Conv2d(width,width,3,padding=1)) self.scale = scale
def forward(self,x): return x+self.scale*self.body(x)
class CoordinateMLP(nn.Module): def __init__(self, inputs, outputs, hidden): super().__init__() layers = [] for width in hidden: layers.extend([nn.Linear(inputs,width),nn.PReLU()]) inputs = width layers.append(nn.Linear(inputs,outputs)) self.layers = nn.Sequential(*layers)
def forward(self,x): return self.layers(x)
class ImplicitStainer(nn.Module): def __init__(self,in_channels=17,width=64,blocks=16,hidden=(256,256,256,256),query_chunk=4096): super().__init__() self.head = nn.Conv2d(in_channels,width,3,padding=1) self.body = nn.Sequential(*[ResidualBlock(width) for _ in range(blocks)],nn.Conv2d(width,width,3,padding=1)) self.imnet = CoordinateMLP(width*2,3,hidden) self.imnet1 = CoordinateMLP(2,width,hidden) self.query_chunk = query_chunk
def forward(self, x): b,_,h,w = x.shape head = self.head(x*2-1) feature = self.body(head)+head ys = (torch.arange(h,device=x.device,dtype=x.dtype)+.5)*2/h-1 xs = (torch.arange(w,device=x.device,dtype=x.dtype)+.5)*2/w-1 coordinates = torch.stack(torch.meshgrid(ys,xs,indexing='ij'),dim=-1).reshape(-1,2) chunks = [] for coords in coordinates.split(self.query_chunk): coords = coords[None].expand(b,-1,-1) values = F.grid_sample(feature,coords.flip(-1).unsqueeze(1),mode='nearest',align_corners=False) values = values[:,:,0,:].transpose(1,2) position = self.imnet1(coords) chunks.append(self.imnet(torch.cat((values,position),dim=-1))) return (torch.cat(chunks,dim=1).transpose(1,2).reshape(b,3,h,w)+1)/21234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253{ "format_version": 1, "model_type": "implicitstainer", "architecture": { "class_name": "ImplicitStainer", "kwargs": { "in_channels": 3, "width": 64, "blocks": 16, "hidden": [ 256, 256, 256, 256 ], "query_chunk": 4096 } }, "input": { "space": "RGB H&E", "dtype": "float32", "range": [ 0, 1 ], "normalization": "stored uint8 /255", "crop": "native center256", "resize": false }, "output": { "space": "numerical_mif", "channels": [ "DAPI", "CD3", "panCK" ], "dtype": "float32", "normalization": "released uint8 /255", "raw_forward": "unclamped", "benchmark_evaluation": "clamp to[0,1]", "physical_calibration": false, "original_target_storage_order": [ "panCK", "CD3", "DAPI" ], "ingestion_reindex": [ 2, 1, 0 ] }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145{ "dataset": "HEMIT", "scope": "frozen author field splits; native center256; tile means", "selected_checkpoint_sha256": "8589a774df266f235e5fa837fb5ef18533d775044f5f04ba870be5f8516e949d", "split_results": { "val": { "n": 630, "metrics": { "mif_psnr": 25.41898671710302, "mif_ssim": 0.6362937193068247, "mif_lpips": 0.35597921780177527, "mif_mae": 0.03208430097216652, "mif_DAPI_mae": 0.0262509385981257, "mif_DAPI_psnr": 29.47381041996063, "mif_DAPI_ssim": 0.6499341578710647, "mif_DAPI_pcc": 0.5235921229075783, "mif_CD3_mae": 0.03860913940838405, "mif_CD3_psnr": 25.817227729918464, "mif_CD3_ssim": 0.6416813680103847, "mif_CD3_pcc": 0.09712516940726766, "mif_panCK_mae": 0.03139282313604203, "mif_panCK_psnr": 29.881238156273252, "mif_panCK_ssim": 0.6172655673254104, "mif_panCK_pcc": 0.20110357131084872 }, "metric_coverage": { "mif_psnr": 630, "mif_ssim": 630, "mif_lpips": 630, "mif_mae": 630, "mif_DAPI_mae": 630, "mif_DAPI_psnr": 630, "mif_DAPI_ssim": 630, "mif_DAPI_pcc": 629, "mif_CD3_mae": 630, "mif_CD3_psnr": 630, "mif_CD3_ssim": 630, "mif_CD3_pcc": 597, "mif_panCK_mae": 630, "mif_panCK_psnr": 630, "mif_panCK_ssim": 630, "mif_panCK_pcc": 630 }, "fluorescence_channels": { "DAPI": { "mae": 0.0262509385981257, "psnr": 29.47381041996063, "ssim": 0.6499341578710647, "pcc_mean_defined_tiles": 0.5235921229075783, "pcc_defined_tiles": 629, "pcc_total_tiles": 630, "pcc_undefined_tiles": 1 }, "CD3": { "mae": 0.03860913940838405, "psnr": 25.817227729918464, "ssim": 0.6416813680103847, "pcc_mean_defined_tiles": 0.09712516940726766, "pcc_defined_tiles": 597, "pcc_total_tiles": 630, "pcc_undefined_tiles": 33 }, "panCK": { "mae": 0.03139282313604203, "psnr": 29.881238156273252, "ssim": 0.6172655673254104, "pcc_mean_defined_tiles": 0.20110357131084872, "pcc_defined_tiles": 630, "pcc_total_tiles": 630, "pcc_undefined_tiles": 0 } } }, "test": { "n": 945, "metrics": { "mif_psnr": 27.523707402950873, "mif_ssim": 0.6992237416524736, "mif_lpips": 0.20992736671336745, "mif_mae": 0.024496910677700448, "mif_DAPI_mae": 0.023624825887579137, "mif_DAPI_psnr": 31.084156484452507, "mif_DAPI_ssim": 0.6181023799553119, "mif_DAPI_pcc": 0.9210784793420735, "mif_CD3_mae": 0.016071989807108094, "mif_CD3_psnr": 30.378172802798964, "mif_CD3_ssim": 0.8402388254801433, "mif_CD3_pcc": 0.43251536677158847, "mif_panCK_mae": 0.033793917109095864, "mif_panCK_psnr": 29.504415279973752, "mif_panCK_ssim": 0.6393299559436778, "mif_panCK_pcc": 0.4798366421181002 }, "metric_coverage": { "mif_psnr": 945, "mif_ssim": 945, "mif_lpips": 945, "mif_mae": 945, "mif_DAPI_mae": 945, "mif_DAPI_psnr": 945, "mif_DAPI_ssim": 945, "mif_DAPI_pcc": 893, "mif_CD3_mae": 945, "mif_CD3_psnr": 945, "mif_CD3_ssim": 945, "mif_CD3_pcc": 862, "mif_panCK_mae": 945, "mif_panCK_psnr": 945, "mif_panCK_ssim": 945, "mif_panCK_pcc": 910 }, "fluorescence_channels": { "DAPI": { "mae": 0.023624825887579137, "psnr": 31.084156484452507, "ssim": 0.6181023799553119, "pcc_mean_defined_tiles": 0.9210784793420735, "pcc_defined_tiles": 893, "pcc_total_tiles": 945, "pcc_undefined_tiles": 52 }, "CD3": { "mae": 0.016071989807108094, "psnr": 30.378172802798964, "ssim": 0.8402388254801433, "pcc_mean_defined_tiles": 0.43251536677158847, "pcc_defined_tiles": 862, "pcc_total_tiles": 945, "pcc_undefined_tiles": 83 }, "panCK": { "mae": 0.033793917109095864, "psnr": 29.504415279973752, "ssim": 0.6393299559436778, "pcc_mean_defined_tiles": 0.4798366421181002, "pcc_defined_tiles": 910, "pcc_total_tiles": 945, "pcc_undefined_tiles": 35 } } } }, "clinical_score_evaluation": false, "metric_protocol": "FP32 numerical mIF;11x11 box SSIM; LPIPS on the normalized intensity stack is an operational image-feature distance, not a biological stain score"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859"""Self-contained inference for the selected HEMIT benchmark checkpoint."""from __future__ import annotations
import importlib.utilimport jsonfrom pathlib import Path
import numpy as npfrom PIL import Imageimport torchfrom safetensors.torch import load_file
def load_model(directory=None, device="cpu"): directory = Path(directory) if directory is not None else Path(__file__).resolve().parent config = json.loads((directory / "config.json").read_text()) spec = importlib.util.spec_from_file_location("_hemit_release_architecture", directory / "architecture.py") architecture = importlib.util.module_from_spec(spec) spec.loader.exec_module(architecture) model = getattr(architecture, config["architecture"]["class_name"])(**config["architecture"]["kwargs"]) tensors = load_file(str(directory / "model.safetensors"), device="cpu") model.load_state_dict(tensors, strict=True) if any(not torch.isfinite(value).all() for value in model.state_dict().values()): raise ValueError("The released state contains nonfinite tensors") return model.to(device=device, dtype=torch.float32).eval()
def load_rgb_center_crop(path): """Match the benchmark: stored RGB uint8 /255, native center256, no resize.""" with Image.open(path) as image: if image.mode != "RGB": raise ValueError("Input must be stored 8-bit RGB H&E, without implicit colour conversion") array = np.asarray(image) if array.dtype != np.uint8 or array.ndim != 3 or array.shape[-1] != 3: raise ValueError("Input must be an HWC RGB uint8 image") height, width = array.shape[:2] if min(height, width) < 256: raise ValueError("Input must be at least256x256 native pixels; this loader never resizes") top, left = (height - 256) // 2, (width - 256) // 2 crop = array[top:top + 256, left:left + 256].copy() tensor = torch.from_numpy(crop).permute(2, 0, 1).float().div(255).unsqueeze(0) return tensor, {"top": top, "left": left, "height": 256, "width": 256}
@torch.inference_mode()def predict_tensor(model, rgb): """Return the unmodified FP32 forward result in DAPI/CD3/panCK order.""" if rgb.ndim != 4 or rgb.shape[1:] != (3, 256, 256): raise ValueError("Expected NCHW RGB at the benchmark's256x256 native crop") if not torch.is_floating_point(rgb) or not torch.isfinite(rgb).all() or rgb.min() < 0 or rgb.max() > 1: raise ValueError("Input must contain finite RGB values in[0,1]") device = next(model.parameters()).device if device.type == "cuda": torch.backends.cuda.matmul.allow_tf32 = False torch.backends.cudnn.allow_tf32 = False prediction = model(rgb.to(device=device, dtype=torch.float32)).float() if prediction.shape != rgb.shape or not torch.isfinite(prediction).all(): raise ValueError("Invalid output shape or nonfinite model output") return prediction123version https://git-lfs.github.com/spec/v1oid sha256:b8dc1bfa201c3ba8a4f2be15a08a9376ef97bbcc7cecf1aef3b9519e06792155size 66732841234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950"""Predict native center256 HEMIT numerical fluorescence channels from H&E."""from __future__ import annotations
import argparseimport jsonfrom pathlib import Path
import numpy as npfrom PIL import Image, ImageDraw
from inference import load_model, load_rgb_center_crop, predict_tensor
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--input", type=Path, required=True, help="Stored uint8 RGB H&E image, at least256x256") parser.add_argument("--output", type=Path, required=True, help="Output.npy: HWC float32 DAPI/CD3/panCK in[0,1]") parser.add_argument("--preview", type=Path, help="Optional three-panel grayscale PNG, no per-image intensity fit") parser.add_argument("--device", default="cpu") args = parser.parse_args() if args.output.suffix.lower() != ".npy": parser.error("--output must end in.npy") model = load_model(device=args.device) rgb, crop = load_rgb_center_crop(args.input) raw = predict_tensor(model, rgb)[0].permute(1, 2, 0).cpu().numpy() prediction = np.clip(raw, 0, 1).astype(np.float32, copy=False) args.output.parent.mkdir(parents=True, exist_ok=True) np.save(args.output, prediction, allow_pickle=False) raw_path = args.output.with_name(args.output.stem + ".raw.npy") np.save(raw_path, raw, allow_pickle=False) metadata = {"axes": "HWC", "channels": ["DAPI", "CD3", "panCK"], "dtype": "float32", "normalization": "released uint8/255 numerical intensity; no physical calibration", "output": "forward result clamped to[0,1], as used in benchmark metrics", "raw_output": raw_path.name, "raw_output_semantics": "unclamped forward result", "source_crop": crop, "resized": False, "clinical_score": False} args.output.with_suffix(".json").write_text(json.dumps(metadata, indent=2) + "\n") if args.preview: canvas = Image.new("RGB", (256 * 3, 280), "white") draw = ImageDraw.Draw(canvas) for index, name in enumerate(metadata["channels"]): plane = Image.fromarray(np.round(prediction[:, :, index] * 255).astype(np.uint8)) canvas.paste(plane.convert("RGB"), (256 * index, 24)) draw.text((256 * index + 8, 6), name + " [0,1]", fill="black") args.preview.parent.mkdir(parents=True, exist_ok=True) canvas.save(args.preview) print(json.dumps({"output": str(args.output), "raw_output": str(raw_path), "channels": metadata["channels"]}))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354{ "schema": "hemit_small_inference_release_evidence_v1", "benchmark_run_id": "hemit_dataset__implicitstainer_seed42", "benchmark_url": "https://thomasdekerf.github.io/virtual-staining-benchmark/#/run/hemit_dataset__implicitstainer_seed42", "original_selected_checkpoint_sha256": "8589a774df266f235e5fa837fb5ef18533d775044f5f04ba870be5f8516e949d", "selected_global_step": 38000, "terminal_global_step": 96000, "training_source_sha256": "f88be5f1c9b90493313f08bc7606c3b9cda65383710468bd0e0df67d3081c14e", "original_config_sha256": "1d8e8a27a55ddd19ec28630a2d2593230bb2a133771d223e742218c61137a286", "architecture_source_sha256": "23615aa92f7e5322755f7bf9fd161f73c28fd4582b4fcd2bceead3e5936f5090", "original_final_evaluation_sha256": "5d563e6106a41547d1015e8bc940daab2b4acf840cc8483c117b709398930041", "upstream_repository": "https://github.com/tushaarkataria/ImplicitStainer", "upstream_commit": "8cbebebd47cf78e372aa844c691a34986f726316", "dataset": { "name": "HEMIT", "doi": "10.17632/3gx53zm49d.1", "url": "https://data.mendeley.com/datasets/3gx53zm49d/1", "license": "CC-BY-4.0", "authors": [ "Chang Bian", "Beth Phillips", "Tim Cootes", "Martin Fergie" ] }, "channel_mapping": { "canonical_order": [ "DAPI", "CD3", "panCK" ], "original_stored_order": [ "panCK", "CD3", "DAPI" ], "ingestion_reindex": [ 2, 1, 0 ], "retained_mapping_evidence_sha256": "e505159699e3728992b3b9f8d251fbcdbf1b1e3a6bc5743c71c04d44b07d20c8", "independent_named_channel_statistics": "https://github.com/Sanofi-Public/MIPHEI-ViT/blob/main/channel_stats_hemit.json" }, "serialized_weights": "model.safetensors", "weight_selection": "selected online inference state, not optimizer/scheduler/training feature encoders", "status": "weights exported; consult weight_export.json for actual tensor export verification", "weight_export_receipt": "weight_export.json", "split_identity": { "disjointness": "released author field identity verified", "patient_whole_slide_mapping_available": false, "independent_patient_disjointness_certified": false }}12345torch>=2.4safetensors>=0.4.3numpy>=1.26Pillow>=10huggingface_hub>=0.241234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465{ "seed": 42, "training_tiles": 3717, "validation_tiles": 630, "test_tiles": 945, "selected_global_step": 38000, "terminal_global_step": 96000, "minimum_benchmark_reference_updates": 80000, "fresh_full_validation_patience": 8, "training_complete": true, "native_adequacy_verified": true, "gate_passed": true, "selection": "minimum full-validation LPIPS; TEST never selects weights", "train": { "max_steps": 80000, "batch_size": 8, "lr": 0.0001, "amp": "bf16", "warmup_steps": 500, "l1_priming_steps": 0, "validate_every": 2000, "checkpoint_every": 1000, "log_every": 50, "grad_clip": 1.0, "validate_initial": false, "reference_steps_per_epoch": 116, "until_plateau": true, "min_lr_ratio": 0.05, "save_generator_snapshots": false }, "loss": { "l1": 0.0, "signed_smooth_l1": 1.0, "implicit_perceptual": 1.0 }, "validation": { "lpips": true, "selection_metric": "lpips", "save_best_psnr": false, "early_stopping": { "enabled": true, "patience": 8, "min_delta": 0.0001, "warmup_checks": 5, "warmup_steps": 80001, "warmup_epochs": 5 }, "fp32": true, "unpadded": true, "selection_mode": "min", "aggregation": "tile_mean", "save_best_unconstrained": false, "selection": "minimum_full_validation_lpips_test_never_selects" }, "manifest_sha256": { "train": "da6dc46ca3febfcd05b21a3372cc4c31c104d394eee9a92330fffe64e184981e", "val": "3119aff2b7276f759aae9bfff643ba947938d5d766c94fa19543f80727d73eb8", "test": "d7fbe1fffaedaeecd68233fb3a0e2d9e96a6e92a94beafbe6878836244d97ba4" }, "split_identity": { "disjointness": "released author field identity verified", "patient_whole_slide_mapping_available": false, "independent_patient_disjointness_certified": false }}12345678910111213141516{ "model": "implicitstainer", "selected_checkpoint_sha256": "8589a774df266f235e5fa837fb5ef18533d775044f5f04ba870be5f8516e949d", "selected_step": 38000, "extraction": "training_model if present, otherwise model; exact native inference selection", "tensor_count": 96, "tensor_bytes": 6664748, "safetensors_bytes": 6673284, "safetensors_sha256": "b8dc1bfa201c3ba8a4f2be15a08a9376ef97bbcc7cecf1aef3b9519e06792155", "every_tensor_bitwise_identical": true, "all_tensors_finite": true, "precision": "float32", "optimizer_and_resume_state_included": false, "selected_weights": "online; serialized config has no enabled EMA", "export_executed_on": "local Mac CPU; no remote checkpoint deserialization"}.gitattributes-34
LICENSEAdded+32
README.mdAdded+117
THIRD_PARTY_NOTICES.mdAdded+15
UPSTREAM_NOTICE.mdAdded+35
architecture.pyAdded+60
config.jsonAdded+53
evaluation.jsonAdded+145
inference.pyAdded+59
model.safetensorsAdded+3
predict.pyAdded+50
release_evidence.jsonAdded+54
requirements.txtAdded+5
training_summary.jsonAdded+65
weight_export.jsonAdded+16