Text Classification
Transformers
Safetensors
English
chest2vec_labeler
feature-extraction
radiology
chest-ct
report-labeling
multi-label
ct-rate
chexbert-style-f1
custom_code
Instructions to use chest2vec/chest2vec_labeler with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use chest2vec/chest2vec_labeler with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="chest2vec/chest2vec_labeler", trust_remote_code=True)# Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("chest2vec/chest2vec_labeler", trust_remote_code=True, dtype="auto") - Notebooks
- Google Colab
- Kaggle
chest2vec CT report labeler (0.6B): self-contained AutoModel, 137-leaf ternary, CheXbert-style report F1
Browse files- .gitattributes +1 -0
- README.md +130 -0
- config.json +273 -0
- merges.txt +0 -0
- model.safetensors +3 -0
- modeling_chest2vec_labeler.py +241 -0
- tokenizer.json +3 -0
- tokenizer_config.json +240 -0
- vocab.json +0 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: cc-by-nc-sa-4.0
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
base_model:
|
| 6 |
+
- Qwen/Qwen3-Embedding-0.6B
|
| 7 |
+
datasets:
|
| 8 |
+
- chest2vec/chest2vec_labels
|
| 9 |
+
pipeline_tag: text-classification
|
| 10 |
+
library_name: transformers
|
| 11 |
+
tags:
|
| 12 |
+
- radiology
|
| 13 |
+
- chest-ct
|
| 14 |
+
- report-labeling
|
| 15 |
+
- multi-label
|
| 16 |
+
- ct-rate
|
| 17 |
+
- chexbert-style-f1
|
| 18 |
+
---
|
| 19 |
+
|
| 20 |
+
# chest2vec CT Report Labeler (0.6B)
|
| 21 |
+
|
| 22 |
+
A weakly-supervised **multi-label classifier** that reads a free-text **chest-CT report** and
|
| 23 |
+
predicts a **137-leaf chest-imaging taxonomy**, with a **ternary** status per label
|
| 24 |
+
(*negative / uncertain / positive*).
|
| 25 |
+
|
| 26 |
+
It also provides a **CheXbert / SRR-BERT-style report-comparison F1**: label a list of
|
| 27 |
+
ground-truth reports and a list of generated/predicted reports, then score them against each
|
| 28 |
+
other (micro / macro / weighted F1) — useful for evaluating radiology report generation.
|
| 29 |
+
|
| 30 |
+
- **Base architecture:** [`Qwen/Qwen3-Embedding-0.6B`](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B) (Apache-2.0)
|
| 31 |
+
- **Adaptation:** LoRA (r=16, α=32) **merged into the weights** + last-token (EOS) pooling + L2-norm + a linear ternary head (`1024 → 137 × 3`)
|
| 32 |
+
- **Self-contained:** the full model (encoder + head) ships in `model.safetensors`. Loading does **not** download Qwen3-Embedding weights — the architecture is rebuilt from the bundled config and our weights are loaded in. Tokenizer is bundled too.
|
| 33 |
+
- **Params:** ~596M · weights in float32
|
| 34 |
+
- **Training labels:** [`chest2vec/chest2vec_labels`](https://huggingface.co/datasets/chest2vec/chest2vec_labels) (revised CT-RATE, 137-leaf taxonomy)
|
| 35 |
+
|
| 36 |
+
## Label space
|
| 37 |
+
|
| 38 |
+
137 leaf labels over 9 chest-CT sections (Lungs & Airways, Pleura, Mediastinum & Hila,
|
| 39 |
+
Cardiovascular, Chest Wall, Bones/Spine, Upper Abdomen, Lower Neck, Others). The exact list is
|
| 40 |
+
in `config.json` (`labels`); full definitions and per-split counts are in the dataset's
|
| 41 |
+
[`LABEL_HIERARCHY.md`](https://huggingface.co/datasets/chest2vec/chest2vec_labels/blob/main/LABEL_HIERARCHY.md).
|
| 42 |
+
|
| 43 |
+
**Ternary head** — `softmax(logits, dim=-1)` over class indices `[0, 1, 2]`:
|
| 44 |
+
|
| 45 |
+
| class index | meaning | value |
|
| 46 |
+
|---:|---|---:|
|
| 47 |
+
| 0 | negative | 0 |
|
| 48 |
+
| 1 | uncertain | -1 |
|
| 49 |
+
| 2 | positive | 1 |
|
| 50 |
+
|
| 51 |
+
A label is reported **positive** when `P(class=2) ≥ threshold` (default **0.5**).
|
| 52 |
+
|
| 53 |
+
## Usage
|
| 54 |
+
|
| 55 |
+
```python
|
| 56 |
+
from transformers import AutoModel, AutoTokenizer
|
| 57 |
+
|
| 58 |
+
model = AutoModel.from_pretrained("chest2vec/chest2vec_labeler", trust_remote_code=True).eval()
|
| 59 |
+
tok = AutoTokenizer.from_pretrained("chest2vec/chest2vec_labeler", trust_remote_code=True)
|
| 60 |
+
|
| 61 |
+
reports = ["Bibasilar atelectasis with small bilateral pleural effusions. Cardiomegaly. Coronary artery calcification."]
|
| 62 |
+
|
| 63 |
+
# 1) human-readable positive labels per report
|
| 64 |
+
print(model.label_reports(reports, tokenizer=tok))
|
| 65 |
+
# [{'Subsegmental / linear atelectasis': 'positive', 'Pleural effusion': 'positive',
|
| 66 |
+
# 'Cardiomegaly': 'positive', 'Coronary artery calcification': 'positive'}]
|
| 67 |
+
|
| 68 |
+
# 2) full prediction matrices
|
| 69 |
+
out = model.predict(reports, tokenizer=tok, threshold=0.5, return_ternary=True)
|
| 70 |
+
out["labels"] # list of 137 label names
|
| 71 |
+
out["proba"] # [N, 137] P(positive)
|
| 72 |
+
out["positive"] # [N, 137] in {0,1}
|
| 73 |
+
out["ternary"] # [N, 137] in {-1,0,1}
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
### CheXbert / SRR-BERT-style report comparison
|
| 77 |
+
|
| 78 |
+
Label both ground-truth and predicted reports, then compute label-level F1 (GT-labels treated
|
| 79 |
+
as truth):
|
| 80 |
+
|
| 81 |
+
```python
|
| 82 |
+
res = model.score_reports(gt_reports, pred_reports, tokenizer=tok) # equal-length lists
|
| 83 |
+
print(res["micro"]["f1"], res["macro"]["f1"], res["weighted"]["f1"])
|
| 84 |
+
print(res["per_label"]["Pleural effusion"]) # {'precision':..,'recall':..,'f1':..,'support_gt':..}
|
| 85 |
+
|
| 86 |
+
# or one-liner that loads the model for you:
|
| 87 |
+
from modeling_chest2vec_labeler import report_f1
|
| 88 |
+
report_f1(gt_reports, pred_reports, tokenizer=tok)
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
Returns `micro`, `macro`, `weighted` precision/recall/F1 over the 137 labels, plus `per_label`.
|
| 92 |
+
|
| 93 |
+
## Inputs & conventions
|
| 94 |
+
|
| 95 |
+
- Input is the **findings** text (the model was trained on CT-RATE findings + their refined
|
| 96 |
+
section-structured form). Reports are formatted internally as
|
| 97 |
+
`Instruct: Given the following chest CT report, extract the presence/absence of entities\nQuery: <report>`,
|
| 98 |
+
truncated to **512** tokens, with an EOS token appended and left-padding.
|
| 99 |
+
- For best fidelity, run in float32 (default). bf16 is fine for throughput with negligible drift.
|
| 100 |
+
|
| 101 |
+
## Evaluation
|
| 102 |
+
|
| 103 |
+
Direct-paragraph evaluation (`softmax positive-class`, macro-F1 over labels with ≥30 positives —
|
| 104 |
+
the stable headline; the all-labels macro is dragged down by sparse-tail labels):
|
| 105 |
+
|
| 106 |
+
| Eval set | reports | macro-F1 (≥30) @0.33 | macro-F1 (≥30) @0.5 | macro-AUC (≥30) |
|
| 107 |
+
|---|--:|--:|--:|--:|
|
| 108 |
+
| CT-RATE revised test (public) | 1,464 | **0.875** | 0.866 | 0.989 |
|
| 109 |
+
| sample1000 (private radiologist-reviewed gold) | 1,000 | **0.766** | 0.761 | 0.972 |
|
| 110 |
+
|
| 111 |
+
On the public test set, a radiologist reviewed **966 reports**: **857 fully accepted, 60
|
| 112 |
+
imperfect-but-acceptable, 49 failed** (94.9% acceptable). AUC barely moves public→private
|
| 113 |
+
(0.989 → 0.972), i.e. label ranking transfers to real clinical reports; the F1 gap is mostly
|
| 114 |
+
threshold/labeling-convention, not domain failure.
|
| 115 |
+
|
| 116 |
+
## Caveats
|
| 117 |
+
|
| 118 |
+
- **Weakly supervised** — trained on LLM-generated labels (not radiologist ground truth) derived
|
| 119 |
+
from report **text**, not images. Not a medical device; not for clinical use.
|
| 120 |
+
- `IVC filter` is in the taxonomy for completeness but had no training positives.
|
| 121 |
+
- `score_reports` measures **label agreement** between two reports as judged by this labeler;
|
| 122 |
+
like CheXbert-F1 it inherits the labeler's own error modes.
|
| 123 |
+
|
| 124 |
+
## License & attribution
|
| 125 |
+
|
| 126 |
+
Released under **CC-BY-NC-SA-4.0**. Built on **`Qwen/Qwen3-Embedding-0.6B`** (Apache-2.0) and
|
| 127 |
+
trained using labels derived from **[CT-RATE](https://huggingface.co/datasets/ibrahimhamamci/CT-RATE)**
|
| 128 |
+
(CC-BY-NC-SA-4.0). **If you use this model, cite the CT-RATE paper** (arXiv:2403.17834) and
|
| 129 |
+
acknowledge Qwen3-Embedding. See the [dataset card](https://huggingface.co/datasets/chest2vec/chest2vec_labels)
|
| 130 |
+
for the full citation.
|
config.json
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_type": "chest2vec_labeler",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"Chest2VecLabelerModel"
|
| 5 |
+
],
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "modeling_chest2vec_labeler.Chest2VecLabelerConfig",
|
| 8 |
+
"AutoModel": "modeling_chest2vec_labeler.Chest2VecLabelerModel"
|
| 9 |
+
},
|
| 10 |
+
"base_model": "Qwen/Qwen3-Embedding-0.6B",
|
| 11 |
+
"encoder_config": {
|
| 12 |
+
"vocab_size": 151669,
|
| 13 |
+
"max_position_embeddings": 32768,
|
| 14 |
+
"hidden_size": 1024,
|
| 15 |
+
"intermediate_size": 3072,
|
| 16 |
+
"num_hidden_layers": 28,
|
| 17 |
+
"num_attention_heads": 16,
|
| 18 |
+
"use_sliding_window": false,
|
| 19 |
+
"sliding_window": null,
|
| 20 |
+
"max_window_layers": 28,
|
| 21 |
+
"num_key_value_heads": 8,
|
| 22 |
+
"head_dim": 128,
|
| 23 |
+
"hidden_act": "silu",
|
| 24 |
+
"initializer_range": 0.02,
|
| 25 |
+
"rms_norm_eps": 1e-06,
|
| 26 |
+
"use_cache": true,
|
| 27 |
+
"rope_theta": 1000000,
|
| 28 |
+
"rope_scaling": null,
|
| 29 |
+
"attention_bias": false,
|
| 30 |
+
"attention_dropout": 0.0,
|
| 31 |
+
"layer_types": [
|
| 32 |
+
"full_attention",
|
| 33 |
+
"full_attention",
|
| 34 |
+
"full_attention",
|
| 35 |
+
"full_attention",
|
| 36 |
+
"full_attention",
|
| 37 |
+
"full_attention",
|
| 38 |
+
"full_attention",
|
| 39 |
+
"full_attention",
|
| 40 |
+
"full_attention",
|
| 41 |
+
"full_attention",
|
| 42 |
+
"full_attention",
|
| 43 |
+
"full_attention",
|
| 44 |
+
"full_attention",
|
| 45 |
+
"full_attention",
|
| 46 |
+
"full_attention",
|
| 47 |
+
"full_attention",
|
| 48 |
+
"full_attention",
|
| 49 |
+
"full_attention",
|
| 50 |
+
"full_attention",
|
| 51 |
+
"full_attention",
|
| 52 |
+
"full_attention",
|
| 53 |
+
"full_attention",
|
| 54 |
+
"full_attention",
|
| 55 |
+
"full_attention",
|
| 56 |
+
"full_attention",
|
| 57 |
+
"full_attention",
|
| 58 |
+
"full_attention",
|
| 59 |
+
"full_attention"
|
| 60 |
+
],
|
| 61 |
+
"return_dict": true,
|
| 62 |
+
"output_hidden_states": false,
|
| 63 |
+
"torchscript": false,
|
| 64 |
+
"dtype": "bfloat16",
|
| 65 |
+
"pruned_heads": {},
|
| 66 |
+
"tie_word_embeddings": true,
|
| 67 |
+
"chunk_size_feed_forward": 0,
|
| 68 |
+
"is_encoder_decoder": false,
|
| 69 |
+
"is_decoder": false,
|
| 70 |
+
"cross_attention_hidden_size": null,
|
| 71 |
+
"add_cross_attention": false,
|
| 72 |
+
"tie_encoder_decoder": false,
|
| 73 |
+
"architectures": [
|
| 74 |
+
"Qwen3ForCausalLM"
|
| 75 |
+
],
|
| 76 |
+
"finetuning_task": null,
|
| 77 |
+
"id2label": {
|
| 78 |
+
"0": "LABEL_0",
|
| 79 |
+
"1": "LABEL_1"
|
| 80 |
+
},
|
| 81 |
+
"label2id": {
|
| 82 |
+
"LABEL_0": 0,
|
| 83 |
+
"LABEL_1": 1
|
| 84 |
+
},
|
| 85 |
+
"task_specific_params": null,
|
| 86 |
+
"problem_type": null,
|
| 87 |
+
"tokenizer_class": null,
|
| 88 |
+
"prefix": null,
|
| 89 |
+
"bos_token_id": 151643,
|
| 90 |
+
"pad_token_id": null,
|
| 91 |
+
"eos_token_id": 151643,
|
| 92 |
+
"sep_token_id": null,
|
| 93 |
+
"decoder_start_token_id": null,
|
| 94 |
+
"max_length": 20,
|
| 95 |
+
"min_length": 0,
|
| 96 |
+
"do_sample": false,
|
| 97 |
+
"early_stopping": false,
|
| 98 |
+
"num_beams": 1,
|
| 99 |
+
"temperature": 1.0,
|
| 100 |
+
"top_k": 50,
|
| 101 |
+
"top_p": 1.0,
|
| 102 |
+
"typical_p": 1.0,
|
| 103 |
+
"repetition_penalty": 1.0,
|
| 104 |
+
"length_penalty": 1.0,
|
| 105 |
+
"no_repeat_ngram_size": 0,
|
| 106 |
+
"encoder_no_repeat_ngram_size": 0,
|
| 107 |
+
"bad_words_ids": null,
|
| 108 |
+
"num_return_sequences": 1,
|
| 109 |
+
"output_scores": false,
|
| 110 |
+
"return_dict_in_generate": false,
|
| 111 |
+
"forced_bos_token_id": null,
|
| 112 |
+
"forced_eos_token_id": null,
|
| 113 |
+
"remove_invalid_values": false,
|
| 114 |
+
"exponential_decay_length_penalty": null,
|
| 115 |
+
"suppress_tokens": null,
|
| 116 |
+
"begin_suppress_tokens": null,
|
| 117 |
+
"num_beam_groups": 1,
|
| 118 |
+
"diversity_penalty": 0.0,
|
| 119 |
+
"_name_or_path": "Qwen/Qwen3-Embedding-0.6B",
|
| 120 |
+
"transformers_version": "4.57.3",
|
| 121 |
+
"model_type": "qwen3",
|
| 122 |
+
"tf_legacy_loss": false,
|
| 123 |
+
"use_bfloat16": false,
|
| 124 |
+
"output_attentions": false
|
| 125 |
+
},
|
| 126 |
+
"hidden_size": 1024,
|
| 127 |
+
"num_classes_per_label": 3,
|
| 128 |
+
"labels": [
|
| 129 |
+
"Consolidation",
|
| 130 |
+
"Ground-glass opacity (GGO)",
|
| 131 |
+
"Crazy-paving pattern",
|
| 132 |
+
"Mosaic attenuation / air-trapping",
|
| 133 |
+
"Tree-in-bud",
|
| 134 |
+
"Centrilobular nodules / bronchiolitis pattern",
|
| 135 |
+
"Pulmonary nodule (solid / PSN / GGN)",
|
| 136 |
+
"Pulmonary mass (>3 cm)",
|
| 137 |
+
"Cavitary nodule / mass",
|
| 138 |
+
"Emphysema",
|
| 139 |
+
"Bullae / giant bulla",
|
| 140 |
+
"Pulmonary cysts / cystic lung disease",
|
| 141 |
+
"Reticulation / intralobular thickening",
|
| 142 |
+
"Interlobular septal thickening",
|
| 143 |
+
"Traction bronchiectasis / bronchiolectasis",
|
| 144 |
+
"Honeycombing",
|
| 145 |
+
"Parenchymal scarring / fibrotic band",
|
| 146 |
+
"Tracheal stenosis / malacia",
|
| 147 |
+
"Tracheal / bronchial wall thickening",
|
| 148 |
+
"Bronchiectasis",
|
| 149 |
+
"Mucoid impaction / plugging",
|
| 150 |
+
"Tracheal diverticulum",
|
| 151 |
+
"Endotracheal tube",
|
| 152 |
+
"Tracheostomy tube",
|
| 153 |
+
"Lobar / segmental atelectasis",
|
| 154 |
+
"Subsegmental / linear atelectasis",
|
| 155 |
+
"Post-lobectomy / segmentectomy",
|
| 156 |
+
"Post-pneumonectomy",
|
| 157 |
+
"Lung transplant",
|
| 158 |
+
"Lungs & Airways_others",
|
| 159 |
+
"Pleural effusion",
|
| 160 |
+
"Loculated pleural effusion",
|
| 161 |
+
"Hemothorax",
|
| 162 |
+
"Chest tube / pleural drain",
|
| 163 |
+
"Pneumothorax",
|
| 164 |
+
"Tension pneumothorax",
|
| 165 |
+
"Pleural thickening",
|
| 166 |
+
"Pleural plaques",
|
| 167 |
+
"Pleural nodule / mass",
|
| 168 |
+
"Pleura_others",
|
| 169 |
+
"Mediastinal lymphadenopathy",
|
| 170 |
+
"Hilar lymphadenopathy",
|
| 171 |
+
"Calcified mediastinal / hilar lymph nodes",
|
| 172 |
+
"Anterior mediastinal mass",
|
| 173 |
+
"Middle / posterior mediastinal mass or cyst",
|
| 174 |
+
"Thymic remnant / hyperplasia",
|
| 175 |
+
"Esophageal wall thickening / mass",
|
| 176 |
+
"Hiatal hernia",
|
| 177 |
+
"Esophageal dilation",
|
| 178 |
+
"Nasogastric / orogastric tube",
|
| 179 |
+
"Pneumomediastinum",
|
| 180 |
+
"Mediastinal hematoma / fluid collection",
|
| 181 |
+
"Mediastinum & Hila_others",
|
| 182 |
+
"Cardiomegaly",
|
| 183 |
+
"Pericardial effusion",
|
| 184 |
+
"Pericardial thickening / calcification",
|
| 185 |
+
"Coronary artery calcification",
|
| 186 |
+
"Coronary stent or bypass graft",
|
| 187 |
+
"Thoracic aortic calcification",
|
| 188 |
+
"Thoracic aortic ectasia / dilation (non-aneurysmal)",
|
| 189 |
+
"Thoracic aortic aneurysm",
|
| 190 |
+
"Aortic dissection / intramural hematoma",
|
| 191 |
+
"Main pulmonary artery enlargement",
|
| 192 |
+
"Pulmonary embolism",
|
| 193 |
+
"Aortic valve calcification",
|
| 194 |
+
"Mitral annular calcification",
|
| 195 |
+
"Pacemaker / ICD leads",
|
| 196 |
+
"Central venous catheter / PICC",
|
| 197 |
+
"LVAD / other cardiac assist device",
|
| 198 |
+
"Cardiovascular_others",
|
| 199 |
+
"Chest wall soft tissue edema / hematoma",
|
| 200 |
+
"Subcutaneous emphysema",
|
| 201 |
+
"Chest wall mass",
|
| 202 |
+
"Post-thoracotomy change",
|
| 203 |
+
"Chest wall tumor invasion",
|
| 204 |
+
"Chest Wall_others",
|
| 205 |
+
"Acute rib fracture",
|
| 206 |
+
"Non-acute / healed rib fracture",
|
| 207 |
+
"Sternal fracture",
|
| 208 |
+
"Vertebral compression fracture",
|
| 209 |
+
"Degenerative spine changes",
|
| 210 |
+
"Osteolytic bone lesion",
|
| 211 |
+
"Osteosclerotic bone lesion",
|
| 212 |
+
"Mixed osteolytic-osteosclerotic lesion",
|
| 213 |
+
"Osteopenia",
|
| 214 |
+
"Scoliosis / kyphosis",
|
| 215 |
+
"Vertebral hemangioma",
|
| 216 |
+
"Postoperative spine change / hardware",
|
| 217 |
+
"Bones / Spine_others",
|
| 218 |
+
"Hepatic steatosis",
|
| 219 |
+
"Focal liver lesion (nodule / mass)",
|
| 220 |
+
"Hepatomegaly",
|
| 221 |
+
"Liver contour irregularity / cirrhosis features",
|
| 222 |
+
"Hepatic calcification",
|
| 223 |
+
"Cholelithiasis / gallstones",
|
| 224 |
+
"Post-cholecystectomy (gallbladder operated / absent)",
|
| 225 |
+
"Gallbladder wall thickening",
|
| 226 |
+
"Hydropic gallbladder / distension",
|
| 227 |
+
"Biliary sludge",
|
| 228 |
+
"Biliary stent / catheter / drain",
|
| 229 |
+
"Splenomegaly",
|
| 230 |
+
"Accessory spleen / splenule / polysplenia",
|
| 231 |
+
"Focal splenic lesion (nodule / mass)",
|
| 232 |
+
"Pancreatic mass / focal lesion",
|
| 233 |
+
"Pancreatic lipomatosis",
|
| 234 |
+
"Adrenal nodule / mass",
|
| 235 |
+
"Adrenal thickening / hyperplasia",
|
| 236 |
+
"Adrenal calcification",
|
| 237 |
+
"Simple renal cyst",
|
| 238 |
+
"Complex renal cyst / solid renal mass",
|
| 239 |
+
"Hydronephrosis",
|
| 240 |
+
"Renal calculi / nephrolithiasis",
|
| 241 |
+
"Renal atrophy / decreased renal size",
|
| 242 |
+
"Nephrectomy (kidney absent / operated)",
|
| 243 |
+
"Ascites",
|
| 244 |
+
"Pneumoperitoneum",
|
| 245 |
+
"Bowel wall thickening / inflammation",
|
| 246 |
+
"Diverticulosis",
|
| 247 |
+
"Omental caking / peritoneal carcinomatosis",
|
| 248 |
+
"Abdominal lymphadenopathy",
|
| 249 |
+
"Abdominal aortic aneurysm (partially imaged)",
|
| 250 |
+
"Abdominal aortic calcification / atherosclerosis (partially imaged)",
|
| 251 |
+
"IVC filter",
|
| 252 |
+
"Upper Abdomen_others",
|
| 253 |
+
"Thyroid enlargement (goiter)",
|
| 254 |
+
"Thyroid nodule",
|
| 255 |
+
"Cervical / supraclavicular lymphadenopathy",
|
| 256 |
+
"Neck soft tissue mass",
|
| 257 |
+
"Lower Neck_others",
|
| 258 |
+
"Breast mass / focal asymmetry",
|
| 259 |
+
"Post-lumpectomy / post-mastectomy change",
|
| 260 |
+
"Breast implant (intact or present)",
|
| 261 |
+
"Axillary lymphadenopathy",
|
| 262 |
+
"Motion artifact / suboptimal study",
|
| 263 |
+
"Study limitation / limited evaluation (non-motion)",
|
| 264 |
+
"No significant intrathoracic abnormality",
|
| 265 |
+
"Others_others"
|
| 266 |
+
],
|
| 267 |
+
"instruction": "Given the following chest CT report, extract the presence/absence of entities",
|
| 268 |
+
"max_len": 512,
|
| 269 |
+
"default_threshold": 0.5,
|
| 270 |
+
"torch_dtype": "float32",
|
| 271 |
+
"n_labels": 137,
|
| 272 |
+
"attn_implementation": "sdpa"
|
| 273 |
+
}
|
merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b779d82e66bc2e765627ea32c160e401bfce2cebcf986e80f7fdf3e53c6934b8
|
| 3 |
+
size 2384826596
|
modeling_chest2vec_labeler.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Chest2Vec CT Report Labeler — HuggingFace `AutoModel` wrapper.
|
| 3 |
+
|
| 4 |
+
A weakly-supervised multi-label classifier that maps a free-text chest-CT report to a
|
| 5 |
+
137-leaf chest-imaging taxonomy with a ternary status per label
|
| 6 |
+
(negative / uncertain / positive).
|
| 7 |
+
|
| 8 |
+
Architecture: `Qwen/Qwen3-Embedding-0.6B` encoder (LoRA merged in) → left-padding-aware
|
| 9 |
+
last-token (EOS) pooling → L2-normalization → a single linear ternary head
|
| 10 |
+
(`hidden=1024 → 137 × 3`).
|
| 11 |
+
|
| 12 |
+
Usage:
|
| 13 |
+
|
| 14 |
+
from transformers import AutoModel, AutoTokenizer
|
| 15 |
+
model = AutoModel.from_pretrained("chest2vec/chest2vec_labeler", trust_remote_code=True).eval()
|
| 16 |
+
tok = AutoTokenizer.from_pretrained("chest2vec/chest2vec_labeler", trust_remote_code=True)
|
| 17 |
+
|
| 18 |
+
reports = ["Bibasilar atelectasis with small bilateral pleural effusions. Cardiomegaly."]
|
| 19 |
+
print(model.label_reports(reports, tokenizer=tok)) # -> [{'Pleural effusion': 'positive', ...}]
|
| 20 |
+
|
| 21 |
+
# CheXbert / SRR-BERT-style report comparison (label both, compare):
|
| 22 |
+
res = model.score_reports(gt_reports, pred_reports, tokenizer=tok)
|
| 23 |
+
print(res["micro"]["f1"], res["macro"]["f1"], res["weighted"]["f1"])
|
| 24 |
+
"""
|
| 25 |
+
from typing import Dict, List, Optional, Any
|
| 26 |
+
import torch
|
| 27 |
+
import torch.nn as nn
|
| 28 |
+
import torch.nn.functional as F
|
| 29 |
+
from transformers import PreTrainedModel, PretrainedConfig, AutoConfig, AutoModel
|
| 30 |
+
from transformers.modeling_outputs import ModelOutput
|
| 31 |
+
from dataclasses import dataclass
|
| 32 |
+
|
| 33 |
+
# class index ordering produced by the head's softmax (axis=-1)
|
| 34 |
+
NEGATIVE, UNCERTAIN, POSITIVE = 0, 1, 2
|
| 35 |
+
_CLASS_TO_VALUE = {NEGATIVE: 0, UNCERTAIN: -1, POSITIVE: 1}
|
| 36 |
+
_CLASS_TO_NAME = {NEGATIVE: "negative", UNCERTAIN: "uncertain", POSITIVE: "positive"}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class Chest2VecLabelerConfig(PretrainedConfig):
|
| 40 |
+
model_type = "chest2vec_labeler"
|
| 41 |
+
|
| 42 |
+
def __init__(
|
| 43 |
+
self,
|
| 44 |
+
encoder_config: Optional[dict] = None,
|
| 45 |
+
base_model: str = "Qwen/Qwen3-Embedding-0.6B",
|
| 46 |
+
hidden_size: int = 1024,
|
| 47 |
+
n_labels: int = 137,
|
| 48 |
+
num_classes_per_label: int = 3,
|
| 49 |
+
labels: Optional[List[str]] = None,
|
| 50 |
+
instruction: str = "Given the following chest CT report, extract the presence/absence of entities",
|
| 51 |
+
max_len: int = 512,
|
| 52 |
+
default_threshold: float = 0.5,
|
| 53 |
+
**kwargs,
|
| 54 |
+
):
|
| 55 |
+
super().__init__(**kwargs)
|
| 56 |
+
self.encoder_config = encoder_config or {}
|
| 57 |
+
self.base_model = base_model
|
| 58 |
+
self.hidden_size = hidden_size
|
| 59 |
+
self.n_labels = n_labels
|
| 60 |
+
self.num_classes_per_label = num_classes_per_label
|
| 61 |
+
self.labels = labels or []
|
| 62 |
+
self.instruction = instruction
|
| 63 |
+
self.max_len = max_len
|
| 64 |
+
self.default_threshold = default_threshold
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@dataclass
|
| 68 |
+
class LabelerOutput(ModelOutput):
|
| 69 |
+
logits: torch.FloatTensor = None # [B, num_labels, 3]
|
| 70 |
+
embedding: torch.FloatTensor = None # [B, hidden] L2-normalized pooled
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _build_encoder(encoder_config: dict, attn_implementation: str = "sdpa"):
|
| 74 |
+
ecfg = dict(encoder_config)
|
| 75 |
+
for k in ("architectures", "auto_map", "transformers_version", "_name_or_path", "torch_dtype"):
|
| 76 |
+
ecfg.pop(k, None)
|
| 77 |
+
model_type = ecfg.pop("model_type", "qwen3")
|
| 78 |
+
cfg = AutoConfig.for_model(model_type, **ecfg)
|
| 79 |
+
cfg.torch_dtype = "float32"
|
| 80 |
+
try:
|
| 81 |
+
cfg._attn_implementation = attn_implementation
|
| 82 |
+
except Exception:
|
| 83 |
+
pass
|
| 84 |
+
try:
|
| 85 |
+
return AutoModel.from_config(cfg, attn_implementation=attn_implementation)
|
| 86 |
+
except TypeError:
|
| 87 |
+
return AutoModel.from_config(cfg)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _last_token_pool(last_hidden_states: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
|
| 91 |
+
"""Left-padding-aware last-token (EOS) pooling — matches the training pipeline."""
|
| 92 |
+
left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])
|
| 93 |
+
if left_padding:
|
| 94 |
+
return last_hidden_states[:, -1]
|
| 95 |
+
idx = attention_mask.sum(dim=1) - 1
|
| 96 |
+
return last_hidden_states[torch.arange(last_hidden_states.size(0), device=last_hidden_states.device), idx]
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class Chest2VecLabelerModel(PreTrainedModel):
|
| 100 |
+
config_class = Chest2VecLabelerConfig
|
| 101 |
+
base_model_prefix = "model"
|
| 102 |
+
|
| 103 |
+
def __init__(self, config: Chest2VecLabelerConfig):
|
| 104 |
+
super().__init__(config)
|
| 105 |
+
self.model = _build_encoder(config.encoder_config, getattr(config, "attn_implementation", "sdpa"))
|
| 106 |
+
self.head = nn.Linear(config.hidden_size, config.n_labels * config.num_classes_per_label)
|
| 107 |
+
self.num_labels = config.n_labels
|
| 108 |
+
self.num_classes_per_label = config.num_classes_per_label
|
| 109 |
+
self._tokenizer = None
|
| 110 |
+
self.post_init()
|
| 111 |
+
|
| 112 |
+
# ---- core forward (token tensors in, logits out) ----
|
| 113 |
+
def forward(self, input_ids=None, attention_mask=None, position_ids=None, **kwargs):
|
| 114 |
+
if position_ids is None and attention_mask is not None:
|
| 115 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 116 |
+
position_ids.masked_fill_(attention_mask == 0, 0)
|
| 117 |
+
out = self.model(input_ids=input_ids, attention_mask=attention_mask,
|
| 118 |
+
position_ids=position_ids, use_cache=False, return_dict=True)
|
| 119 |
+
h = out.last_hidden_state if hasattr(out, "last_hidden_state") else out.hidden_states[-1]
|
| 120 |
+
emb = _last_token_pool(h, attention_mask)
|
| 121 |
+
emb = F.normalize(emb.float(), p=2, dim=-1)
|
| 122 |
+
logits = self.head(emb).view(emb.size(0), self.num_labels, self.num_classes_per_label)
|
| 123 |
+
return LabelerOutput(logits=logits, embedding=emb)
|
| 124 |
+
|
| 125 |
+
# ---- tokenization (matches training: Instruct/Query + reserved EOS + left pad) ----
|
| 126 |
+
def _get_tokenizer(self, tokenizer=None):
|
| 127 |
+
if tokenizer is not None:
|
| 128 |
+
return tokenizer
|
| 129 |
+
if self._tokenizer is None:
|
| 130 |
+
from transformers import AutoTokenizer
|
| 131 |
+
src = self.config._name_or_path or self.config.base_model
|
| 132 |
+
self._tokenizer = AutoTokenizer.from_pretrained(src, padding_side="left", trust_remote_code=True)
|
| 133 |
+
if self._tokenizer.pad_token_id is None:
|
| 134 |
+
self._tokenizer.pad_token = self._tokenizer.eos_token
|
| 135 |
+
return self._tokenizer
|
| 136 |
+
|
| 137 |
+
def _encode(self, tok, reports: List[str], max_len: int):
|
| 138 |
+
instr = self.config.instruction.strip()
|
| 139 |
+
texts = [(f"Instruct: {instr}\nQuery: {str(r).strip()}" if instr else str(r).strip()) for r in reports]
|
| 140 |
+
pad_id = tok.pad_token_id if tok.pad_token_id is not None else tok.eos_token_id
|
| 141 |
+
eod_id = tok.convert_tokens_to_ids("<|endoftext|>")
|
| 142 |
+
if eod_id is None or eod_id < 0:
|
| 143 |
+
eod_id = pad_id
|
| 144 |
+
enc = tok(texts, add_special_tokens=False, truncation=True, max_length=max_len - 1,
|
| 145 |
+
padding=False, return_attention_mask=False)
|
| 146 |
+
ids = [x + [eod_id] for x in enc["input_ids"]]
|
| 147 |
+
T = max((len(x) for x in ids), default=1)
|
| 148 |
+
input_ids = [[pad_id] * (T - len(x)) + x for x in ids]
|
| 149 |
+
attn = [[0] * (T - len(x)) + [1] * len(x) for x in ids]
|
| 150 |
+
return (torch.tensor(input_ids, dtype=torch.long), torch.tensor(attn, dtype=torch.long))
|
| 151 |
+
|
| 152 |
+
# ---- high-level prediction API ----
|
| 153 |
+
@torch.no_grad()
|
| 154 |
+
def predict_proba(self, reports: List[str], tokenizer=None, batch_size: int = 16,
|
| 155 |
+
max_len: Optional[int] = None, device=None) -> torch.Tensor:
|
| 156 |
+
"""Return [N, num_labels] probability of the POSITIVE class for each label."""
|
| 157 |
+
if isinstance(reports, str):
|
| 158 |
+
reports = [reports]
|
| 159 |
+
tok = self._get_tokenizer(tokenizer)
|
| 160 |
+
max_len = max_len or self.config.max_len
|
| 161 |
+
device = device or next(self.parameters()).device
|
| 162 |
+
self.eval()
|
| 163 |
+
out = []
|
| 164 |
+
for i in range(0, len(reports), batch_size):
|
| 165 |
+
ii, am = self._encode(tok, reports[i:i + batch_size], max_len)
|
| 166 |
+
logits = self(input_ids=ii.to(device), attention_mask=am.to(device)).logits
|
| 167 |
+
out.append(torch.softmax(logits.float(), dim=-1)[:, :, POSITIVE].cpu())
|
| 168 |
+
return torch.cat(out, dim=0)
|
| 169 |
+
|
| 170 |
+
@torch.no_grad()
|
| 171 |
+
def predict(self, reports: List[str], tokenizer=None, threshold: Optional[float] = None,
|
| 172 |
+
batch_size: int = 16, max_len: Optional[int] = None, device=None,
|
| 173 |
+
return_ternary: bool = False) -> Dict[str, Any]:
|
| 174 |
+
"""Return {'labels': names, 'positive': [N,L] 0/1, 'proba': [N,L], ('ternary': [N,L] in {-1,0,1})}."""
|
| 175 |
+
if isinstance(reports, str):
|
| 176 |
+
reports = [reports]
|
| 177 |
+
thr = self.config.default_threshold if threshold is None else threshold
|
| 178 |
+
tok = self._get_tokenizer(tokenizer)
|
| 179 |
+
max_len = max_len or self.config.max_len
|
| 180 |
+
device = device or next(self.parameters()).device
|
| 181 |
+
self.eval()
|
| 182 |
+
proba, ternary = [], []
|
| 183 |
+
for i in range(0, len(reports), batch_size):
|
| 184 |
+
ii, am = self._encode(tok, reports[i:i + batch_size], max_len)
|
| 185 |
+
logits = self(input_ids=ii.to(device), attention_mask=am.to(device)).logits.float().cpu()
|
| 186 |
+
proba.append(torch.softmax(logits, dim=-1)[:, :, POSITIVE])
|
| 187 |
+
if return_ternary:
|
| 188 |
+
cls = logits.argmax(-1)
|
| 189 |
+
ternary.append(torch.tensor([[_CLASS_TO_VALUE[int(c)] for c in row] for row in cls]))
|
| 190 |
+
proba = torch.cat(proba, dim=0)
|
| 191 |
+
res = {"labels": list(self.config.labels), "proba": proba.numpy(),
|
| 192 |
+
"positive": (proba >= thr).int().numpy(), "threshold": thr}
|
| 193 |
+
if return_ternary:
|
| 194 |
+
res["ternary"] = torch.cat(ternary, dim=0).numpy()
|
| 195 |
+
return res
|
| 196 |
+
|
| 197 |
+
def label_reports(self, reports: List[str], tokenizer=None, threshold: Optional[float] = None,
|
| 198 |
+
**kw) -> List[Dict[str, str]]:
|
| 199 |
+
"""Return, per report, a dict {label_name: 'positive'} for labels above threshold."""
|
| 200 |
+
out = self.predict(reports, tokenizer=tokenizer, threshold=threshold, **kw)
|
| 201 |
+
names = out["labels"]
|
| 202 |
+
return [{names[j]: "positive" for j in range(len(names)) if row[j]} for row in out["positive"]]
|
| 203 |
+
|
| 204 |
+
# ---- CheXbert / SRR-BERT-style report-comparison F1 ----
|
| 205 |
+
@torch.no_grad()
|
| 206 |
+
def score_reports(self, gt_reports: List[str], pred_reports: List[str], tokenizer=None,
|
| 207 |
+
threshold: Optional[float] = None, batch_size: int = 16,
|
| 208 |
+
max_len: Optional[int] = None, device=None) -> Dict[str, Any]:
|
| 209 |
+
"""
|
| 210 |
+
Label both GT and predicted reports, then compute label-level F1 (CheXbert-style).
|
| 211 |
+
|
| 212 |
+
Treats the labels extracted from `gt_reports` as ground truth and those from
|
| 213 |
+
`pred_reports` as the prediction. Returns micro / macro / weighted P,R,F1 over the
|
| 214 |
+
137 labels, plus per-label scores.
|
| 215 |
+
"""
|
| 216 |
+
from sklearn.metrics import precision_recall_fscore_support
|
| 217 |
+
if len(gt_reports) != len(pred_reports):
|
| 218 |
+
raise ValueError("gt_reports and pred_reports must have the same length")
|
| 219 |
+
kw = dict(tokenizer=tokenizer, threshold=threshold, batch_size=batch_size, max_len=max_len, device=device)
|
| 220 |
+
y_true = self.predict(gt_reports, **kw)["positive"]
|
| 221 |
+
y_pred = self.predict(pred_reports, **kw)["positive"]
|
| 222 |
+
names = list(self.config.labels)
|
| 223 |
+
|
| 224 |
+
res: Dict[str, Any] = {"n_reports": len(gt_reports),
|
| 225 |
+
"threshold": self.config.default_threshold if threshold is None else threshold}
|
| 226 |
+
for avg in ("micro", "macro", "weighted"):
|
| 227 |
+
p, r, f, _ = precision_recall_fscore_support(y_true, y_pred, average=avg, zero_division=0)
|
| 228 |
+
res[avg] = {"precision": float(p), "recall": float(r), "f1": float(f)}
|
| 229 |
+
p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average=None,
|
| 230 |
+
labels=list(range(len(names))), zero_division=0)
|
| 231 |
+
res["per_label"] = {names[j]: {"precision": float(p[j]), "recall": float(r[j]),
|
| 232 |
+
"f1": float(f[j]), "support_gt": int(s[j])} for j in range(len(names))}
|
| 233 |
+
return res
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def report_f1(gt_reports: List[str], pred_reports: List[str], model=None, tokenizer=None,
|
| 237 |
+
model_id: str = "chest2vec/chest2vec_labeler", **kw) -> Dict[str, Any]:
|
| 238 |
+
"""Convenience wrapper: load the labeler (if not supplied) and score GT vs predicted reports."""
|
| 239 |
+
if model is None:
|
| 240 |
+
model = Chest2VecLabelerModel.from_pretrained(model_id).eval()
|
| 241 |
+
return model.score_reports(gt_reports, pred_reports, tokenizer=tokenizer, **kw)
|
tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:def76fb086971c7867b829c23a26261e38d9d74e02139253b38aeb9df8b4b50a
|
| 3 |
+
size 11423705
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_bos_token": false,
|
| 3 |
+
"add_prefix_space": false,
|
| 4 |
+
"added_tokens_decoder": {
|
| 5 |
+
"151643": {
|
| 6 |
+
"content": "<|endoftext|>",
|
| 7 |
+
"lstrip": false,
|
| 8 |
+
"normalized": false,
|
| 9 |
+
"rstrip": false,
|
| 10 |
+
"single_word": false,
|
| 11 |
+
"special": true
|
| 12 |
+
},
|
| 13 |
+
"151644": {
|
| 14 |
+
"content": "<|im_start|>",
|
| 15 |
+
"lstrip": false,
|
| 16 |
+
"normalized": false,
|
| 17 |
+
"rstrip": false,
|
| 18 |
+
"single_word": false,
|
| 19 |
+
"special": true
|
| 20 |
+
},
|
| 21 |
+
"151645": {
|
| 22 |
+
"content": "<|im_end|>",
|
| 23 |
+
"lstrip": false,
|
| 24 |
+
"normalized": false,
|
| 25 |
+
"rstrip": false,
|
| 26 |
+
"single_word": false,
|
| 27 |
+
"special": true
|
| 28 |
+
},
|
| 29 |
+
"151646": {
|
| 30 |
+
"content": "<|object_ref_start|>",
|
| 31 |
+
"lstrip": false,
|
| 32 |
+
"normalized": false,
|
| 33 |
+
"rstrip": false,
|
| 34 |
+
"single_word": false,
|
| 35 |
+
"special": true
|
| 36 |
+
},
|
| 37 |
+
"151647": {
|
| 38 |
+
"content": "<|object_ref_end|>",
|
| 39 |
+
"lstrip": false,
|
| 40 |
+
"normalized": false,
|
| 41 |
+
"rstrip": false,
|
| 42 |
+
"single_word": false,
|
| 43 |
+
"special": true
|
| 44 |
+
},
|
| 45 |
+
"151648": {
|
| 46 |
+
"content": "<|box_start|>",
|
| 47 |
+
"lstrip": false,
|
| 48 |
+
"normalized": false,
|
| 49 |
+
"rstrip": false,
|
| 50 |
+
"single_word": false,
|
| 51 |
+
"special": true
|
| 52 |
+
},
|
| 53 |
+
"151649": {
|
| 54 |
+
"content": "<|box_end|>",
|
| 55 |
+
"lstrip": false,
|
| 56 |
+
"normalized": false,
|
| 57 |
+
"rstrip": false,
|
| 58 |
+
"single_word": false,
|
| 59 |
+
"special": true
|
| 60 |
+
},
|
| 61 |
+
"151650": {
|
| 62 |
+
"content": "<|quad_start|>",
|
| 63 |
+
"lstrip": false,
|
| 64 |
+
"normalized": false,
|
| 65 |
+
"rstrip": false,
|
| 66 |
+
"single_word": false,
|
| 67 |
+
"special": true
|
| 68 |
+
},
|
| 69 |
+
"151651": {
|
| 70 |
+
"content": "<|quad_end|>",
|
| 71 |
+
"lstrip": false,
|
| 72 |
+
"normalized": false,
|
| 73 |
+
"rstrip": false,
|
| 74 |
+
"single_word": false,
|
| 75 |
+
"special": true
|
| 76 |
+
},
|
| 77 |
+
"151652": {
|
| 78 |
+
"content": "<|vision_start|>",
|
| 79 |
+
"lstrip": false,
|
| 80 |
+
"normalized": false,
|
| 81 |
+
"rstrip": false,
|
| 82 |
+
"single_word": false,
|
| 83 |
+
"special": true
|
| 84 |
+
},
|
| 85 |
+
"151653": {
|
| 86 |
+
"content": "<|vision_end|>",
|
| 87 |
+
"lstrip": false,
|
| 88 |
+
"normalized": false,
|
| 89 |
+
"rstrip": false,
|
| 90 |
+
"single_word": false,
|
| 91 |
+
"special": true
|
| 92 |
+
},
|
| 93 |
+
"151654": {
|
| 94 |
+
"content": "<|vision_pad|>",
|
| 95 |
+
"lstrip": false,
|
| 96 |
+
"normalized": false,
|
| 97 |
+
"rstrip": false,
|
| 98 |
+
"single_word": false,
|
| 99 |
+
"special": true
|
| 100 |
+
},
|
| 101 |
+
"151655": {
|
| 102 |
+
"content": "<|image_pad|>",
|
| 103 |
+
"lstrip": false,
|
| 104 |
+
"normalized": false,
|
| 105 |
+
"rstrip": false,
|
| 106 |
+
"single_word": false,
|
| 107 |
+
"special": true
|
| 108 |
+
},
|
| 109 |
+
"151656": {
|
| 110 |
+
"content": "<|video_pad|>",
|
| 111 |
+
"lstrip": false,
|
| 112 |
+
"normalized": false,
|
| 113 |
+
"rstrip": false,
|
| 114 |
+
"single_word": false,
|
| 115 |
+
"special": true
|
| 116 |
+
},
|
| 117 |
+
"151657": {
|
| 118 |
+
"content": "<tool_call>",
|
| 119 |
+
"lstrip": false,
|
| 120 |
+
"normalized": false,
|
| 121 |
+
"rstrip": false,
|
| 122 |
+
"single_word": false,
|
| 123 |
+
"special": false
|
| 124 |
+
},
|
| 125 |
+
"151658": {
|
| 126 |
+
"content": "</tool_call>",
|
| 127 |
+
"lstrip": false,
|
| 128 |
+
"normalized": false,
|
| 129 |
+
"rstrip": false,
|
| 130 |
+
"single_word": false,
|
| 131 |
+
"special": false
|
| 132 |
+
},
|
| 133 |
+
"151659": {
|
| 134 |
+
"content": "<|fim_prefix|>",
|
| 135 |
+
"lstrip": false,
|
| 136 |
+
"normalized": false,
|
| 137 |
+
"rstrip": false,
|
| 138 |
+
"single_word": false,
|
| 139 |
+
"special": false
|
| 140 |
+
},
|
| 141 |
+
"151660": {
|
| 142 |
+
"content": "<|fim_middle|>",
|
| 143 |
+
"lstrip": false,
|
| 144 |
+
"normalized": false,
|
| 145 |
+
"rstrip": false,
|
| 146 |
+
"single_word": false,
|
| 147 |
+
"special": false
|
| 148 |
+
},
|
| 149 |
+
"151661": {
|
| 150 |
+
"content": "<|fim_suffix|>",
|
| 151 |
+
"lstrip": false,
|
| 152 |
+
"normalized": false,
|
| 153 |
+
"rstrip": false,
|
| 154 |
+
"single_word": false,
|
| 155 |
+
"special": false
|
| 156 |
+
},
|
| 157 |
+
"151662": {
|
| 158 |
+
"content": "<|fim_pad|>",
|
| 159 |
+
"lstrip": false,
|
| 160 |
+
"normalized": false,
|
| 161 |
+
"rstrip": false,
|
| 162 |
+
"single_word": false,
|
| 163 |
+
"special": false
|
| 164 |
+
},
|
| 165 |
+
"151663": {
|
| 166 |
+
"content": "<|repo_name|>",
|
| 167 |
+
"lstrip": false,
|
| 168 |
+
"normalized": false,
|
| 169 |
+
"rstrip": false,
|
| 170 |
+
"single_word": false,
|
| 171 |
+
"special": false
|
| 172 |
+
},
|
| 173 |
+
"151664": {
|
| 174 |
+
"content": "<|file_sep|>",
|
| 175 |
+
"lstrip": false,
|
| 176 |
+
"normalized": false,
|
| 177 |
+
"rstrip": false,
|
| 178 |
+
"single_word": false,
|
| 179 |
+
"special": false
|
| 180 |
+
},
|
| 181 |
+
"151665": {
|
| 182 |
+
"content": "<tool_response>",
|
| 183 |
+
"lstrip": false,
|
| 184 |
+
"normalized": false,
|
| 185 |
+
"rstrip": false,
|
| 186 |
+
"single_word": false,
|
| 187 |
+
"special": false
|
| 188 |
+
},
|
| 189 |
+
"151666": {
|
| 190 |
+
"content": "</tool_response>",
|
| 191 |
+
"lstrip": false,
|
| 192 |
+
"normalized": false,
|
| 193 |
+
"rstrip": false,
|
| 194 |
+
"single_word": false,
|
| 195 |
+
"special": false
|
| 196 |
+
},
|
| 197 |
+
"151667": {
|
| 198 |
+
"content": "<think>",
|
| 199 |
+
"lstrip": false,
|
| 200 |
+
"normalized": false,
|
| 201 |
+
"rstrip": false,
|
| 202 |
+
"single_word": false,
|
| 203 |
+
"special": false
|
| 204 |
+
},
|
| 205 |
+
"151668": {
|
| 206 |
+
"content": "</think>",
|
| 207 |
+
"lstrip": false,
|
| 208 |
+
"normalized": false,
|
| 209 |
+
"rstrip": false,
|
| 210 |
+
"single_word": false,
|
| 211 |
+
"special": false
|
| 212 |
+
}
|
| 213 |
+
},
|
| 214 |
+
"additional_special_tokens": [
|
| 215 |
+
"<|im_start|>",
|
| 216 |
+
"<|im_end|>",
|
| 217 |
+
"<|object_ref_start|>",
|
| 218 |
+
"<|object_ref_end|>",
|
| 219 |
+
"<|box_start|>",
|
| 220 |
+
"<|box_end|>",
|
| 221 |
+
"<|quad_start|>",
|
| 222 |
+
"<|quad_end|>",
|
| 223 |
+
"<|vision_start|>",
|
| 224 |
+
"<|vision_end|>",
|
| 225 |
+
"<|vision_pad|>",
|
| 226 |
+
"<|image_pad|>",
|
| 227 |
+
"<|video_pad|>"
|
| 228 |
+
],
|
| 229 |
+
"bos_token": null,
|
| 230 |
+
"chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].role == 'system' %}\n {{- messages[0].content + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0].role == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0].content + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set content = message.content %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is defined and message.reasoning_content is not none %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- else %}\n {%- if '</think>' in message.content %}\n {%- set content = message.content.split('</think>')[-1].lstrip('\\n') %}\n {%- set reasoning_content = message.content.split('</think>')[0].rstrip('\\n').split('<think>')[-1].lstrip('\\n') %}\n {%- endif %}\n {%- endif %}\n {%- if loop.index0 > ns.last_query_index %}\n {%- if loop.last or (not loop.last and reasoning_content) %}\n {{- '<|im_start|>' + message.role + '\\n<think>\\n' + reasoning_content.strip('\\n') + '\\n</think>\\n\\n' + content.lstrip('\\n') }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- if (loop.first and content) or (not loop.first) %}\n {{- '\\n' }}\n {%- endif %}\n {%- if tool_call.function %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {%- if tool_call.arguments is string %}\n {{- tool_call.arguments }}\n {%- else %}\n {{- tool_call.arguments | tojson }}\n {%- endif %}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '<think>\\n\\n</think>\\n\\n' }}\n {%- endif %}\n{%- endif %}",
|
| 231 |
+
"clean_up_tokenization_spaces": false,
|
| 232 |
+
"eos_token": "<|im_end|>",
|
| 233 |
+
"errors": "replace",
|
| 234 |
+
"extra_special_tokens": {},
|
| 235 |
+
"model_max_length": 131072,
|
| 236 |
+
"pad_token": "<|endoftext|>",
|
| 237 |
+
"split_special_tokens": false,
|
| 238 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
| 239 |
+
"unk_token": null
|
| 240 |
+
}
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|