Commit ·
ec3cdee
0
Parent(s):
Release TREAT-MMTB 2026 Task 2 inference
Browse files- .dockerignore +9 -0
- .gitattributes +1 -0
- Dockerfile +24 -0
- LICENSE-DINOv3.md +66 -0
- README.md +99 -0
- config.json +52 -0
- configuration_mmtb.py +15 -0
- model_manifest.json +37 -0
- modeling_base.py +108 -0
- modeling_mmtb.py +46 -0
- predict.py +194 -0
- requirements.txt +5 -0
- weights/model_0.safetensors +3 -0
- weights/model_1.safetensors +3 -0
- weights/model_2.safetensors +3 -0
- weights/model_3.safetensors +3 -0
.dockerignore
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*
|
| 2 |
+
!Dockerfile
|
| 3 |
+
!requirements.txt
|
| 4 |
+
!predict.py
|
| 5 |
+
!config.json
|
| 6 |
+
!weights/
|
| 7 |
+
!weights/model_*.safetensors
|
| 8 |
+
!LICENSE-DINOv3.md
|
| 9 |
+
!README.md
|
.gitattributes
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
Dockerfile
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM nvidia/cuda:11.8.0-cudnn8-runtime-ubuntu22.04
|
| 2 |
+
|
| 3 |
+
ENV DEBIAN_FRONTEND=noninteractive \
|
| 4 |
+
PYTHONUNBUFFERED=1 \
|
| 5 |
+
PYTHONDONTWRITEBYTECODE=1 \
|
| 6 |
+
HF_HUB_OFFLINE=1 \
|
| 7 |
+
TRANSFORMERS_OFFLINE=1
|
| 8 |
+
|
| 9 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 10 |
+
python3.10 python3-pip python3.10-dev \
|
| 11 |
+
&& ln -sf /usr/bin/python3.10 /usr/bin/python \
|
| 12 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 13 |
+
|
| 14 |
+
WORKDIR /workspace
|
| 15 |
+
COPY requirements.txt .
|
| 16 |
+
RUN python -m pip install --no-cache-dir --upgrade pip \
|
| 17 |
+
&& python -m pip install --no-cache-dir torch==2.4.1 --index-url https://download.pytorch.org/whl/cu118 \
|
| 18 |
+
&& python -m pip install --no-cache-dir -r requirements.txt
|
| 19 |
+
|
| 20 |
+
COPY predict.py config.json ./
|
| 21 |
+
COPY LICENSE-DINOv3.md README.md ./
|
| 22 |
+
COPY weights ./weights
|
| 23 |
+
RUN python -c "from pathlib import Path; expected = {f'model_{i}.safetensors' for i in range(4)}; actual = {p.name for p in Path('weights').iterdir() if p.is_file()}; assert actual == expected, (expected, actual)"
|
| 24 |
+
ENTRYPOINT ["python", "predict.py"]
|
LICENSE-DINOv3.md
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DINOv3 License
|
| 2 |
+
|
| 3 |
+
*Last Updated: August 19, 2025*
|
| 4 |
+
|
| 5 |
+
**“Agreement”** means the terms and conditions for use, reproduction, distribution and modification of the DINO Materials set forth herein.
|
| 6 |
+
|
| 7 |
+
**“DINO Materials”** means, collectively, Documentation and the models, software and algorithms, including machine-learning model code, trained model weights, inference-enabling code, training-enabling code, fine-tuning enabling code, and other elements of the foregoing distributed by Meta and made available under this Agreement.
|
| 8 |
+
|
| 9 |
+
**“Documentation”** means the specifications, manuals and documentation accompanying
|
| 10 |
+
DINO Materials distributed by Meta.
|
| 11 |
+
|
| 12 |
+
**“Licensee”** or **“you”** means you, or your employer or any other person or entity (if you are entering into this Agreement on such person or entity’s behalf), of the age required under applicable laws, rules or regulations to provide legal consent and that has legal authority to bind your employer or such other person or entity if you are entering in this Agreement on their behalf.
|
| 13 |
+
|
| 14 |
+
**“Meta”** or **“we”** means Meta Platforms Ireland Limited (if you are located in or, if you are an entity, your principal place of business is in the EEA or Switzerland) or Meta Platforms, Inc. (if you are located outside of the EEA or Switzerland).
|
| 15 |
+
|
| 16 |
+
**“Sanctions”** means any economic or trade sanctions or restrictions administered or enforced by the United States (including the Office of Foreign Assets Control of the U.S. Department of the Treasury (“OFAC”), the U.S. Department of State and the U.S. Department of Commerce), the United Nations, the European Union, or the United Kingdom.
|
| 17 |
+
|
| 18 |
+
**“Trade Controls”** means any of the following: Sanctions and applicable export and import controls.
|
| 19 |
+
|
| 20 |
+
By clicking “I Accept” below or by using or distributing any portion or element of the DINO Materials, you agree to be bound by this Agreement.
|
| 21 |
+
|
| 22 |
+
## 1. License Rights and Redistribution.
|
| 23 |
+
|
| 24 |
+
a. <ins>Grant of Rights</ins>. You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Meta’s intellectual property or other rights owned by Meta embodied in the DINO Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the DINO Materials.
|
| 25 |
+
|
| 26 |
+
b. <ins>Redistribution and Use</ins>.
|
| 27 |
+
|
| 28 |
+
i. Distribution of DINO Materials, and any derivative works thereof, are subject to the terms of this Agreement. If you distribute or make the DINO Materials, or any derivative works thereof, available to a third party, you may only do so under the terms of this Agreement and you shall provide a copy of this Agreement with any such DINO Materials.
|
| 29 |
+
|
| 30 |
+
ii. If you submit for publication the results of research you perform on, using, or otherwise in connection with DINO Materials, you must acknowledge the use of DINO Materials in your publication.
|
| 31 |
+
|
| 32 |
+
iii. Your use of the DINO Materials must comply with applicable laws and regulations, including Trade Control Laws and applicable privacy and data protection laws.
|
| 33 |
+
|
| 34 |
+
iv. Your use of the DINO Materials will not involve or encourage others to reverse engineer, decompile or discover the underlying components of the DINO Materials.
|
| 35 |
+
|
| 36 |
+
v. You are not the target of Trade Controls and your use of DINO Materials must comply with Trade Controls. You agree not to use, or permit others to use, DINO Materials for any activities subject to the International Traffic in Arms Regulations (ITAR) or end uses prohibited by Trade Controls, including those related to military or warfare purposes, nuclear industries or applications, espionage, or the development or use of guns or illegal weapons.
|
| 37 |
+
|
| 38 |
+
## 2. User Support.
|
| 39 |
+
|
| 40 |
+
Your use of the DINO Materials is done at your own discretion; Meta does not process any information nor provide any service in relation to such use. Meta is under no obligation to provide any support services for the DINO Materials. Any support provided is “as is”, “with all faults”, and without warranty of any kind.
|
| 41 |
+
|
| 42 |
+
## 3. Disclaimer of Warranty.
|
| 43 |
+
|
| 44 |
+
UNLESS REQUIRED BY APPLICABLE LAW, THE DINO MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OF ANY KIND, AND META DISCLAIMS ALL WARRANTIES OF ANY KIND, BOTH EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE DINO MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE DINO MATERIALS AND ANY OUTPUT AND RESULTS.
|
| 45 |
+
|
| 46 |
+
## 4. Limitation of Liability.
|
| 47 |
+
|
| 48 |
+
IN NO EVENT WILL META OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT OR INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
|
| 49 |
+
|
| 50 |
+
## 5. Intellectual Property.
|
| 51 |
+
|
| 52 |
+
a. Subject to Meta’s ownership of DINO Materials and derivatives made by or for Meta, with respect to any derivative works and modifications of the DINO Materials that are made by you, as between you and Meta, you are and will be the owner of such derivative works and modifications.
|
| 53 |
+
|
| 54 |
+
b. If you institute litigation or other proceedings against Meta or any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the DINO Materials, outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Meta from and against any claim by any third party arising out of or related to your use or distribution of the DINO Materials.
|
| 55 |
+
|
| 56 |
+
## 6. Term and Termination.
|
| 57 |
+
|
| 58 |
+
The term of this Agreement will commence upon your acceptance of this Agreement or access to the DINO Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Meta may terminate this Agreement if you are in breach of any term or condition of this Agreement. Upon termination of this Agreement, you shall delete and cease use of the DINO Materials. Sections 3, 4 and 7 shall survive the termination of this Agreement.
|
| 59 |
+
|
| 60 |
+
## 7. Governing Law and Jurisdiction.
|
| 61 |
+
|
| 62 |
+
This Agreement will be governed and construed under the laws of the State of California without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The courts of California shall have exclusive jurisdiction of any dispute arising out of this Agreement.
|
| 63 |
+
|
| 64 |
+
## 8. Modifications and Amendments.
|
| 65 |
+
|
| 66 |
+
Meta may modify this Agreement from time to time; provided that they are similar in spirit to the current version of the Agreement, but may differ in detail to address new problems or concerns. All such changes will be effective immediately. Your continued use of the DINO Materials after any modification to this Agreement constitutes your agreement to such modification. Except as provided in this Agreement, no modification or addition to any provision of this Agreement will be binding unless it is in writing and signed by an authorized representative of both you and Meta.
|
README.md
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
tags:
|
| 3 |
+
- treat-mmtb-2026
|
| 4 |
+
---
|
| 5 |
+
|
| 6 |
+
# MultimodalAI — TREAT-MMTB 2026 Task 2
|
| 7 |
+
|
| 8 |
+
[](https://huggingface.co/Deepnoid/TREAT-MMTB-2026-Task2-MultimodalAI) [](https://github.com/deepnoid-ai/TREAT-MMTB-2026-Task2-MultimodalAI) [](https://github.com/mi2rl-challenge/treat-mmtb.miccai2026/blob/main/leader_board_point.json) [](https://treat-mmtb.mi2rl.co/)
|
| 9 |
+
|
| 10 |
+
TB/Normal classification from chest X-ray PNGs for [TREAT-MMTB 2026](https://treat-mmtb.mi2rl.co/). Clinical metadata are not used.
|
| 11 |
+
|
| 12 |
+
## Challenge result
|
| 13 |
+
|
| 14 |
+
MultimodalAI's [official final external leaderboard](https://github.com/mi2rl-challenge/treat-mmtb.miccai2026/blob/main/leader_board_point.json) result:
|
| 15 |
+
|
| 16 |
+
| Rank | External fullset F1 |
|
| 17 |
+
| --- | --- |
|
| 18 |
+
| 2 | 0.8642 |
|
| 19 |
+
|
| 20 |
+
## Installation
|
| 21 |
+
|
| 22 |
+
Python 3.10, with PyTorch for CUDA 11.8 and dependencies from [requirements.txt](requirements.txt):
|
| 23 |
+
|
| 24 |
+
```bash
|
| 25 |
+
python -m pip install torch==2.4.1 --index-url https://download.pytorch.org/whl/cu118
|
| 26 |
+
python -m pip install -r requirements.txt
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
## AutoModel inference
|
| 30 |
+
|
| 31 |
+
Code and weights load automatically from Hugging Face.
|
| 32 |
+
|
| 33 |
+
```python
|
| 34 |
+
from transformers import AutoModel
|
| 35 |
+
|
| 36 |
+
model = AutoModel.from_pretrained(
|
| 37 |
+
"Deepnoid/TREAT-MMTB-2026-Task2-MultimodalAI",
|
| 38 |
+
trust_remote_code=True,
|
| 39 |
+
).to("cuda").eval()
|
| 40 |
+
|
| 41 |
+
result = model.predict("/path/to/image.png", output_dir=None)[0]
|
| 42 |
+
label = result["label"]
|
| 43 |
+
|
| 44 |
+
results = model.predict("/path/to/png_folder", output_dir="output/task2", batch_size=4)
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
- **Input:** a PNG file or a folder, read non-recursively with case-insensitive extensions.
|
| 48 |
+
- **Return:** always a list of results containing `filename` and `label` (`TB` or `Normal`). `output_dir=None` (default) writes no output.
|
| 49 |
+
- **Save:** setting `output_dir` writes `prediction.csv` with columns `filename,TB/Normal`.
|
| 50 |
+
|
| 51 |
+
Use `.to("cpu")` for CPU inference. The default batch size is 32; reduce it for smaller GPUs.
|
| 52 |
+
|
| 53 |
+
## CLI inference
|
| 54 |
+
|
| 55 |
+
Place all four checkpoints in `weights/` beside `predict.py` (or set `--weights`). Architecture and threshold settings are read from `config.json` (or set `--config`). `--input` accepts a file or folder.
|
| 56 |
+
|
| 57 |
+
```bash
|
| 58 |
+
python predict.py --input /path/to/png_folder --output output/task2 --batch-size 4
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
## Models and method
|
| 62 |
+
|
| 63 |
+
`weights/model_0.safetensors` through `weights/model_3.safetensors` are DINOv3 ViT-L/16 classifiers with attention pooling.
|
| 64 |
+
|
| 65 |
+
Input combines histogram equalization, CLAHE, and grayscale channels, center-padded and resized to 512 × 512. Inference ensembles four models with horizontal-flip augmentation and a decision threshold of **0.35** for `TB` versus `Normal`.
|
| 66 |
+
|
| 67 |
+
## Docker
|
| 68 |
+
|
| 69 |
+
Requires an NVIDIA GPU, driver, and [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html). Place all four [checkpoints](https://huggingface.co/Deepnoid/TREAT-MMTB-2026-Task2-MultimodalAI/tree/main/weights) in `weights/` beside the Dockerfile. Build with network access; inference runs offline.
|
| 70 |
+
|
| 71 |
+
```bash
|
| 72 |
+
docker build -t multimodalai-task2:latest .
|
| 73 |
+
mkdir -p output
|
| 74 |
+
docker run --rm --gpus all --network none \
|
| 75 |
+
-v /absolute/path/to/png_folder:/input:ro \
|
| 76 |
+
-v "$PWD/output":/output multimodalai-task2:latest
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
Append `--input /input/image.png` for a single file or `--batch-size 4` for a smaller batch. Results are saved in `output/prediction.csv`.
|
| 80 |
+
|
| 81 |
+
## Builds on
|
| 82 |
+
|
| 83 |
+
Vision-language pretraining followed GLINT (Park et al., 2026), using Meta AI / FAIR's [DINOv3](https://github.com/facebookresearch/dinov3) encoders (Siméoni et al., 2025), [MPNet](https://huggingface.co/sentence-transformers/all-mpnet-base-v2) sentence embeddings (Song et al., 2020), and report labels using [Qwen3.6-35B-A3B](https://qwen.ai/blog?id=qwen3.6-35b-a3b).
|
| 84 |
+
|
| 85 |
+
| Dataset | Use |
|
| 86 |
+
| --- | --- |
|
| 87 |
+
| [TREAT-MMTB 2026](https://doi.org/10.5281/zenodo.19732124) | Classification training |
|
| 88 |
+
| [MIMIC-CXR](https://physionet.org/content/mimic-cxr/) | Vision-language pretraining and classification training |
|
| 89 |
+
| [TB Portals](https://tbportals.niaid.nih.gov/) | Classification training |
|
| 90 |
+
| [VinDr-CXR](https://physionet.org/content/vindr-cxr/1.0.0/) | Classification training |
|
| 91 |
+
| [TBX11K](https://mmcheng.net/tb/) | Classification training |
|
| 92 |
+
| [PadChest](https://bimcv.cipf.es/bimcv-projects/padchest/) | Classification training |
|
| 93 |
+
| [Shenzhen and Montgomery](https://lhncbc.nlm.nih.gov/LHC-publications/PDF/pub9356.pdf) | Classification training (two of four ensemble members) |
|
| 94 |
+
|
| 95 |
+
## Acknowledgements
|
| 96 |
+
|
| 97 |
+
This work was supported by the Technology Innovation Program (RS-2025-02221011, Development of Medical-Specialized Multimodal Hyperscale Generative AI Technology for Global Integration) funded by the Ministry of Trade Industry & Energy (MOTIE, South Korea), and by the “Advanced GPU Utilization Support Program” funded by the Government of the Republic of Korea (Ministry of Science and ICT).
|
| 98 |
+
|
| 99 |
+
Data were obtained from the [TB Portals](https://tbportals.niaid.nih.gov), which is an open-access TB data resource supported by the National Institute of Allergy and Infectious Diseases (NIAID) Office of Cyber Infrastructure and Computational Biology (OCICB) in Bethesda, MD. These data were collected and submitted by members of the [TB Portals Consortium](https://tbportals.niaid.nih.gov/Partners). Investigators and other data contributors that originally submitted the data to the TB Portals did not participate in the design or analysis of this study (Rosenthal et al., 2017).
|
config.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_type": "treat-mmtb-2026",
|
| 3 |
+
"task": 2,
|
| 4 |
+
"mode": "cls",
|
| 5 |
+
"cls_spec": {
|
| 6 |
+
"img_size": 512,
|
| 7 |
+
"threshold": 0.35,
|
| 8 |
+
"patch_start": 5,
|
| 9 |
+
"tower": {
|
| 10 |
+
"model_type": "dinov3_vit",
|
| 11 |
+
"hidden_size": 1024,
|
| 12 |
+
"intermediate_size": 4096,
|
| 13 |
+
"num_hidden_layers": 24,
|
| 14 |
+
"num_attention_heads": 16,
|
| 15 |
+
"num_register_tokens": 4,
|
| 16 |
+
"patch_size": 16,
|
| 17 |
+
"image_size": 512,
|
| 18 |
+
"hidden_act": "gelu",
|
| 19 |
+
"attention_dropout": 0.0,
|
| 20 |
+
"drop_path_rate": 0.0,
|
| 21 |
+
"initializer_range": 0.02,
|
| 22 |
+
"layer_norm_eps": 1e-05,
|
| 23 |
+
"layerscale_value": 1.0,
|
| 24 |
+
"key_bias": false,
|
| 25 |
+
"query_bias": true,
|
| 26 |
+
"value_bias": true,
|
| 27 |
+
"proj_bias": true,
|
| 28 |
+
"mlp_bias": true,
|
| 29 |
+
"num_channels": 3,
|
| 30 |
+
"pos_embed_rescale": 2.0,
|
| 31 |
+
"rope_theta": 100.0,
|
| 32 |
+
"use_gated_mlp": false
|
| 33 |
+
},
|
| 34 |
+
"pool": {
|
| 35 |
+
"num_heads": 8
|
| 36 |
+
},
|
| 37 |
+
"head": {
|
| 38 |
+
"vision_hidden_dim": 1024,
|
| 39 |
+
"hidden_dim": 512,
|
| 40 |
+
"num_classes": 1,
|
| 41 |
+
"dropout": 0.1
|
| 42 |
+
}
|
| 43 |
+
},
|
| 44 |
+
"architectures": [
|
| 45 |
+
"MMTBModel"
|
| 46 |
+
],
|
| 47 |
+
"auto_map": {
|
| 48 |
+
"AutoConfig": "configuration_mmtb.MMTBConfig",
|
| 49 |
+
"AutoModel": "modeling_mmtb.MMTBModel"
|
| 50 |
+
},
|
| 51 |
+
"transformers_version": "4.56.1"
|
| 52 |
+
}
|
configuration_mmtb.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class MMTBConfig(PretrainedConfig):
|
| 5 |
+
model_type = "treat-mmtb-2026"
|
| 6 |
+
|
| 7 |
+
def __init__(self, task=1, mode=None, **kwargs):
|
| 8 |
+
super().__init__(**kwargs)
|
| 9 |
+
if task not in (1, 2):
|
| 10 |
+
raise ValueError("task must be 1 or 2")
|
| 11 |
+
mode = mode or ("seg" if task == 1 else "cls")
|
| 12 |
+
if mode not in (("seg", "cls") if task == 1 else ("cls",)):
|
| 13 |
+
raise ValueError(f"Unsupported mode {mode!r} for task {task}")
|
| 14 |
+
self.task = task
|
| 15 |
+
self.mode = mode
|
model_manifest.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"task": "task2",
|
| 3 |
+
"models": [
|
| 4 |
+
{
|
| 5 |
+
"name": "model_0",
|
| 6 |
+
"file": "weights/model_0.safetensors",
|
| 7 |
+
"role": "classification",
|
| 8 |
+
"bytes": 1231473340,
|
| 9 |
+
"sha256": "63698b697ec192f36d4db1f1a6d5b8a51c709b3392e929942cec8af86b965ae8",
|
| 10 |
+
"removed_training_tensors": 0
|
| 11 |
+
},
|
| 12 |
+
{
|
| 13 |
+
"name": "model_1",
|
| 14 |
+
"file": "weights/model_1.safetensors",
|
| 15 |
+
"role": "classification",
|
| 16 |
+
"bytes": 1231473340,
|
| 17 |
+
"sha256": "3e73450395023ef387dfbec933d517e0eca891efcbb7c3b730fdeed3c9c278b0",
|
| 18 |
+
"removed_training_tensors": 0
|
| 19 |
+
},
|
| 20 |
+
{
|
| 21 |
+
"name": "model_2",
|
| 22 |
+
"file": "weights/model_2.safetensors",
|
| 23 |
+
"role": "classification",
|
| 24 |
+
"bytes": 1231473340,
|
| 25 |
+
"sha256": "5848953c80779082f624874dd10189a164a6f5d7fae91d5686e761dd5cdadb3a",
|
| 26 |
+
"removed_training_tensors": 0
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"name": "model_3",
|
| 30 |
+
"file": "weights/model_3.safetensors",
|
| 31 |
+
"role": "classification",
|
| 32 |
+
"bytes": 1231473340,
|
| 33 |
+
"sha256": "e509ed08a5e1c9fd21ac50cf255e1edf6f8b68390550135aa39a40b4d8f09022",
|
| 34 |
+
"removed_training_tensors": 0
|
| 35 |
+
}
|
| 36 |
+
]
|
| 37 |
+
}
|
modeling_base.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import hashlib
|
| 3 |
+
import json
|
| 4 |
+
import shutil
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
from safetensors.torch import load_file, save_file
|
| 10 |
+
from transformers import PreTrainedModel
|
| 11 |
+
from transformers.utils.hub import cached_file
|
| 12 |
+
|
| 13 |
+
from .configuration_mmtb import MMTBConfig
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class MMTBBaseModel(PreTrainedModel):
|
| 17 |
+
config_class = MMTBConfig
|
| 18 |
+
base_model_prefix = "models"
|
| 19 |
+
|
| 20 |
+
def __init__(self, config):
|
| 21 |
+
super().__init__(config)
|
| 22 |
+
if config.task != self.task:
|
| 23 |
+
raise ValueError(f"Expected task {self.task}, received task {config.task}")
|
| 24 |
+
self.models = nn.ModuleList(self.build_models(config))
|
| 25 |
+
|
| 26 |
+
@classmethod
|
| 27 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, config=None,
|
| 28 |
+
cache_dir=None, force_download=False, local_files_only=False,
|
| 29 |
+
token=None, revision="main", **kwargs):
|
| 30 |
+
if model_args:
|
| 31 |
+
raise TypeError("Positional model arguments are not supported")
|
| 32 |
+
subfolder = kwargs.pop("subfolder", "")
|
| 33 |
+
commit_hash = kwargs.pop("_commit_hash", None)
|
| 34 |
+
for key in ("_from_auto", "_from_pipeline", "trust_remote_code", "adapter_kwargs"):
|
| 35 |
+
kwargs.pop(key, None)
|
| 36 |
+
if config is None:
|
| 37 |
+
config = cls.config_class.from_pretrained(
|
| 38 |
+
pretrained_model_name_or_path, cache_dir=cache_dir, force_download=force_download,
|
| 39 |
+
local_files_only=local_files_only, token=token, revision=revision, subfolder=subfolder,
|
| 40 |
+
)
|
| 41 |
+
config = copy.deepcopy(config)
|
| 42 |
+
if "mode" in kwargs:
|
| 43 |
+
config.mode = kwargs.pop("mode")
|
| 44 |
+
device = kwargs.pop("device", "cpu")
|
| 45 |
+
dtype = kwargs.pop("dtype", None)
|
| 46 |
+
legacy_dtype = kwargs.pop("torch_dtype", None)
|
| 47 |
+
dtype = dtype if dtype is not None else legacy_dtype
|
| 48 |
+
if dtype is None or dtype == "auto":
|
| 49 |
+
dtype = getattr(config, "dtype", None) or torch.float32
|
| 50 |
+
if kwargs:
|
| 51 |
+
raise TypeError(f"Unsupported loading arguments: {', '.join(sorted(kwargs))}; use device= or model.to() for placement")
|
| 52 |
+
if device == "auto":
|
| 53 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 54 |
+
device = torch.device(device)
|
| 55 |
+
if dtype in (None, "auto"):
|
| 56 |
+
dtype = torch.float32
|
| 57 |
+
elif isinstance(dtype, str):
|
| 58 |
+
dtype = getattr(torch, dtype, None)
|
| 59 |
+
if dtype not in (torch.float32, torch.float16, torch.bfloat16, torch.float64):
|
| 60 |
+
raise ValueError("dtype must be a floating-point torch dtype or 'auto'")
|
| 61 |
+
if config.task != cls.task:
|
| 62 |
+
raise ValueError(f"Expected task {cls.task}, received task {config.task}")
|
| 63 |
+
indices = cls.checkpoint_indices(config)
|
| 64 |
+
resolved_revision = getattr(config, "_commit_hash", None) or commit_hash or revision
|
| 65 |
+
paths = [cached_file(
|
| 66 |
+
pretrained_model_name_or_path, f"weights/model_{index}.safetensors",
|
| 67 |
+
cache_dir=cache_dir, force_download=force_download, local_files_only=local_files_only,
|
| 68 |
+
token=token, revision=resolved_revision, subfolder=subfolder,
|
| 69 |
+
) for index in indices]
|
| 70 |
+
model = cls(config)
|
| 71 |
+
for net, path in zip(model.models, paths):
|
| 72 |
+
net.load_state_dict(load_file(path), strict=True)
|
| 73 |
+
net.to(device=device, dtype=dtype)
|
| 74 |
+
model.eval()
|
| 75 |
+
return model
|
| 76 |
+
|
| 77 |
+
def save_pretrained(self, save_directory, **kwargs):
|
| 78 |
+
if kwargs:
|
| 79 |
+
raise TypeError(f"Unsupported saving arguments: {', '.join(sorted(kwargs))}")
|
| 80 |
+
directory = Path(save_directory)
|
| 81 |
+
directory.mkdir(parents=True, exist_ok=True)
|
| 82 |
+
weights = directory / "weights"
|
| 83 |
+
weights.mkdir(exist_ok=True)
|
| 84 |
+
expected = {f"model_{index}.safetensors" for index in self.checkpoint_indices(self.config)}
|
| 85 |
+
if any(path.name not in expected for path in weights.iterdir()):
|
| 86 |
+
raise ValueError("Save to a fresh directory or one containing only the selected checkpoint files")
|
| 87 |
+
entries = []
|
| 88 |
+
for index, net in zip(self.checkpoint_indices(self.config), self.models):
|
| 89 |
+
target = weights / f"model_{index}.safetensors"
|
| 90 |
+
state = {name: tensor.detach().cpu().contiguous() for name, tensor in net.state_dict().items()}
|
| 91 |
+
save_file(state, str(target), metadata={"format": "pt"})
|
| 92 |
+
digest = hashlib.sha256()
|
| 93 |
+
with target.open("rb") as source:
|
| 94 |
+
for chunk in iter(lambda: source.read(8 * 1024 * 1024), b""):
|
| 95 |
+
digest.update(chunk)
|
| 96 |
+
entries.append({"name": f"model_{index}", "file": f"weights/{target.name}",
|
| 97 |
+
"bytes": target.stat().st_size, "sha256": digest.hexdigest()})
|
| 98 |
+
config = copy.deepcopy(self.config)
|
| 99 |
+
config.auto_map = {"AutoConfig": "configuration_mmtb.MMTBConfig", "AutoModel": "modeling_mmtb.MMTBModel"}
|
| 100 |
+
config.architectures = ["MMTBModel"]
|
| 101 |
+
config.dtype = self.dtype
|
| 102 |
+
config.save_pretrained(directory)
|
| 103 |
+
for filename in ("configuration_mmtb.py", "modeling_base.py", "modeling_mmtb.py", "predict.py"):
|
| 104 |
+
source = Path(__file__).resolve().parent / filename
|
| 105 |
+
target = directory / filename
|
| 106 |
+
if source.resolve() != target.resolve():
|
| 107 |
+
shutil.copyfile(source, target)
|
| 108 |
+
(directory / "model_manifest.json").write_text(json.dumps({"task": f"task{self.task}", "models": entries}, indent=2) + "\n")
|
modeling_mmtb.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import csv
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from .configuration_mmtb import MMTBConfig
|
| 7 |
+
from .modeling_base import MMTBBaseModel
|
| 8 |
+
from .predict import TBModel, Task2Model, discover_images
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class MMTBModel(MMTBBaseModel):
|
| 12 |
+
config_class = MMTBConfig
|
| 13 |
+
task = 2
|
| 14 |
+
|
| 15 |
+
@staticmethod
|
| 16 |
+
def checkpoint_indices(config):
|
| 17 |
+
if config.mode != "cls":
|
| 18 |
+
raise ValueError("task 2 supports mode='cls' only")
|
| 19 |
+
return range(4)
|
| 20 |
+
|
| 21 |
+
@classmethod
|
| 22 |
+
def build_models(cls, config):
|
| 23 |
+
return [TBModel(config.cls_spec) for _ in cls.checkpoint_indices(config)]
|
| 24 |
+
|
| 25 |
+
@torch.inference_mode()
|
| 26 |
+
def predict(self, input_path, output_dir=None, batch_size=32):
|
| 27 |
+
if batch_size < 1:
|
| 28 |
+
raise ValueError("batch_size must be at least 1")
|
| 29 |
+
paths = discover_images(input_path)
|
| 30 |
+
pipeline = Task2Model(self.models, self.config.cls_spec)
|
| 31 |
+
results = []
|
| 32 |
+
for start in range(0, len(paths), batch_size):
|
| 33 |
+
batch = paths[start:start + batch_size]
|
| 34 |
+
results.extend({"filename": path.name, "label": label}
|
| 35 |
+
for path, label in zip(batch, pipeline.predict_batch(batch)))
|
| 36 |
+
if output_dir is not None:
|
| 37 |
+
output = Path(output_dir)
|
| 38 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 39 |
+
with (output / "prediction.csv").open("w", newline="") as stream:
|
| 40 |
+
writer = csv.writer(stream)
|
| 41 |
+
writer.writerow(["filename", "TB/Normal"])
|
| 42 |
+
writer.writerows((result["filename"], result["label"]) for result in results)
|
| 43 |
+
return results
|
| 44 |
+
|
| 45 |
+
def forward(self, input_path, output_dir=None, batch_size=32):
|
| 46 |
+
return self.predict(input_path, output_dir=output_dir, batch_size=batch_size)
|
predict.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import csv
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import PIL.Image
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
|
| 12 |
+
IMAGENET_MEAN = (0.485, 0.456, 0.406)
|
| 13 |
+
IMAGENET_STD = (0.229, 0.224, 0.225)
|
| 14 |
+
CLAHE_CLIP, CLAHE_GRID = 1.0, (8, 8)
|
| 15 |
+
DEFAULT_WEIGHTS = Path(__file__).resolve().parent / "weights"
|
| 16 |
+
DEFAULT_CONFIG = Path(__file__).resolve().parent / "config.json"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
ID2LABEL = {0: "Normal", 1: "TB"}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def load_config(config_path=DEFAULT_CONFIG):
|
| 23 |
+
return json.loads(Path(config_path).read_text())
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def minmax_uint8(arr):
|
| 27 |
+
arr = np.asarray(arr).astype(np.float32)
|
| 28 |
+
mn, mx = float(arr.min()), float(arr.max())
|
| 29 |
+
return ((arr - mn) / (mx - mn + 1e-8) * 255.0).astype(np.uint8)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def png_to_image(png_path):
|
| 33 |
+
import cv2
|
| 34 |
+
|
| 35 |
+
base = minmax_uint8(np.asarray(PIL.Image.open(png_path).convert("L")))
|
| 36 |
+
eq = cv2.equalizeHist(base)
|
| 37 |
+
clahe = cv2.createCLAHE(clipLimit=CLAHE_CLIP, tileGridSize=CLAHE_GRID).apply(base)
|
| 38 |
+
return np.stack([eq, clahe, base], axis=-1)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def pad_to_square(img):
|
| 42 |
+
h, w = img.shape[:2]
|
| 43 |
+
if h == w:
|
| 44 |
+
return img
|
| 45 |
+
s = max(h, w)
|
| 46 |
+
top, left = (s - h) // 2, (s - w) // 2
|
| 47 |
+
out = np.zeros((s, s, img.shape[2]), dtype=img.dtype)
|
| 48 |
+
out[top : top + h, left : left + w, :] = img
|
| 49 |
+
return out
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def to_input(img3, size, mean, std, device, dtype):
|
| 53 |
+
x = torch.from_numpy(np.ascontiguousarray(pad_to_square(img3))).permute(2, 0, 1)[None].float()
|
| 54 |
+
if tuple(x.shape[-2:]) != (size, size):
|
| 55 |
+
x = F.interpolate(x, size=(size, size), mode="bilinear", align_corners=False, antialias=True)
|
| 56 |
+
x = x / 255.0
|
| 57 |
+
x = (x - torch.tensor(mean).view(1, 3, 1, 1)) / torch.tensor(std).view(1, 3, 1, 1)
|
| 58 |
+
return x[0].to(device=device, dtype=dtype)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def build_vit(tower_cfg):
|
| 62 |
+
from transformers import AutoConfig, AutoModel
|
| 63 |
+
|
| 64 |
+
cfg = AutoConfig.for_model(tower_cfg["model_type"], **{k: v for k, v in tower_cfg.items() if k != "model_type"})
|
| 65 |
+
return AutoModel.from_config(cfg)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class AttnPool(nn.Module):
|
| 69 |
+
def __init__(self, dim, num_heads=8):
|
| 70 |
+
super().__init__()
|
| 71 |
+
self.query = nn.Parameter(torch.zeros(1, 1, dim))
|
| 72 |
+
self.attn = nn.MultiheadAttention(dim, num_heads, batch_first=True)
|
| 73 |
+
self.norm = nn.LayerNorm(dim)
|
| 74 |
+
|
| 75 |
+
def forward(self, tokens):
|
| 76 |
+
q = self.query.expand(tokens.shape[0], -1, -1)
|
| 77 |
+
pooled, _ = self.attn(q, tokens, tokens, need_weights=False)
|
| 78 |
+
return self.norm(pooled.squeeze(1))
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class Head(nn.Module):
|
| 82 |
+
def __init__(self, in_channels, hidden_dim, num_classes, dropout):
|
| 83 |
+
super().__init__()
|
| 84 |
+
self.mlp = nn.Sequential(
|
| 85 |
+
nn.Linear(in_channels, hidden_dim), nn.GELU(), nn.Dropout(dropout), nn.Linear(hidden_dim, num_classes)
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
def forward(self, x):
|
| 89 |
+
return self.mlp(x).squeeze(-1)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class TBModel(nn.Module):
|
| 93 |
+
def __init__(self, spec):
|
| 94 |
+
super().__init__()
|
| 95 |
+
self.vision_model = build_vit(spec["tower"])
|
| 96 |
+
self.patch_start = int(spec["patch_start"])
|
| 97 |
+
d = int(spec["head"]["vision_hidden_dim"])
|
| 98 |
+
self.pool = AttnPool(d, num_heads=int(spec["pool"]["num_heads"]))
|
| 99 |
+
self.head = Head(d, int(spec["head"]["hidden_dim"]), int(spec["head"]["num_classes"]), float(spec["head"]["dropout"]))
|
| 100 |
+
|
| 101 |
+
def _tokens(self, pixel_values):
|
| 102 |
+
return self.vision_model(pixel_values).last_hidden_state[:, self.patch_start :, :]
|
| 103 |
+
|
| 104 |
+
def forward(self, pixel_values):
|
| 105 |
+
return self.head(self.pool(self._tokens(pixel_values)))
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class Task2Model:
|
| 109 |
+
def __init__(self, nets, spec):
|
| 110 |
+
self.nets = list(nets)
|
| 111 |
+
self.size = int(spec["img_size"])
|
| 112 |
+
self.thr = float(spec["threshold"])
|
| 113 |
+
p = next(self.nets[0].parameters())
|
| 114 |
+
self.device, self.dtype = p.device, p.dtype
|
| 115 |
+
|
| 116 |
+
@torch.no_grad()
|
| 117 |
+
def predict_batch(self, paths):
|
| 118 |
+
x = torch.stack([
|
| 119 |
+
to_input(png_to_image(p), self.size, IMAGENET_MEAN, IMAGENET_STD, self.device, self.dtype)
|
| 120 |
+
for p in paths
|
| 121 |
+
])
|
| 122 |
+
logits = []
|
| 123 |
+
for net in self.nets:
|
| 124 |
+
logits.append(net(x).reshape(-1).float())
|
| 125 |
+
logits.append(net(torch.flip(x, dims=[-1])).reshape(-1).float())
|
| 126 |
+
probs = torch.sigmoid(torch.stack(logits).mean(0)).cpu().numpy()
|
| 127 |
+
return [ID2LABEL[int(pr >= self.thr)] for pr in probs]
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def load_model(weights_path=DEFAULT_WEIGHTS, device="auto", config_path=DEFAULT_CONFIG):
|
| 131 |
+
from safetensors.torch import load_file
|
| 132 |
+
|
| 133 |
+
paths = [Path(weights_path) / f"model_{i}.safetensors" for i in range(4)]
|
| 134 |
+
for path in paths:
|
| 135 |
+
if not path.is_file():
|
| 136 |
+
raise FileNotFoundError(f"Missing model weights: {path}")
|
| 137 |
+
spec = load_config(config_path)["cls_spec"]
|
| 138 |
+
dev = torch.device("cuda" if torch.cuda.is_available() else "cpu") if device == "auto" else torch.device(device)
|
| 139 |
+
nets = []
|
| 140 |
+
for path in paths:
|
| 141 |
+
net = TBModel(spec)
|
| 142 |
+
net.load_state_dict(load_file(str(path)), strict=True)
|
| 143 |
+
nets.append(net.to(dev).eval())
|
| 144 |
+
print(f"[weights] loaded {path.name}", flush=True)
|
| 145 |
+
return Task2Model(nets, spec)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def discover_images(input_path):
|
| 149 |
+
path = Path(input_path)
|
| 150 |
+
if path.is_file():
|
| 151 |
+
if path.suffix.lower() != ".png":
|
| 152 |
+
raise ValueError(f"Expected a PNG file: {path}")
|
| 153 |
+
return [path]
|
| 154 |
+
if not path.is_dir():
|
| 155 |
+
raise FileNotFoundError(f"Input does not exist: {path}")
|
| 156 |
+
paths = sorted(p for p in path.iterdir() if p.is_file() and p.suffix.lower() == ".png")
|
| 157 |
+
if not paths:
|
| 158 |
+
raise ValueError(f"No PNG files found in: {path}")
|
| 159 |
+
return paths
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def predict(input_path, output_dir, weights_path=DEFAULT_WEIGHTS, batch_size=32, device="auto", config_path=DEFAULT_CONFIG):
|
| 163 |
+
if batch_size < 1:
|
| 164 |
+
raise ValueError("batch_size must be at least 1")
|
| 165 |
+
paths = discover_images(input_path)
|
| 166 |
+
model = load_model(weights_path, device=device, config_path=config_path)
|
| 167 |
+
output_dir = Path(output_dir)
|
| 168 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 169 |
+
rows = []
|
| 170 |
+
for i in range(0, len(paths), batch_size):
|
| 171 |
+
batch = paths[i:i + batch_size]
|
| 172 |
+
rows.extend((path.name, label) for path, label in zip(batch, model.predict_batch(batch)))
|
| 173 |
+
with (output_dir / "prediction.csv").open("w", newline="") as f:
|
| 174 |
+
writer = csv.writer(f)
|
| 175 |
+
writer.writerow(["filename", "TB/Normal"])
|
| 176 |
+
writer.writerows(rows)
|
| 177 |
+
print(f"[done] wrote {len(rows)} predictions -> {output_dir}", flush=True)
|
| 178 |
+
return rows
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def main():
|
| 182 |
+
parser = argparse.ArgumentParser(description="MultimodalAI: TB/Normal classification")
|
| 183 |
+
parser.add_argument("--input", default="/input", help="PNG file or directory of PNG files")
|
| 184 |
+
parser.add_argument("--output", default="/output", help="output directory")
|
| 185 |
+
parser.add_argument("--weights", default=str(DEFAULT_WEIGHTS), help="directory containing model_0.safetensors through model_3.safetensors")
|
| 186 |
+
parser.add_argument("--config", default=str(DEFAULT_CONFIG), help="config.json holding model and threshold settings")
|
| 187 |
+
parser.add_argument("--batch-size", type=int, default=32)
|
| 188 |
+
parser.add_argument("--device", default="auto", help="auto, cpu, cuda, or cuda:N")
|
| 189 |
+
args = parser.parse_args()
|
| 190 |
+
predict(args.input, args.output, args.weights, args.batch_size, args.device, args.config)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
if __name__ == "__main__":
|
| 194 |
+
main()
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
transformers==4.56.1
|
| 2 |
+
safetensors==0.8.0
|
| 3 |
+
numpy==1.26.4
|
| 4 |
+
opencv-python-headless==4.10.0.84
|
| 5 |
+
pillow>=10
|
weights/model_0.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:63698b697ec192f36d4db1f1a6d5b8a51c709b3392e929942cec8af86b965ae8
|
| 3 |
+
size 1231473340
|
weights/model_1.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3e73450395023ef387dfbec933d517e0eca891efcbb7c3b730fdeed3c9c278b0
|
| 3 |
+
size 1231473340
|
weights/model_2.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5848953c80779082f624874dd10189a164a6f5d7fae91d5686e761dd5cdadb3a
|
| 3 |
+
size 1231473340
|
weights/model_3.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e509ed08a5e1c9fd21ac50cf255e1edf6f8b68390550135aa39a40b4d8f09022
|
| 3 |
+
size 1231473340
|