bengid commited on
Commit
3bb7156
Β·
verified Β·
1 Parent(s): 822cf75

Upload README.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. README.md +44 -43
README.md CHANGED
@@ -23,9 +23,9 @@ model-index:
23
  split: validation
24
  metrics:
25
  - type: accuracy
26
- value: 0.9796
27
  - type: f1
28
- value: 0.9658
29
  - task:
30
  type: image-classification
31
  dataset:
@@ -34,18 +34,18 @@ model-index:
34
  split: test
35
  metrics:
36
  - type: accuracy
37
- value: 0.9796
38
  - type: f1
39
- value: 0.9637
40
  ---
41
 
42
  # ViT-B/16 Flower Classifier
43
 
44
- Fine-tuned [`torchvision.models.vit_b_16`](https://docs.pytorch.org/vision/main/models/vision_transformer.html) (ImageNet-1K pretrained) for 102-class flower classification on the Oxford-102 Flowers dataset, with the full backbone unfrozen during fine-tuning. Achieves **0.9796 accuracy / 0.9637 macro-F1** on a held-out test split.
45
 
46
- > **Note:** earlier versions of this card reported 1.0 accuracy / 1.0 F1. Those numbers were produced by a data leak in the training pipeline's split logic and have been corrected β€” see [Metrics correction](#metrics-correction--earlier-scores-were-invalid) below. The weights are unaffected; only the measurement was.
47
 
48
- **Recommended when** accuracy is the priority and the extra size/latency budget is acceptable β€” e.g. offline batch labeling, research baselines, or any deployment where a ~344MB model and ~87ms mean inference isn't a constraint. For latency- or memory-constrained serving, see [EfficientNetV2-S Flower Classifier](efficientnetv2-s-readme.md), which gives up ~2.7pp of test F1 for ~4x less size and ~3x less latency.
49
 
50
  ## Usage
51
 
@@ -62,9 +62,10 @@ model.heads[-1] = torch.nn.Linear(model.heads[-1].in_features, 102)
62
  model.load_state_dict(load_file(weights_path, device="cpu"))
63
  model.eval()
64
 
65
- # preprocessing: resize(256) -> center-crop(224) -> normalize with dataset mean/std
 
66
  # see src/utils.py:get_transforms() in the training repo for the exact pipeline
67
- #(https://github.com/ben-gid/flowers/blob/main/src/utils.py)
68
  ```
69
 
70
  ## Training Data
@@ -75,23 +76,25 @@ model.eval()
75
 
76
  Single-stage fine-tune with a **two-phase backbone unfreeze** callback (`BackboneFinetuning`): the ViT backbone starts frozen (only the classification head trains), then unfreezes at a fixed epoch with its own, lower learning rate and a separate parameter group β€” unlike this project's original (v1) EfficientNet-B0 model, which only ever unfroze its *last 3 backbone blocks*.
77
 
 
 
78
  ### Hyperparameters
79
 
80
  | Parameter | Value |
81
  |---|---|
82
  | Optimizer | AdamW |
83
  | LR scheduler | Cosine annealing (T_max=50, eta_min=1e-06) |
84
- | Head LR (before unfreeze) | 1e-3 |
85
- | Head LR (after unfreeze) | 1e-3 |
86
- | Backbone LR (after unfreeze) | 1e-5 |
87
  | Unfreeze epoch | 5 |
88
  | Max epochs | 50 |
89
  | Batch size | 64 |
90
  | Effective batch size | 256 |
91
  | Gradient accumulation | 4 |
92
- | Precision | 16-mixed |
93
  | Weight decay | 0.01 |
94
- | Early stopping patience | 5 |
95
 
96
  ## Evaluation
97
 
@@ -99,25 +102,23 @@ Oxford-102 split 70/15/15 by `random_split(seed=42)` β†’ 5,733 train / 1,228 val
99
 
100
  | Metric | Validation | Test |
101
  |---|---|---|
102
- | **Accuracy** | **0.9796** | **0.9796** |
103
- | **Macro F1** | **0.9658** | **0.9637** |
104
- | Loss | 0.1015 | 0.0973 |
105
-
106
- Val and test accuracy are identical here by coincidence β€” both splits are 1,228 images and the model gets 1,203 right on each. The F1 scores differ, as expected.
107
 
108
  | Property | Value |
109
  |---|---|
110
  | Parameters | 85,877,094 |
111
  | Model size | 343.5 MB |
112
  | Checkpoint size | 1030.7 MB |
113
- | Mean latency | 86.5 ms |
114
- | p95 latency | 104.0 ms |
115
 
116
- Latency measured on ryzen 5600x cpu at batch size 1.
117
 
118
- Macro F1 sits ~1.6pp below accuracy on both splits, which is the signature of uneven per-class performance on a dataset whose class counts range from 40 to 258 images β€” the rare classes are where the misses are. Per-class F1 is computed but not currently exported; see `test_per_class_f1` in `src/classifier.py`.
119
 
120
- ## Metrics correction β€” earlier scores were invalid
121
 
122
  An earlier version of this card claimed **1.0 accuracy / 1.0 F1**. That was a measurement bug, not a real result. `FlowerDataModule.setup()` in `src/data.py` built all three splits from the same subset:
123
 
@@ -131,39 +132,38 @@ self.test_set = SubsetWithTransform(train_subset, self.transform_test) # bug
131
 
132
  `val_subset` and `test_subset` were built and then discarded. Validation and test scored the model against the exact images it had trained on β€” total leakage, not partial. A ~1.0 score was the expected outcome of memorization and carried no information about generalization.
133
 
134
- **The weights are not contaminated.** Training only ever read `train_subset`, so no held-out image ever reached a gradient. What the bug corrupted was *measurement* β€” and, through it, model selection: `ModelCheckpoint` and `EarlyStopping` were both driven by `val_acc`, which was really train accuracy. This checkpoint was therefore chosen on a signal that couldn't distinguish good epochs from overfit ones, and is unlikely to be the best epoch of its run.
135
 
136
- The split logic is now fixed. The metrics above come from re-scoring this same published checkpoint against genuinely held-out data via `notebooks/reevaluate_published_models.ipynb`.
137
 
138
- **A full retrain on the corrected splits is planned.** Expect these numbers to improve: this is a leak-era checkpoint re-measured honestly, not a model whose training was ever guided by a real validation signal. Early stopping never had a reason to fire at the right time, and no hyperparameter choice in this run was validated against held-out data.
139
 
140
  ## Strengths & Weaknesses
141
 
142
  **Strengths:**
143
- - Best accuracy and macro-F1 of every architecture evaluated for this project (see comparison below) β€” attention-based global context handles flowers that differ mainly in overall shape/arrangement rather than local texture.
 
144
  - Full-backbone fine-tuning lets every ViT layer adapt to the flower domain, avoiding the ceiling that partial-unfreeze approaches hit.
145
- - Holds its lead on the corrected metrics: the ~2.7pp test-F1 margin over EfficientNetV2-S is real, where under the leaked numbers both models looked tied at ~1.0.
146
 
147
  **Weaknesses:**
148
- - Largest and slowest model in the lineup by a wide margin β€” ~4x the parameters and ~3x the mean latency of EfficientNetV2-S, for ~2.7pp of test F1. Whether that trade is worth it depends entirely on your latency budget; for most serving it isn't.
149
- - ViTs are comparatively data-hungry and were historically harder to fine-tune from limited data before full-backbone unfreezing + a long enough schedule (see "Why the earlier models underperformed" below) β€” this model only reaches its ceiling because both were used.
150
- - Not a good fit for edge/mobile or high-throughput serving given its size and latency.
151
- - Selected by a checkpoint callback that was reading a leaked metric (see above), so this is likely not the best epoch this recipe can produce.
152
 
153
  ## Limitations
154
 
155
  - **Closed-set, single-label**: trained on exactly 102 Oxford flower species; will confidently misclassify any other flower species, non-flower image, or multi-flower image into one of the 102 known classes β€” there is no out-of-distribution rejection.
156
- - **Fixed input pipeline**: expects a 224Γ—224 center-cropped, normalized input (resize-then-crop). Unusual aspect ratios or off-center subjects can crop the flower out of frame.
157
  - **No adversarial robustness or calibration guarantees** β€” confidence scores are not calibrated probabilities.
158
  - Reported metrics are on held-out Oxford-102 val/test splits; real-world images (different lighting, backgrounds, camera quality) may perform worse.
159
- - **Macro F1 (~0.964) is the number to trust, not accuracy (~0.980)** β€” Oxford-102 is class-imbalanced (40–258 images per class), and the gap between the two means errors concentrate in rare classes. If your use case cares about the long tail, budget for the F1 figure.
160
- - This checkpoint predates the split fix and was selected on a leaked validation signal β€” a retrain is planned (see [Metrics correction](#metrics-correction--earlier-scores-were-invalid)).
161
 
162
  ## Intended Use
163
 
164
  **Intended uses:**
165
  - Flower species identification within the 102 Oxford-102 classes (gardening/botany apps, educational tools, dataset labeling).
166
- - Backend model for this project's v2 `/classify` API endpoint when accuracy is prioritized over latency.
167
 
168
  **Out-of-scope uses:**
169
  - General-purpose plant, object, or scene classification outside the 102 trained species.
@@ -172,24 +172,25 @@ The split logic is now fixed. The metrics above come from re-scoring this same p
172
 
173
  ## Model Comparison
174
 
175
- This project trained four models in total, in this order. All figures are **test-split** accuracy on held-out data:
176
 
177
  | Model | Test Acc | Test F1 | Params | Size (MB) | Best For |
178
  |---|---|---|---|---|---|
179
  | [SimpleCNN (scratch)](https://huggingface.co/bengid/flower-classifier/blob/main/flower_model_weights.pth) | ~0.63 | - | - | - | historical baseline only |
180
  | [EfficientNet-B0 (v1, partial unfreeze)](https://huggingface.co/bengid/flower-classifier/blob/main/ft_EfficientNet-B0.pth) | >0.93 | - | - | - | historical baseline only |
181
- | [EfficientNetV2-S](https://huggingface.co/bengid/efficientnetv2-s-flower-classifier) | 0.9642 | 0.9364 | 20,308,150 | 81.8 | efficient production serving |
182
- | **ViT-B/16 (this model)** | **0.9796** | **0.9637** | 85,877,094 | 343.5 | maximum accuracy |
 
183
 
184
- The two v1 models were trained by the older, pre-Lightning pipeline (`api/app/v1/flowers/train_scratch.py`), which split train/val/test correctly β€” their numbers were never affected by the leak and are directly comparable to the corrected v2 figures above.
185
 
186
  ### Why the earlier models underperformed
187
 
188
  - **SimpleCNN (scratch)** was trained from randomly initialized weights with no ImageNet pretraining, on a 6-block custom CNN β€” too little capacity and too little prior visual knowledge to learn 102 fine-grained flower classes from ~8k images alone.
189
  - **EfficientNet-B0 (v1)** started from ImageNet-pretrained weights but only ever unfroze its *last 3 backbone blocks* during fine-tuning (see this project's root `README.md` for the original two-stage recipe) β€” the earlier backbone layers, tuned for general ImageNet features, never adapted to flower-specific low/mid-level features.
190
- - Both **EfficientNetV2-S** and **ViT-B/16** (this model) unfreeze the *entire* backbone during fine-tuning, which drives the improvement from ~93% to ~96–98% test accuracy.
191
 
192
- Note that this last gain is **~3–5 points, not the ~7 points the leaked metrics implied**. Full-backbone unfreezing is a real improvement over partial unfreezing, but a far more modest one than a jump from 93% to "100%" suggested. The leaked numbers made a good architectural decision look like a spectacular one.
193
 
194
  ## License
195
 
 
23
  split: validation
24
  metrics:
25
  - type: accuracy
26
+ value: 0.9837
27
  - type: f1
28
+ value: 0.9737
29
  - task:
30
  type: image-classification
31
  dataset:
 
34
  split: test
35
  metrics:
36
  - type: accuracy
37
+ value: 0.9837
38
  - type: f1
39
+ value: 0.9722
40
  ---
41
 
42
  # ViT-B/16 Flower Classifier
43
 
44
+ Fine-tuned [`torchvision.models.vit_b_16`](https://docs.pytorch.org/vision/main/models/vision_transformer.html) (ImageNet-1K pretrained) for 102-class flower classification on the Oxford-102 Flowers dataset, with the full backbone unfrozen during fine-tuning. Achieves **0.9837 accuracy / 0.9722 macro-F1** on a held-out test split β€” the best of every architecture evaluated for this project.
45
 
46
+ > **Note:** this card describes a **new checkpoint**, retrained after a data leak in the training pipeline's split logic was fixed. The weights previously published under this repo were leak-era and were selected on a corrupted validation signal β€” see [Training history](#training-history). If you pinned an earlier revision, re-download.
47
 
48
+ **Recommended when** macro-F1 is the priority and the size budget is not binding β€” offline batch labeling, research baselines, or any deployment where 343.5 MB of weights is acceptable. For most serving, [ConvNeXt-Tiny](https://huggingface.co/bengid/convnext-tiny-flower-classifier) is the better trade: it scores 0.9694 macro-F1 against this model's 0.9722, at 111.6 MB instead of 343.5 MB.
49
 
50
  ## Usage
51
 
 
62
  model.load_state_dict(load_file(weights_path, device="cpu"))
63
  model.eval()
64
 
65
+ # preprocessing: Resize((256, 256)) -> CenterCrop(224) -> ToTensor -> Normalize(dataset mean/std)
66
+ # note: the resize is to a fixed 256x256 square, NOT shortest-side-256 -- aspect ratio is not preserved
67
  # see src/utils.py:get_transforms() in the training repo for the exact pipeline
68
+ # (https://github.com/ben-gid/flowers/blob/main/src/utils.py)
69
  ```
70
 
71
  ## Training Data
 
76
 
77
  Single-stage fine-tune with a **two-phase backbone unfreeze** callback (`BackboneFinetuning`): the ViT backbone starts frozen (only the classification head trains), then unfreezes at a fixed epoch with its own, lower learning rate and a separate parameter group β€” unlike this project's original (v1) EfficientNet-B0 model, which only ever unfroze its *last 3 backbone blocks*.
78
 
79
+ Trained under the `corrected-split-retrain` MLflow experiment, i.e. after the split bug described in [Training history](#training-history) was fixed. Checkpoint selection and early stopping were therefore driven by a genuine held-out validation signal.
80
+
81
  ### Hyperparameters
82
 
83
  | Parameter | Value |
84
  |---|---|
85
  | Optimizer | AdamW |
86
  | LR scheduler | Cosine annealing (T_max=50, eta_min=1e-06) |
87
+ | Head LR (before unfreeze) | 0.001 |
88
+ | Head LR (after unfreeze) | 0.0003 |
89
+ | Backbone LR (after unfreeze) | 2e-05 |
90
  | Unfreeze epoch | 5 |
91
  | Max epochs | 50 |
92
  | Batch size | 64 |
93
  | Effective batch size | 256 |
94
  | Gradient accumulation | 4 |
95
+ | Precision | bf16-mixed |
96
  | Weight decay | 0.01 |
97
+ | Early stopping patience | 8 |
98
 
99
  ## Evaluation
100
 
 
102
 
103
  | Metric | Validation | Test |
104
  |---|---|---|
105
+ | **Accuracy** | **0.9837** | **0.9837** |
106
+ | **Macro F1** | **0.9737** | **0.9722** |
107
+ | Loss | 0.0797 | 0.0762 |
 
 
108
 
109
  | Property | Value |
110
  |---|---|
111
  | Parameters | 85,877,094 |
112
  | Model size | 343.5 MB |
113
  | Checkpoint size | 1030.7 MB |
114
+ | Mean latency | 5.39 ms |
115
+ | p95 latency | 5.68 ms |
116
 
117
+ Latency measured on an NVIDIA RTX 5070 (`cuda:0`) at batch size 1, with `torch.cuda.synchronize()` after every forward pass. **These figures do not transfer to CPU.** An earlier CPU benchmark of the same architectures put ViT-B/16 at roughly 3x the latency of the other two, while ConvNeXt-Tiny and EfficientNetV2-S landed within a few milliseconds of each other β€” close enough that two runs of that benchmark disagreed on which was faster. Benchmark on your own serving hardware before treating any of this as a ranking.
118
 
119
+ Macro F1 sits below accuracy on both splits, which is the signature of uneven per-class performance on a dataset whose class counts range from 40 to 258 images β€” the rare classes are where the misses are. This model has the narrowest accuracy-to-F1 spread of the three, though it leads ConvNeXt-Tiny only marginally on that measure. Per-class F1 is computed but not currently exported; see `test_per_class_f1` in `src/classifier.py`.
120
 
121
+ ## Training history
122
 
123
  An earlier version of this card claimed **1.0 accuracy / 1.0 F1**. That was a measurement bug, not a real result. `FlowerDataModule.setup()` in `src/data.py` built all three splits from the same subset:
124
 
 
132
 
133
  `val_subset` and `test_subset` were built and then discarded. Validation and test scored the model against the exact images it had trained on β€” total leakage, not partial. A ~1.0 score was the expected outcome of memorization and carried no information about generalization.
134
 
135
+ **The weights were never contaminated.** Training only ever read `train_subset`, so no held-out image ever reached a gradient. What the bug corrupted was *measurement* β€” and, through it, model selection: `ModelCheckpoint` and `EarlyStopping` were both driven by `val_acc`, which was really train accuracy.
136
 
137
+ **This checkpoint replaces the leak-era one.** It comes from the `corrected-split-retrain` experiment, trained after the fix, so every metric above was measured on genuinely held-out data and the checkpoint was selected on a real validation signal.
138
 
139
+ One finding worth recording: the retrain recovered less than expected. The leak-era ViT checkpoint, re-scored honestly on the same held-out data, reached 0.9637 test macro-F1 against this model's 0.9722. The bug inflated the *reported* numbers substantially; it cost the *weights* comparatively little.
140
 
141
  ## Strengths & Weaknesses
142
 
143
  **Strengths:**
144
+ - Best accuracy and macro-F1 of every architecture evaluated for this project β€” attention-based global context handles flowers that differ mainly in overall shape/arrangement rather than local texture.
145
+ - Narrowest accuracy-to-macro-F1 spread of the three published models, so its errors are the least concentrated in rare classes β€” though it is only marginally ahead of ConvNeXt-Tiny here.
146
  - Full-backbone fine-tuning lets every ViT layer adapt to the flower domain, avoiding the ceiling that partial-unfreeze approaches hit.
 
147
 
148
  **Weaknesses:**
149
+ - Largest model in the lineup by a wide margin β€” 85,877,094 parameters and 343.5 MB of weights, roughly three times ConvNeXt-Tiny, for a macro-F1 margin measured in fractions of a point. For most serving that trade is not worth paying.
150
+ - The accuracy lead over ConvNeXt-Tiny is small enough (0.9722 vs 0.9694) that it is within the range a different seed or a longer schedule could move. Treat it as a lead, not a law.
151
+ - ViTs are comparatively data-hungry and were historically harder to fine-tune from limited data before full-backbone unfreezing plus a long enough schedule β€” this model only reaches its ceiling because both were used.
152
+ - Not a good fit for edge/mobile deployment given its size.
153
 
154
  ## Limitations
155
 
156
  - **Closed-set, single-label**: trained on exactly 102 Oxford flower species; will confidently misclassify any other flower species, non-flower image, or multi-flower image into one of the 102 known classes β€” there is no out-of-distribution rejection.
157
+ - **Fixed input pipeline**: expects a 224Γ—224 input produced by resizing to a fixed 256Γ—256 square and center-cropping. The resize does not preserve aspect ratio, so non-square images are distorted before the crop, and off-center subjects can be cropped out of frame.
158
  - **No adversarial robustness or calibration guarantees** β€” confidence scores are not calibrated probabilities.
159
  - Reported metrics are on held-out Oxford-102 val/test splits; real-world images (different lighting, backgrounds, camera quality) may perform worse.
160
+ - **Macro F1 (0.9722) is the number to trust, not accuracy (0.9837)** β€” Oxford-102 is class-imbalanced (40–258 images per class), and the gap between the two means errors concentrate in rare classes. If your use case cares about the long tail, budget for the F1 figure.
 
161
 
162
  ## Intended Use
163
 
164
  **Intended uses:**
165
  - Flower species identification within the 102 Oxford-102 classes (gardening/botany apps, educational tools, dataset labeling).
166
+ - Backend model for this project's v2 `/classify` API endpoint when macro-F1 is prioritized over model size.
167
 
168
  **Out-of-scope uses:**
169
  - General-purpose plant, object, or scene classification outside the 102 trained species.
 
172
 
173
  ## Model Comparison
174
 
175
+ All figures are **test-split** metrics on held-out data. The three current models were trained on the corrected splits; the two v1 baselines are listed for historical context.
176
 
177
  | Model | Test Acc | Test F1 | Params | Size (MB) | Best For |
178
  |---|---|---|---|---|---|
179
  | [SimpleCNN (scratch)](https://huggingface.co/bengid/flower-classifier/blob/main/flower_model_weights.pth) | ~0.63 | - | - | - | historical baseline only |
180
  | [EfficientNet-B0 (v1, partial unfreeze)](https://huggingface.co/bengid/flower-classifier/blob/main/ft_EfficientNet-B0.pth) | >0.93 | - | - | - | historical baseline only |
181
+ | **[ViT-B/16](https://huggingface.co/bengid/vit-flower-classifier) (this model)** | **0.9837** | **0.9722** | **85,877,094** | **343.5** | maximum macro-F1 |
182
+ | [ConvNeXt-Tiny](https://huggingface.co/bengid/convnext-tiny-flower-classifier) | 0.9821 | 0.9694 | 27,898,566 | 111.6 | default serving choice |
183
+ | [EfficientNetV2-S](https://huggingface.co/bengid/efficientnetv2-s-flower-classifier) | 0.9691 | 0.9433 | 20,308,150 | 81.8 | smallest weights |
184
 
185
+ The two v1 models were trained by the older, pre-Lightning pipeline (`api/app/v1/flowers/train_scratch.py`), which split train/val/test correctly β€” their numbers were never affected by the leak and are directly comparable to the corrected figures above.
186
 
187
  ### Why the earlier models underperformed
188
 
189
  - **SimpleCNN (scratch)** was trained from randomly initialized weights with no ImageNet pretraining, on a 6-block custom CNN β€” too little capacity and too little prior visual knowledge to learn 102 fine-grained flower classes from ~8k images alone.
190
  - **EfficientNet-B0 (v1)** started from ImageNet-pretrained weights but only ever unfroze its *last 3 backbone blocks* during fine-tuning (see this project's root `README.md` for the original two-stage recipe) β€” the earlier backbone layers, tuned for general ImageNet features, never adapted to flower-specific low/mid-level features.
191
+ - All three current models unfreeze the *entire* backbone during fine-tuning, which drives the improvement from ~93% to ~96–98% test accuracy.
192
 
193
+ Note that this gain is **~3–5 points, not the ~7 points the leaked metrics implied**. Full-backbone unfreezing is a real improvement over partial unfreezing, but a far more modest one than a jump from 93% to "100%" suggested.
194
 
195
  ## License
196