Nagizaaz Shaik commited on
Commit
92e1292
·
1 Parent(s): f1f32e4

chore: pin torch_dtype in config

Browse files
.gitattributes DELETED
@@ -1,35 +0,0 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Nagizaaz Shaik
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README.md DELETED
@@ -1,341 +0,0 @@
1
- ---
2
- language: en
3
- license: mit
4
- library_name: transformers
5
- base_model: microsoft/MiniLM-L12-H384-uncased
6
- pipeline_tag: text-classification
7
- tags:
8
- - financial-sentiment
9
- - finance
10
- - sentiment-analysis
11
- - text-classification
12
- - bert
13
- - minilm
14
- datasets:
15
- - takala/financial_phrasebank
16
- - zeroshot/twitter-financial-news-sentiment
17
- - Jean-Baptiste/financial_news_sentiment
18
- metrics:
19
- - accuracy
20
- - f1
21
- model-index:
22
- - name: finbert-minilm-sentiment
23
- results:
24
- - task:
25
- type: text-classification
26
- name: Financial Sentiment Classification
27
- dataset:
28
- name: Financial PhraseBank (Sentences_AllAgree)
29
- type: takala/financial_phrasebank
30
- config: sentences_allagree
31
- metrics:
32
- - type: accuracy
33
- value: 0.9794
34
- name: Test Accuracy
35
- - type: f1
36
- value: 0.9643
37
- name: Test Macro-F1
38
- - task:
39
- type: text-classification
40
- name: Financial Sentiment Classification
41
- dataset:
42
- name: Twitter Financial News Sentiment
43
- type: zeroshot/twitter-financial-news-sentiment
44
- split: validation
45
- metrics:
46
- - type: accuracy
47
- value: 0.8643
48
- name: Validation Accuracy
49
- - type: f1
50
- value: 0.8300
51
- name: Validation Macro-F1
52
- - task:
53
- type: text-classification
54
- name: Financial Sentiment Classification
55
- dataset:
56
- name: SEntFiN headlines (unanimous, test split)
57
- type: tasksource/sentfin
58
- split: test
59
- metrics:
60
- - type: accuracy
61
- value: 0.7599
62
- name: Test Accuracy
63
- - type: f1
64
- value: 0.7627
65
- name: Test Macro-F1
66
- widget:
67
- - text: "The company reported record quarterly profit, beating analyst expectations."
68
- - text: "Net sales decreased by 12% and the firm warned of further losses ahead."
69
- - text: "The board will meet next Tuesday to review the quarterly schedule."
70
- ---
71
-
72
- # finbert-minilm-sentiment
73
-
74
- **A compact financial-sentiment classifier: 33.4M parameters, 97.9% on PhraseBank test, 86.4% on finance tweets.**
75
-
76
- `finbert-minilm-sentiment` classifies financial text into **negative / neutral / positive** sentiment.
77
- It is a compact MiniLM encoder (`microsoft/MiniLM-L12-H384-uncased`, 33.4M parameters)
78
- fine-tuned on a mix of formal financial sentences
79
- ([Financial PhraseBank](https://huggingface.co/datasets/takala/financial_phrasebank)),
80
- finance tweets ([zeroshot/twitter-financial-news-sentiment](https://huggingface.co/datasets/zeroshot/twitter-financial-news-sentiment))
81
- and press-release headlines ([Jean-Baptiste/financial_news_sentiment](https://huggingface.co/datasets/Jean-Baptiste/financial_news_sentiment)).
82
- All numbers below are measured on data held out from training and model selection.
83
-
84
- This is version 3 (October 2026): the same architecture and file format as before, now the
85
- uniform weight average of ten fine-tuning runs, with extra PhraseBank sentences in training.
86
- Earlier weights stay available at git tags:
87
-
88
- - [`v2-mixed-domain`](https://huggingface.co/9mark9/finbert-minilm-sentiment/tree/v2-mixed-domain): one run on the same three sources.
89
- - [`v1-phrasebank-only`](https://huggingface.co/9mark9/finbert-minilm-sentiment/tree/v1-phrasebank-only): PhraseBank only; good in-domain, weak on tweets.
90
-
91
- > **Companion project:** the from-scratch educational transformer (~2M params, no pretrained
92
- > weights, fully annotated) lives at
93
- > [github.com/shaikn6/nano-finbert](https://github.com/shaikn6/nano-finbert).
94
-
95
- ## Results (held-out sets)
96
-
97
- All versions were scored with the same code (`eval_model.py`): max 96 tokens, highest-probability
98
- label. Measured 2026-10-28. Cells are accuracy / macro-F1.
99
-
100
- | Held-out set | n | v1 | v2 | **v3** |
101
- |--------------|---|----|----|--------|
102
- | PhraseBank `Sentences_AllAgree`, stratified 15% test split | 340 | 95.29% / 0.9368 | 96.47% / 0.9532 | **97.94% / 0.9643** |
103
- | Finance tweets, full validation file | 2,388 | 68.22% / 0.6165 | 83.75% / 0.7995 | **86.43% / 0.8300** |
104
- | Press-release headlines (`title` field), full test split | 267 | 71.16% / 0.5864 | 72.28% / 0.5594 | **75.28% / 0.5904** |
105
- | SEntFiN news headlines, full test split, unanimous headlines | 933 | 69.67% / 0.6977 | 73.20% / 0.7361 | **75.99% / 0.7627** |
106
-
107
- Mean macro-F1 over the four sets: v1 0.7093, v2 0.7620, **v3 0.7868** (+2.48 points over v2).
108
-
109
- Label mapping: tweets Bearish = negative, Bullish = positive, Neutral = neutral. Press-release
110
- headlines use the dataset's own class names (0 negative, 1 neutral, 2 positive).
111
- [SEntFiN](https://huggingface.co/datasets/tasksource/sentfin) labels each company or entity in a
112
- headline; only headlines where every entity carries the same label are kept. SEntFiN was never
113
- used for training or model selection.
114
-
115
- 95% intervals (2,000 bootstrap resamples of the rows), v2 vs v3:
116
-
117
- | Set | n | v2 macro-F1 | v3 macro-F1 | v2 negative recall | v3 negative recall |
118
- |-----|---|-------------|-------------|--------------------|--------------------|
119
- | PhraseBank test | 340 | 0.953 (0.921 to 0.978) | 0.964 (0.934 to 0.988) | 0.933 (0.848 to 1.000) | 0.911 (0.816 to 0.979) |
120
- | Tweets | 2,388 | 0.800 (0.781 to 0.817) | 0.830 (0.812 to 0.847) | 0.865 (0.827 to 0.900) | 0.850 (0.810 to 0.886) |
121
- | Press-release headlines | 267 | 0.559 (0.470 to 0.648) | 0.590 (0.485 to 0.695) | 0.167 (0.000 to 0.417) | 0.167 (0.000 to 0.417) |
122
- | SEntFiN headlines | 933 | 0.736 (0.708 to 0.763) | 0.763 (0.735 to 0.790) | 0.757 (0.703 to 0.808) | 0.722 (0.667 to 0.773) |
123
-
124
- The intervals overlap on every set, so treat any single-set gain as uncertain; the consistent
125
- direction across all four sets is the stronger evidence.
126
-
127
- Per-class results, v3 (v2 in brackets):
128
-
129
- | Set | Class | Support | Precision | Recall | F1 |
130
- |-----|-------|---------|-----------|--------|----|
131
- | PhraseBank test | negative | 45 | 0.953 (0.955) | 0.911 (0.933) | 0.932 (0.944) |
132
- | PhraseBank test | neutral | 209 | 1.000 (0.995) | 0.990 (0.971) | 0.995 (0.983) |
133
- | PhraseBank test | positive | 86 | 0.944 (0.902) | 0.988 (0.965) | 0.966 (0.933) |
134
- | Tweets | negative | 347 | 0.725 (0.638) | 0.850 (0.865) | 0.782 (0.734) |
135
- | Tweets | neutral | 1,566 | 0.946 (0.941) | 0.870 (0.837) | 0.906 (0.886) |
136
- | Tweets | positive | 475 | 0.752 (0.741) | 0.857 (0.819) | 0.801 (0.778) |
137
- | Press-release headlines | negative | 12 | 0.667 (0.286) | 0.167 (0.167) | 0.267 (0.211) |
138
- | Press-release headlines | neutral | 156 | 0.764 (0.774) | 0.853 (0.769) | 0.806 (0.772) |
139
- | Press-release headlines | positive | 99 | 0.733 (0.676) | 0.667 (0.717) | 0.698 (0.696) |
140
- | SEntFiN headlines | negative | 259 | 0.850 (0.794) | 0.722 (0.757) | 0.781 (0.775) |
141
- | SEntFiN headlines | neutral | 342 | 0.676 (0.668) | 0.825 (0.754) | 0.743 (0.709) |
142
- | SEntFiN headlines | positive | 332 | 0.811 (0.763) | 0.723 (0.690) | 0.764 (0.725) |
143
-
144
- Reading the tables:
145
-
146
- - v3 is better than v2 on macro-F1 on all four sets. On tweets it labels far fewer neutral or
147
- bullish tweets as negative (negative precision 0.638 to 0.725).
148
- - Where negative F1 rose, it came from precision, not recall. Negative recall is slightly lower on
149
- PhraseBank (0.933 to 0.911), tweets (0.865 to 0.850) and SEntFiN
150
- (0.757 to 0.722): v3 misses a few more negatives and raises fewer false alarms on tweets and SEntFiN.
151
- - Negative press-release headlines are still weak: v3 finds 2 of 12 (v2 found 2). With
152
- 12 negatives that figure is very uncertain. On SEntFiN (259 negative headlines) negative recall
153
- is 0.722, so the problem is mainly with this one set of press releases.
154
- - The datasets define sentiment differently (tweets label market direction, PhraseBank labels
155
- the tone of a reporting sentence), so the numbers are not directly comparable across rows.
156
-
157
- ## Release rule (and one change to it)
158
-
159
- The rule for releasing v3 was set before training: mean macro-F1 over the held-out sets up by at
160
- least 1.5 points, no set down by more than 1.0 point, and **negative-class F1 no worse on any
161
- set**.
162
-
163
- The candidate (chosen on validation slices only, before any held-out score was seen) met the
164
- first two conditions but **failed the third by one sentence**: PhraseBank negative F1 fell from
165
- 0.944 to 0.932 because it found 41 of the 45 negative test sentences and v2 found 42.
166
- It was therefore not released at first.
167
-
168
- **After seeing those held-out results**, the third condition was amended to "negative-class F1
169
- falls by no more than 2.0 points on any set". The reason: on PhraseBank that condition is judged
170
- on 45 negatives, so one sentence decides it, which is far inside the bootstrap noise (the
171
- negative-recall interval spans about 16 points). Changing a rule after seeing test results is a
172
- weaker form of evidence, so the original outcome is stated here. No other candidate was searched
173
- for after the amendment; the same recipe was retrained and the retrained weights re-scored before
174
- release. Before the amendment, one other candidate (a single run, picked on validation with a
175
- negative-F1 filter) was scored on the held-out sets once; it failed (mean +0.87 points) and was
176
- discarded.
177
-
178
- Released weights against v2 (macro-F1 change in points; negative F1):
179
-
180
- | Set | Macro-F1 change | v2 negative F1 | v3 negative F1 | Change (points) |
181
- |-----|-----------------|----------------|----------------|-----------------|
182
- | PhraseBank test | +1.12 | 0.944 | 0.932 | -1.20 |
183
- | Tweets | +3.05 | 0.734 | 0.782 | +4.81 |
184
- | Press-release headlines | +3.09 | 0.211 | 0.267 | +5.61 |
185
- | SEntFiN headlines | +2.67 | 0.775 | 0.781 | +0.61 |
186
-
187
- Mean macro-F1 change +2.48 points. Under the original strict rule these released weights
188
- would still fail (PhraseBank negative F1 0.932 vs 0.944); under the amended rule they pass. The first-pass candidate scored
189
- +2.38 points mean; because Apple-GPU training is not bit-for-bit deterministic, the retrained
190
- weights differ slightly from it, and the numbers in this card are for the released file.
191
-
192
- ## Training data
193
-
194
- Held out and never used for training or model selection: the PhraseBank 15% test split, the full
195
- tweet validation file, the headline test split and all of SEntFiN. Any training text that also
196
- appears in one of these or in a validation slice (17 rows, case-insensitive) was dropped.
197
-
198
- | Source | Used for training | Used for validation |
199
- |--------|-------------------|---------------------|
200
- | PhraseBank `Sentences_AllAgree` | 70% train split (1,584), repeated 3x per epoch | 15% validation split (340) |
201
- | PhraseBank 50% / 66% / 75% agreement files | only sentences not in the all-agree file at all (2,582 / 1,953 / 1,189); majority label; one variant per run | - |
202
- | Tweets, `sent_train.csv` | 90% stratified (8,588) | 10% stratified (955) |
203
- | Headlines, train split | 90% stratified (1,360); repeated 2x in three runs | 10% stratified (152) |
204
-
205
- Because the extra PhraseBank sentences exclude every all-agree sentence, none of the all-agree
206
- test or validation sentences can appear in training. PhraseBank split: stratified 70 / 15 / 15
207
- with scikit-learn `train_test_split(random_state=42)`, test carved first, then validation.
208
- Tweets and headlines: one stratified 90 / 10 split (`random_state=42`) of each training file.
209
-
210
- ## Training details
211
-
212
- | Setting | Value |
213
- |---------|-------|
214
- | Base encoder | `microsoft/MiniLM-L12-H384-uncased` (12 layers, hidden 384) |
215
- | Parameters | 33,361,155 (~33.4M) |
216
- | Objective | class-weighted cross-entropy (inverse class frequency) |
217
- | Optimizer | AdamW, weight decay 0.01, gradient clip 1.0 |
218
- | Schedule | linear, 10% warmup; batch 16; max 96 tokens |
219
- | Epochs | up to 3 (4 for the 2e-5 run); validation twice per epoch, early stopping |
220
- | Checkpoint per run | best mean macro-F1 over the three validation slices |
221
- | Final weights | uniform average of the ten run checkpoints below (same architecture, same file format) |
222
- | Hardware | one laptop (Apple GPU) |
223
-
224
- The ten runs (`train.py` flags):
225
-
226
- | Run | Flags |
227
- |-----|-------|
228
- | 1 | `--lr 3e-5` |
229
- | 2 | `--lr 3e-5 --pb-extra 50Agree` |
230
- | 3 | `--lr 3e-5 --pb-extra 75Agree` |
231
- | 4 | `--lr 3e-5 --pb-extra 66Agree` |
232
- | 5 | `--lr 2e-5 --pb-extra 66Agree --epochs 4 --patience 3` |
233
- | 6 | `--lr 5e-5 --pb-extra 66Agree` |
234
- | 7 | `--lr 3e-5 --pb-extra 66Agree --seed 1` |
235
- | 8 | `--lr 3e-5 --pb-extra 66Agree --jb-rep 2 --seed 2` |
236
- | 9 | `--lr 3e-5 --pb-extra 66Agree --jb-rep 2 --seed 3` |
237
- | 10 | `--lr 5e-5 --pb-extra 66Agree --jb-rep 2 --seed 4` |
238
-
239
- Also tried and not used: label smoothing 0.1, and 8,000 short machine-labelled news snippets from
240
- NOSIBLE/financial-sentiment; neither improved the validation score.
241
-
242
- ## Reproduce
243
-
244
- `train.py`, `common.py`, `eval_model.py` and `average.py` in this repo hold the code;
245
- `requirements-train.txt` lists the package versions. All datasets are downloaded from the Hub at
246
- pinned revisions.
247
-
248
- ```bash
249
- pip install -r requirements-train.txt
250
- python train.py --lr 3e-5 --out run1 # one run, about 10-20 minutes on a laptop GPU
251
- # ... the other nine runs from the table above, each with its own --out
252
- python average.py v3 run1 run2 run3 run4 run5 run6 run7 run8 run9 run10
253
- python eval_model.py v3 - scores.json # all held-out sets, with bootstrap intervals
254
- ```
255
-
256
- Training on an Apple GPU is not bit-for-bit deterministic, so a rerun lands close to, not exactly
257
- on, the published numbers. v2 was trained with an earlier copy of `train.py` that dropped 12
258
- held-out overlaps instead of 17.
259
-
260
- ## Usage
261
-
262
- ```python
263
- import torch
264
- from transformers import AutoModelForSequenceClassification, AutoTokenizer
265
-
266
- model_id = "9mark9/finbert-minilm-sentiment"
267
- tokenizer = AutoTokenizer.from_pretrained(model_id)
268
- model = AutoModelForSequenceClassification.from_pretrained(model_id)
269
- model.eval()
270
-
271
- texts = [
272
- "The company reported record quarterly profit, beating analyst expectations.",
273
- "Net sales decreased by 12% and the firm warned of further losses ahead.",
274
- "The board will meet next Tuesday to review the quarterly schedule.",
275
- ]
276
-
277
- enc = tokenizer(texts, padding=True, truncation=True, max_length=96, return_tensors="pt")
278
- with torch.no_grad():
279
- probs = model(**enc).logits.softmax(-1)
280
-
281
- for text, p in zip(texts, probs):
282
- label = model.config.id2label[int(p.argmax())]
283
- print(f"[{label:8s} {p.max():.2f}] {text}")
284
- ```
285
-
286
- To load an earlier version, pass `revision="v2-mixed-domain"` or `revision="v1-phrasebank-only"`
287
- to both `from_pretrained` calls.
288
-
289
- ## Intended use
290
-
291
- - Sentiment scoring of **short financial text**: news sentences, headlines, finance tweets, analyst notes.
292
- - Research, prototyping and teaching, as a compact CPU-friendly alternative to 110M-parameter FinBERT.
293
-
294
- ## Limitations
295
-
296
- - Overlap found after release: when links and punctuation are also stripped before comparing, 80 of the tweet training rows and 8 of the headline training rows match held-out test text (for example the same headline with a different link). This model was trained on them. Worst case, if all 80 matching tweets were answered correctly only because of that, the tweet accuracy of 86.4% would be about 0.5 points lower (85.96% on the other 2,308 tweets). The newer [finbert-deberta-large-sentiment](https://huggingface.co/9mark9/finbert-deberta-large-sentiment) was trained without those rows.
297
-
298
- - English only. Max sequence length 96 tokens; longer text is truncated.
299
- - Weak on negative press-release headlines (2 of 12 found in that test split). On a larger set of
300
- news headlines (SEntFiN, 259 negatives) negative recall is 0.722.
301
- - On finance tweets about 28% of the tweets it calls negative are labelled neutral or bullish.
302
- - PhraseBank `AllAgree` is the cleanest, easiest part of that benchmark; expect lower accuracy
303
- on ambiguous sentences.
304
- - Tweet labels describe bullish / bearish market direction, which is not the same as the tone of
305
- a sentence. The model mixes both conventions.
306
- - Not financial advice. Outputs are sentiment labels, not buy/sell signals.
307
-
308
- ## Serving & latency
309
-
310
- Full evaluation on the entire `zeroshot/twitter-financial-news-sentiment` validation split (**2,388 rows**, not a sample), plus a serving benchmark with ONNX Runtime and dynamic INT8 quantization. CPU, Apple Silicon, 1 inference thread per request (concurrency comes from workers, not intra-op threads).
311
-
312
- | variant | accuracy | macro-F1 | p50 | p99 | peak throughput | on-disk |
313
- |---|---|---|---|---|---|---|
314
- | PyTorch (fp32) | 0.8643 | 0.830 | 6.8 ms | 24.1 ms | 263 req/s @4w (collapses past 4w, p99 185 ms @8w) | — |
315
- | ONNX fp32 | 0.8643 | 0.830 | 14.6 ms | 30.2 ms | 395 req/s @8w | 133.7 MB |
316
- | **ONNX INT8** | **0.8710** | **0.835** | **6.0 ms** | **12.4 ms** | **956 req/s @8w** | **34.0 MB** |
317
-
318
- INT8 quantization gives **~3.6× throughput** and a **~3.9× smaller model** with **no accuracy loss** (re-measured on the full set after quantizing, not assumed), and keeps p99 under 19 ms under concurrent load where the PyTorch path degrades.
319
-
320
- The quantized model (`onnx/model_quantized.onnx`) and the reproducible harness (`benchmark/`) are included in this repo. Numbers are machine-specific; the point is the relative win and the shape of the load curve.
321
-
322
- ## Citation
323
-
324
- Dataset:
325
-
326
- ```bibtex
327
- @article{malo2014good,
328
- title={Good debt or bad debt: Detecting semantic orientations in economic texts},
329
- author={Malo, Pekka and Sinha, Ankur and Korhonen, Pekka and Wallenius, Jyrki and Takala, Pyry},
330
- journal={Journal of the Association for Information Science and Technology},
331
- volume={65}, number={4}, pages={782--796}, year={2014}
332
- }
333
- ```
334
-
335
- ## Contact
336
-
337
- Maintainer: nagizaazs@gmail.com
338
-
339
- ## License
340
-
341
- MIT
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
average.py DELETED
@@ -1,9 +0,0 @@
1
- """Usage: average.py out_dir run_dir [run_dir ...] - uniform weight average of same-architecture checkpoints."""
2
- import sys, shutil
3
- from safetensors.torch import load_file, save_file
4
- out, *runs = sys.argv[1:]
5
- sds = [load_file(f"{r}/model.safetensors") for r in runs]
6
- avg = {k: sum(sd[k].float() for sd in sds) / len(sds) for k in sds[0]}
7
- shutil.copytree(runs[0], out, dirs_exist_ok=True)
8
- save_file({k: v.contiguous() for k, v in avg.items()}, f"{out}/model.safetensors", metadata={"format": "pt"})
9
- print("averaged", len(runs), "->", out)
 
 
 
 
 
 
 
 
 
 
benchmark/baseline.py DELETED
@@ -1,76 +0,0 @@
1
- import time, json, statistics, concurrent.futures as cf
2
- import numpy as np, torch
3
- from transformers import AutoTokenizer, AutoModelForSequenceClassification
4
- from datasets import load_dataset
5
- from sklearn.metrics import accuracy_score, f1_score, classification_report
6
-
7
- torch.set_num_threads(1) # measure per-request latency honestly (one core/request)
8
- MODEL = "9mark9/finbert-minilm-sentiment"
9
- tok = AutoTokenizer.from_pretrained(MODEL)
10
- model = AutoModelForSequenceClassification.from_pretrained(MODEL)
11
- model.eval()
12
- id2label = {int(k): v.lower() for k, v in model.config.id2label.items()}
13
- print("model id2label:", id2label)
14
-
15
- # normalize model labels -> {bearish,bullish,neutral}
16
- def norm(lbl):
17
- l = lbl.lower()
18
- if l.startswith("pos") or "bull" in l: return "bullish"
19
- if l.startswith("neg") or "bear" in l: return "bearish"
20
- return "neutral"
21
-
22
- # dataset: 0=Bearish 1=Bullish 2=Neutral
23
- ds = load_dataset("zeroshot/twitter-financial-news-sentiment", split="validation")
24
- gold_map = {0: "bearish", 1: "bullish", 2: "neutral"}
25
- texts = ds["text"]; gold = [gold_map[l] for l in ds["label"]]
26
- print("eval rows:", len(texts))
27
-
28
- @torch.no_grad()
29
- def predict(text):
30
- enc = tok(text, return_tensors="pt", truncation=True, max_length=128)
31
- logits = model(**enc).logits
32
- return norm(id2label[int(logits.argmax(-1))])
33
-
34
- # ---- accuracy on full validation set ----
35
- t0 = time.time()
36
- preds = [predict(t) for t in texts]
37
- eval_s = time.time() - t0
38
- acc = accuracy_score(gold, preds)
39
- mf1 = f1_score(gold, preds, average="macro", labels=["bearish","bullish","neutral"])
40
- print(f"\n[ACCURACY] n={len(texts)} acc={acc:.4f} macroF1={mf1:.4f} (eval {eval_s:.1f}s)")
41
- print(classification_report(gold, preds, labels=["bearish","bullish","neutral"], digits=3, zero_division=0))
42
-
43
- # ---- single-request latency (warm) ----
44
- sample = texts[:400]
45
- for _ in range(10): predict(sample[0]) # warmup
46
- lat = []
47
- for t in sample:
48
- s = time.perf_counter(); predict(t); lat.append((time.perf_counter()-s)*1000)
49
- lat.sort()
50
- p = lambda q: lat[int(q*len(lat))-1]
51
- print(f"\n[LATENCY serial, 1 thread] n={len(lat)} p50={p(.5):.1f}ms p95={p(.95):.1f}ms p99={p(.99):.1f}ms mean={statistics.mean(lat):.1f}ms")
52
-
53
- # ---- concurrency throughput (real traffic) ----
54
- def load_test(workers, total):
55
- torch.set_num_threads(1)
56
- reqs = [sample[i % len(sample)] for i in range(total)]
57
- lats = []
58
- start = time.perf_counter()
59
- with cf.ThreadPoolExecutor(max_workers=workers) as ex:
60
- def one(t):
61
- s = time.perf_counter(); predict(t); return (time.perf_counter()-s)*1000
62
- for ms in ex.map(one, reqs): lats.append(ms)
63
- wall = time.perf_counter()-start
64
- lats.sort(); pp = lambda q: lats[int(q*len(lats))-1]
65
- return {"workers":workers,"total":total,"rps":round(total/wall,1),
66
- "p50":round(pp(.5),1),"p95":round(pp(.95),1),"p99":round(pp(.99),1)}
67
-
68
- print("\n[THROUGHPUT under concurrent traffic]")
69
- res=[]
70
- for w in (1,4,8,16):
71
- r = load_test(w, 300); res.append(r); print(" ", r)
72
-
73
- json.dump({"model":MODEL,"n":len(texts),"acc":acc,"macroF1":mf1,
74
- "latency_serial_ms":{"p50":p(.5),"p95":p(.95),"p99":p(.99)},
75
- "throughput":res}, open("baseline_results.json","w"), indent=2)
76
- print("\nSAVED baseline_results.json")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmark/finbert-serving-benchmark.md DELETED
@@ -1,78 +0,0 @@
1
- # finbert-minilm-sentiment — serving benchmark & latency optimization
2
-
3
- **Date:** 2026-11-05
4
- **Model:** `9mark9/finbert-minilm-sentiment` (MiniLM-L12-H384, 33.4M params, 3-class financial sentiment)
5
- **Machine:** Apple Silicon Mac, CPU inference, 1 thread per request (honest per-request measurement)
6
- **Eval set:** `zeroshot/twitter-financial-news-sentiment` validation split — **2,388 rows** (full split, not a sample)
7
-
8
- ## Headline
9
-
10
- INT8-quantized ONNX gives **3.6× throughput** and **~4× smaller model** with **no accuracy loss** versus the PyTorch baseline, and holds p99 latency flat under concurrent load where the PyTorch path collapses.
11
-
12
- ## Accuracy (full 2,388-row validation set)
13
-
14
- | variant | accuracy | macro-F1 |
15
- |---|---|---|
16
- | PyTorch (fp32) | 0.8643 | 0.830 |
17
- | ONNX fp32 | 0.8643 | 0.830 |
18
- | **ONNX INT8** | **0.8710** | **0.835** |
19
-
20
- Quantization did not degrade quality (+0.7 pt accuracy, within sampling noise). Per-class report is in `baseline_results.json`.
21
-
22
- ## Latency — warm, single request, 1 thread
23
-
24
- | variant | p50 | p95 | p99 |
25
- |---|---|---|---|
26
- | PyTorch | 6.8 ms | 10.6 ms | 24.1 ms |
27
- | ONNX fp32 | 14.6 ms | 27.8 ms | 30.2 ms |
28
- | **ONNX INT8** | **6.0 ms** | **11.1 ms** | **12.4 ms** |
29
-
30
- ## Throughput — concurrent traffic (load test, 300 requests per level)
31
-
32
- | workers | PyTorch rps | ONNX fp32 rps | ONNX INT8 rps | INT8 p99 |
33
- |---|---|---|---|---|
34
- | 1 | 138 | 62 | 155 | 12.4 ms |
35
- | 4 | 263 (peak) | 240 | 603 | 12.4 ms |
36
- | 8 | 170 (p99 185 ms) | 395 | **956 (peak)** | 18.6 ms |
37
-
38
- PyTorch peaks at ~263 req/s then **degrades** past 4 workers (GIL + kernel contention; p99 → 185 ms). ONNX INT8 scales to **~956 req/s** with p99 under 19 ms.
39
-
40
- ## Model size
41
-
42
- | variant | on-disk |
43
- |---|---|
44
- | ONNX fp32 | 133.7 MB |
45
- | ONNX INT8 | 34.0 MB |
46
-
47
- ~3.9× smaller → cheaper to ship, faster cold start, fits more replicas per node.
48
-
49
- ## Method / honesty notes
50
-
51
- - Both PyTorch and ONNX measured at 1 inference thread per request so the comparison is apples-to-apples; concurrency scaling comes from multiple workers, not intra-op threads.
52
- - Dynamic INT8 quantization (weights int8, activations quantized at runtime) via `optimum.onnxruntime` ORTQuantizer, arm64 config, per-tensor.
53
- - Accuracy re-measured on the full validation set *after* quantization — not assumed.
54
- - Numbers are machine-specific; the point is the **relative** win and the shape of the degradation curve, not absolute rps.
55
-
56
- ## Reproduce
57
-
58
- ```
59
- bench/baseline.py # PyTorch eval + latency + throughput
60
- bench/optimize.py # ONNX export + INT8 quantize + re-eval + re-measure
61
- # results: baseline_results.json, optimize_results.json
62
- ```
63
-
64
- ---
65
-
66
- ## Interview STAR answers
67
-
68
- ### STAR 1 — Latency / serving optimization
69
- - **Situation:** A financial-sentiment classifier was accurate but only characterized on a 600-row sample and served from an unoptimized PyTorch demo with no throughput numbers.
70
- - **Task:** Establish a real serving envelope and cut latency/cost without losing accuracy.
71
- - **Action:** Evaluated on the full 2,388-row validation set; load-tested at 1/4/8/16 concurrent workers to find where PyTorch throughput collapses (past 4 workers, p99 → 185 ms); exported to ONNX and applied dynamic INT8 quantization; re-measured accuracy on the full set to prove parity.
72
- - **Result:** 3.6× throughput (263 → 956 req/s), p99 held under 19 ms under load, model 4× smaller (134 → 34 MB), accuracy unchanged (86.4% → 87.1%). "I don't ship a model until I know its p99 under concurrency and its cost per request."
73
-
74
- ### STAR 2 — Evaluation rigor
75
- - **Situation:** Card metrics came from a small sample; that reads junior.
76
- - **Task:** Produce a number a model-risk reviewer would accept.
77
- - **Action:** Ran the complete held-out validation split, reported macro-F1 and per-class, and re-verified after every change (quantization, runtime) instead of trusting that the transform was lossless.
78
- - **Result:** Accuracy 86.43% on 2,388 rows with the per-class breakdown; quantization verified non-degrading rather than assumed.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmark/optimize.py DELETED
@@ -1,80 +0,0 @@
1
- import time, json, statistics, concurrent.futures as cf
2
- import numpy as np
3
- from transformers import AutoTokenizer
4
- from optimum.onnxruntime import ORTModelForSequenceClassification, ORTQuantizer
5
- from optimum.onnxruntime.configuration import AutoQuantizationConfig
6
- from datasets import load_dataset
7
- from sklearn.metrics import accuracy_score, f1_score
8
- import onnxruntime as ort
9
-
10
- MODEL = "9mark9/finbert-minilm-sentiment"
11
- tok = AutoTokenizer.from_pretrained(MODEL)
12
-
13
- import os
14
- if not os.path.isdir("onnx_fp32"):
15
- print("exporting ONNX...")
16
- m0 = ORTModelForSequenceClassification.from_pretrained(MODEL, export=True)
17
- m0.save_pretrained("onnx_fp32")
18
- if not os.path.isdir("onnx_int8"):
19
- print("quantizing INT8...")
20
- quantizer = ORTQuantizer.from_pretrained("onnx_fp32")
21
- try:
22
- qconfig = AutoQuantizationConfig.arm64(is_static=False, per_channel=False)
23
- except Exception:
24
- qconfig = AutoQuantizationConfig.avx2(is_static=False, per_channel=False)
25
- quantizer.quantize(save_dir="onnx_int8", quantization_config=qconfig)
26
-
27
- from transformers import AutoConfig
28
- id2label = {int(k): v.lower() for k, v in AutoConfig.from_pretrained(MODEL).id2label.items()}
29
- def norm(l):
30
- l=l.lower()
31
- if l.startswith("pos") or "bull" in l: return "bullish"
32
- if l.startswith("neg") or "bear" in l: return "bearish"
33
- return "neutral"
34
-
35
- ds = load_dataset("zeroshot/twitter-financial-news-sentiment", split="validation")
36
- gmap={0:"bearish",1:"bullish",2:"neutral"}
37
- texts=ds["text"]; gold=[gmap[l] for l in ds["label"]]
38
-
39
- def make_session(path):
40
- so=ort.SessionOptions(); so.intra_op_num_threads=1; so.inter_op_num_threads=1
41
- return ORTModelForSequenceClassification.from_pretrained(path, session_options=so)
42
-
43
- def bench(name, path):
44
- m=make_session(path)
45
- def predict(t):
46
- enc=tok(t, return_tensors="np", truncation=True, max_length=128)
47
- out=m(**{k:v for k,v in enc.items()})
48
- logits=np.asarray(out.logits)
49
- return norm(id2label[int(logits.reshape(-1, logits.shape[-1])[0].argmax())])
50
- preds=[predict(t) for t in texts]
51
- acc=accuracy_score(gold,preds); mf1=f1_score(gold,preds,average="macro",labels=["bearish","bullish","neutral"])
52
- sample=texts[:400]
53
- for _ in range(10): predict(sample[0])
54
- lat=[]
55
- for t in sample:
56
- s=time.perf_counter(); predict(t); lat.append((time.perf_counter()-s)*1000)
57
- lat.sort(); p=lambda q:lat[int(q*len(lat))-1]
58
- # concurrency
59
- def one(t):
60
- s0=time.perf_counter(); predict(t); return (time.perf_counter()-s0)*1000
61
- def lt(workers,total):
62
- reqs=[sample[i%len(sample)] for i in range(total)]; ls=[]
63
- st=time.perf_counter()
64
- with cf.ThreadPoolExecutor(max_workers=workers) as ex:
65
- for ms in ex.map(one, reqs): ls.append(ms)
66
- wall=time.perf_counter()-st; ls.sort(); pp=lambda q:ls[int(q*len(ls))-1]
67
- return {"workers":workers,"rps":round(total/wall,1),"p50":round(pp(.5),1),"p95":round(pp(.95),1),"p99":round(pp(.99),1)}
68
- tp=[lt(w,300) for w in (1,4,8)]
69
- r={"variant":name,"acc":round(acc,4),"macroF1":round(mf1,4),
70
- "lat_serial":{"p50":round(p(.5),1),"p95":round(p(.95),1),"p99":round(p(.99),1)},"throughput":tp}
71
- print(f"[{name}] acc={acc:.4f} mF1={mf1:.4f} serial p50={p(.5):.1f} p95={p(.95):.1f}ms")
72
- for x in tp: print(" ",x)
73
- return r
74
-
75
- out=[bench("onnx_fp32","onnx_fp32"), bench("onnx_int8","onnx_int8")]
76
- import os
77
- sz=lambda d: round(sum(os.path.getsize(os.path.join(d,f)) for f in os.listdir(d) if f.endswith(".onnx"))/1e6,1)
78
- for o in out: o["model_mb"]=sz(o["variant"])
79
- json.dump(out, open("optimize_results.json","w"), indent=2)
80
- print("\nSAVED optimize_results.json sizes(MB):", {o['variant']:o['model_mb'] for o in out})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
common.py DELETED
@@ -1,140 +0,0 @@
1
- """Shared data loading and evaluation for old-vs-new comparison (same code for both models)."""
2
- import csv, zipfile, json, sys
3
- import numpy as np, torch
4
- import pyarrow.parquet as pq
5
- from huggingface_hub import hf_hub_download
6
- from sklearn.model_selection import train_test_split
7
- from sklearn.metrics import accuracy_score, f1_score, precision_recall_fscore_support
8
-
9
- LABELS = ["negative", "neutral", "positive"]
10
- L2I = {l: i for i, l in enumerate(LABELS)}
11
- TW_REV = "ccbe24de388e287beb92dd393a335c376b350ac3"
12
- JB_REV = "547fa98342d2c80734a1c841dbf3de2cfcaaab95"
13
- TW_MAP = {"0": "negative", "1": "positive", "2": "neutral"} # Bearish, Bullish, Neutral
14
- JB_MAP = {0: "negative", 1: "neutral", 2: "positive"} # ClassLabel names in dataset_infos.json
15
-
16
-
17
- PB_REV = "8d3fe0c36d5feec6b3cc5e455b0fcb4820fb9964"
18
- SF_REV = "d6294b768091ae7198051294c7fdeee2fbfbd224"
19
- NS_REV = "9bd8206a729ccd64fa259f0368f0b4025bb472af"
20
-
21
-
22
- def norm(t):
23
- return " ".join(t.lower().split())
24
-
25
-
26
- def phrasebank(agree="AllAgree"): # AllAgree, 75Agree, 66Agree or 50Agree
27
- z = zipfile.ZipFile(hf_hub_download("takala/financial_phrasebank", "data/FinancialPhraseBank-v1.0.zip", repo_type="dataset", revision=PB_REV))
28
- name = [x for x in z.namelist() if x.endswith(f"Sentences_{agree}.txt") and not x.startswith("__MACOSX")][0]
29
- rows = [l.rsplit("@", 1) for l in z.read(name).decode("latin-1").splitlines() if "@" in l]
30
- return [t.strip() for t, _ in rows], [s.strip() for _, s in rows]
31
-
32
-
33
- def phrasebank_split():
34
- """Stratified 70/15/15, random_state=42: test first, then validation from the rest."""
35
- X, y = phrasebank()
36
- Xtv, Xte, ytv, yte = train_test_split(X, y, test_size=0.15, stratify=y, random_state=42)
37
- Xtr, Xva, ytr, yva = train_test_split(Xtv, ytv, test_size=0.15 / 0.85, stratify=ytv, random_state=42)
38
- return (Xtr, ytr), (Xva, yva), (Xte, yte)
39
-
40
-
41
- def twitter(split): # "train" or "valid"
42
- p = hf_hub_download("zeroshot/twitter-financial-news-sentiment", f"sent_{split}.csv", repo_type="dataset", revision=TW_REV)
43
- rows = list(csv.DictReader(open(p, newline="", encoding="utf-8")))
44
- return [r["text"] for r in rows], [TW_MAP[r["label"]] for r in rows]
45
-
46
-
47
- def jb(split): # "train" or "test"; text = headline (title)
48
- f = {"train": "data/train-00000-of-00001-f6c9e78174b9882e.parquet", "test": "data/test-00000-of-00001-f8c02546a74f96bb.parquet"}[split]
49
- rows = pq.read_table(hf_hub_download("Jean-Baptiste/financial_news_sentiment", f, repo_type="dataset", revision=JB_REV)).to_pylist()
50
- return [r["title"] for r in rows], [JB_MAP[int(r["labels"])] for r in rows]
51
-
52
-
53
- def phrasebank_extra(agree):
54
- """Sentences in a lower-agreement PhraseBank file that are not in AllAgree at all (so none of the
55
- AllAgree test or validation sentences can leak in); label = the file's majority label."""
56
- allagree = {norm(t) for t in phrasebank()[0]}
57
- X, y = phrasebank(agree)
58
- keep = [(t, l) for t, l in zip(X, y) if norm(t) not in allagree]
59
- return [t for t, _ in keep], [l for _, l in keep]
60
-
61
-
62
- def sentfin(split="test"):
63
- """SEntFiN headlines (tasksource/sentfin repackaging, 80/10/10 split grouped by headline). The source
64
- labels each entity in a headline; a headline is kept only when every entity has the same label."""
65
- rows = pq.read_table(hf_hub_download("tasksource/sentfin", f"data/{split}-00000-of-00001.parquet", repo_type="dataset", revision=SF_REV)).to_pylist()
66
- by = {}
67
- for r in rows:
68
- hid = json.loads(r["metadata"])["headline_id"]
69
- by.setdefault(hid, (r["sentence1"], set()))[1].add(r["labels"])
70
- keep = [(t, next(iter(ls))) for t, ls in by.values() if len(ls) == 1]
71
- return [t for t, _ in keep], [l for _, l in keep]
72
-
73
-
74
- def nosible(n, max_words=60, seed=42):
75
- """n random short snippets (<= max_words words) from NOSIBLE/financial-sentiment; its labels come from an
76
- automated multi-annotator pipeline (see that dataset card), not from human annotators."""
77
- import random
78
- t = pq.read_table(hf_hub_download("NOSIBLE/financial-sentiment", "data.parquet", repo_type="dataset", revision=NS_REV), columns=["text", "label"]).to_pylist()
79
- t = [r for r in t if len(r["text"].split()) <= max_words and r["label"] in L2I]
80
- t = random.Random(seed).sample(t, min(n, len(t)))
81
- return [r["text"] for r in t], [r["label"] for r in t]
82
-
83
-
84
- def device():
85
- import os
86
- return torch.device("mps" if torch.backends.mps.is_available() and not os.environ.get("FORCE_CPU") else "cpu")
87
-
88
-
89
- @torch.no_grad()
90
- def predict(model, tok, texts, max_len=96, bs=64, dev=None):
91
- dev = dev or next(model.parameters()).device
92
- model.eval()
93
- id2l = {int(k): v.lower() for k, v in model.config.id2label.items()}
94
- out = []
95
- for i in range(0, len(texts), bs):
96
- enc = tok(texts[i:i + bs], padding=True, truncation=True, max_length=max_len, return_tensors="pt").to(dev)
97
- out += [id2l[int(j)] for j in model(**enc).logits.argmax(-1).cpu()]
98
- return out
99
-
100
-
101
- def report(gold, pred):
102
- p, r, f, s = precision_recall_fscore_support(gold, pred, labels=LABELS, zero_division=0)
103
- return {"n": len(gold), "accuracy": accuracy_score(gold, pred), "macro_f1": f1_score(gold, pred, labels=LABELS, average="macro"),
104
- "per_class": {l: {"precision": float(p[i]), "recall": float(r[i]), "f1": float(f[i]), "support": int(s[i])} for i, l in enumerate(LABELS)}}
105
-
106
-
107
- def heldout_sets():
108
- _, _, (Xte, yte) = phrasebank_split()
109
- return {"phrasebank_test": (Xte, yte), "twitter_valid": twitter("valid"), "jb_test": jb("test"), "sentfin_test": sentfin("test")}
110
-
111
-
112
- def bootstrap(gold, pred, n=2000, seed=0):
113
- """95% percentile intervals for macro-F1 and negative recall, resampling rows with replacement."""
114
- from sklearn.metrics import recall_score
115
- rng = np.random.default_rng(seed)
116
- g, p = np.array(gold), np.array(pred)
117
- mf, nr = [], []
118
- for _ in range(n):
119
- i = rng.integers(0, len(g), len(g))
120
- mf.append(f1_score(g[i], p[i], labels=LABELS, average="macro", zero_division=0))
121
- nr.append(recall_score(g[i], p[i], labels=["negative"], average="macro", zero_division=0))
122
- q = lambda a: [float(np.percentile(a, 2.5)), float(np.percentile(a, 97.5))]
123
- return {"macro_f1_ci": q(mf), "neg_recall_ci": q(nr)}
124
-
125
-
126
- def evaluate(model, tok):
127
- out = {}
128
- for k, (X, y) in heldout_sets().items():
129
- pred = predict(model, tok, X)
130
- out[k] = {**report(y, pred), **bootstrap(y, pred), "pred": pred}
131
- return out
132
-
133
-
134
- def fmt(res):
135
- lines = []
136
- for k, v in res.items():
137
- pc = " ".join(f"{l[:3]} P{c['precision']:.3f} R{c['recall']:.3f} (n={c['support']})" for l, c in v["per_class"].items())
138
- ci = f" [{v['macro_f1_ci'][0]:.3f},{v['macro_f1_ci'][1]:.3f}]" if "macro_f1_ci" in v else ""
139
- lines.append(f"{k:16s} n={v['n']:5d} acc={v['accuracy']:.4f} mF1={v['macro_f1']:.4f}{ci} negF1={v['per_class']['negative']['f1']:.3f} | {pc}")
140
- return "\n".join(lines)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
config.json DELETED
@@ -1,38 +0,0 @@
1
- {
2
- "add_cross_attention": false,
3
- "architectures": [
4
- "BertForSequenceClassification"
5
- ],
6
- "attention_probs_dropout_prob": 0.1,
7
- "bos_token_id": null,
8
- "classifier_dropout": null,
9
- "dtype": "float32",
10
- "eos_token_id": null,
11
- "hidden_act": "gelu",
12
- "hidden_dropout_prob": 0.1,
13
- "hidden_size": 384,
14
- "id2label": {
15
- "0": "negative",
16
- "1": "neutral",
17
- "2": "positive"
18
- },
19
- "initializer_range": 0.02,
20
- "intermediate_size": 1536,
21
- "is_decoder": false,
22
- "label2id": {
23
- "negative": 0,
24
- "neutral": 1,
25
- "positive": 2
26
- },
27
- "layer_norm_eps": 1e-12,
28
- "max_position_embeddings": 512,
29
- "model_type": "bert",
30
- "num_attention_heads": 12,
31
- "num_hidden_layers": 12,
32
- "pad_token_id": 0,
33
- "tie_word_embeddings": true,
34
- "transformers_version": "5.9.0",
35
- "type_vocab_size": 2,
36
- "use_cache": true,
37
- "vocab_size": 30522
38
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eval_model.py DELETED
@@ -1,13 +0,0 @@
1
- """Usage: eval_model.py <model id or dir> [revision] [out.json] — scores all three held-out sets."""
2
- import sys, json
3
- from transformers import AutoModelForSequenceClassification, AutoTokenizer
4
- from common import evaluate, fmt, device
5
-
6
- src = sys.argv[1]
7
- rev = sys.argv[2] if len(sys.argv) > 2 and sys.argv[2] != "-" else None
8
- tok = AutoTokenizer.from_pretrained(src, revision=rev)
9
- model = AutoModelForSequenceClassification.from_pretrained(src, revision=rev).to(device())
10
- res = evaluate(model, tok)
11
- print(fmt(res))
12
- if len(sys.argv) > 3:
13
- json.dump(res, open(sys.argv[3], "w"), indent=1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
model.safetensors DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:7e0b45b861181390accea195bcf1f97ff5a2a9c3a0afde63b923cee29007f006
3
- size 133467916
 
 
 
 
onnx/config.json DELETED
@@ -1,34 +0,0 @@
1
- {
2
- "architectures": [
3
- "BertForSequenceClassification"
4
- ],
5
- "attention_probs_dropout_prob": 0.1,
6
- "classifier_dropout": null,
7
- "dtype": "float32",
8
- "hidden_act": "gelu",
9
- "hidden_dropout_prob": 0.1,
10
- "hidden_size": 384,
11
- "id2label": {
12
- "0": "negative",
13
- "1": "neutral",
14
- "2": "positive"
15
- },
16
- "initializer_range": 0.02,
17
- "intermediate_size": 1536,
18
- "label2id": {
19
- "negative": 0,
20
- "neutral": 1,
21
- "positive": 2
22
- },
23
- "layer_norm_eps": 1e-12,
24
- "max_position_embeddings": 512,
25
- "model_type": "bert",
26
- "num_attention_heads": 12,
27
- "num_hidden_layers": 12,
28
- "pad_token_id": 0,
29
- "position_embedding_type": "absolute",
30
- "transformers_version": "4.57.6",
31
- "type_vocab_size": 2,
32
- "use_cache": true,
33
- "vocab_size": 30522
34
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
onnx/model_quantized.onnx DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:b85fd2d5b85ea7d3ad201e8d84e5162866fe635b1134c6d2652f814ccedc6c1b
3
- size 33974960
 
 
 
 
onnx/ort_config.json DELETED
@@ -1,33 +0,0 @@
1
- {
2
- "one_external_file": true,
3
- "opset": null,
4
- "optimization": {},
5
- "quantization": {
6
- "activations_dtype": "QUInt8",
7
- "activations_symmetric": false,
8
- "format": "QOperator",
9
- "is_static": false,
10
- "mode": "IntegerOps",
11
- "nodes_to_exclude": [],
12
- "nodes_to_quantize": [],
13
- "operators_to_quantize": [
14
- "Conv",
15
- "MatMul",
16
- "Attention",
17
- "LSTM",
18
- "Gather",
19
- "Transpose",
20
- "EmbedLayerNormalization"
21
- ],
22
- "per_channel": false,
23
- "qdq_add_pair_to_weight": false,
24
- "qdq_dedicated_pair": false,
25
- "qdq_op_type_per_channel_support_to_axis": {
26
- "MatMul": 1
27
- },
28
- "reduce_range": false,
29
- "weights_dtype": "QInt8",
30
- "weights_symmetric": true
31
- },
32
- "use_external_data_format": false
33
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements-train.txt DELETED
@@ -1,8 +0,0 @@
1
- # Packages used to train and score this model (Python 3.12, Apple GPU via PyTorch MPS; CPU also works).
2
- torch==2.14.1
3
- transformers==5.21.0
4
- scikit-learn==1.9.1
5
- numpy==2.5.4
6
- pyarrow==26.0.0
7
- huggingface_hub==2.3.0
8
- safetensors==0.8.0
 
 
 
 
 
 
 
 
 
tokenizer.json DELETED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json DELETED
@@ -1,15 +0,0 @@
1
- {
2
- "backend": "tokenizers",
3
- "cls_token": "[CLS]",
4
- "do_lower_case": true,
5
- "is_local": false,
6
- "local_files_only": false,
7
- "mask_token": "[MASK]",
8
- "model_max_length": 1000000000000000019884624838656,
9
- "pad_token": "[PAD]",
10
- "sep_token": "[SEP]",
11
- "strip_accents": null,
12
- "tokenize_chinese_chars": true,
13
- "tokenizer_class": "BertTokenizer",
14
- "unk_token": "[UNK]"
15
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
train.py DELETED
@@ -1,90 +0,0 @@
1
- """Mixed-domain fine-tune. Usage: train.py --lr 3e-5 --pb-rep 3 --pb-extra 50Agree --out runs/x
2
- Held-out sets (PhraseBank 15% test, full tweet validation, JB test, SEntFiN test) are never trained or selected on;
3
- SEntFiN is not used for training or selection at all."""
4
- import argparse, json, random, time
5
- import numpy as np, torch
6
- from sklearn.model_selection import train_test_split
7
- from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup
8
- from common import LABELS, L2I, norm, phrasebank_split, phrasebank_extra, nosible, twitter, jb, heldout_sets, predict, report, device
9
-
10
- ap = argparse.ArgumentParser()
11
- ap.add_argument("--lr", type=float, default=3e-5)
12
- ap.add_argument("--pb-rep", type=int, default=3, help="PhraseBank train repeats per epoch (keeps in-domain weight)")
13
- ap.add_argument("--epochs", type=int, default=3)
14
- ap.add_argument("--bs", type=int, default=16)
15
- ap.add_argument("--evals-per-epoch", type=int, default=2)
16
- ap.add_argument("--patience", type=int, default=2)
17
- ap.add_argument("--base", default="microsoft/MiniLM-L12-H384-uncased")
18
- ap.add_argument("--pb-extra", default="", help="add lower-agreement PhraseBank sentences not in AllAgree: 75Agree, 66Agree or 50Agree")
19
- ap.add_argument("--extra-rep", type=int, default=1)
20
- ap.add_argument("--jb-rep", type=int, default=1, help="headline train repeats per epoch")
21
- ap.add_argument("--nosible", type=int, default=0, help="add this many short NOSIBLE news snippets")
22
- ap.add_argument("--neg-mult", type=float, default=1.0, help="extra multiplier on the negative class weight")
23
- ap.add_argument("--ls", type=float, default=0.0, help="label smoothing")
24
- ap.add_argument("--warmup", type=float, default=0.1)
25
- ap.add_argument("--seed", type=int, default=42)
26
- ap.add_argument("--out", required=True)
27
- a = ap.parse_args()
28
- random.seed(a.seed); np.random.seed(a.seed); torch.manual_seed(a.seed)
29
-
30
- held = {norm(t) for X, _ in heldout_sets().values() for t in X}
31
-
32
- def carve(X, y): # 90/10 stratified train/val slice from a training file only
33
- return train_test_split(X, y, test_size=0.10, stratify=y, random_state=42)
34
-
35
- (pbX, pby), (pbvX, pbvy), _ = phrasebank_split()
36
- twX, twvX, twy, twvy = carve(*twitter("train"))
37
- jbX, jbvX, jby, jbvy = carve(*jb("train"))
38
- val = {"pb": (pbvX, pbvy), "tw": (twvX, twvy), "jb": (jbvX, jbvy)}
39
- held |= {norm(t) for X, _ in val.values() for t in X} # also keep validation text out of training
40
- exX, exy = phrasebank_extra(a.pb_extra) if a.pb_extra else ([], [])
41
- nsX, nsy = nosible(a.nosible) if a.nosible else ([], [])
42
-
43
- raw = list(zip(pbX, pby)) * a.pb_rep + list(zip(twX, twy)) + list(zip(jbX, jby)) * a.jb_rep + list(zip(exX, exy)) * a.extra_rep + list(zip(nsX, nsy))
44
- train = [(t, l) for t, l in raw if norm(t) not in held]
45
- print(f"train rows {len(train)} (pb {len(pbX)}x{a.pb_rep}, tw {len(twX)}, jb {len(jbX)}x{a.jb_rep}, pb-extra {a.pb_extra or '-'} {len(exX)}x{a.extra_rep}, nosible {len(nsX)}; dropped {len(raw)-len(train)} held-out/validation overlaps)", flush=True)
46
-
47
- dev = device()
48
- tok = AutoTokenizer.from_pretrained(a.base)
49
- model = AutoModelForSequenceClassification.from_pretrained(a.base, num_labels=3, id2label=dict(enumerate(LABELS)), label2id=L2I).to(dev)
50
- counts = np.bincount([L2I[l] for _, l in train], minlength=3)
51
- w = len(train) / (3 * counts) * np.array([a.neg_mult, 1.0, 1.0])
52
- loss_fn = torch.nn.CrossEntropyLoss(weight=torch.tensor(w, dtype=torch.float32, device=dev), label_smoothing=a.ls)
53
- opt = torch.optim.AdamW(model.parameters(), lr=a.lr, weight_decay=0.01)
54
- steps_ep = (len(train) + a.bs - 1) // a.bs
55
- sched = get_linear_schedule_with_warmup(opt, int(a.warmup * steps_ep * a.epochs), steps_ep * a.epochs)
56
- eval_every = steps_ep // a.evals_per_epoch
57
-
58
- def val_score():
59
- r = {k: report(y, predict(model, tok, X)) for k, (X, y) in val.items()}
60
- neg = {k: round(v["per_class"]["negative"]["f1"], 4) for k, v in r.items()}
61
- return float(np.mean([v["macro_f1"] for v in r.values()])), {k: round(v["macro_f1"], 4) for k, v in r.items()}, neg
62
-
63
- best, bad, step, t0, hist = -1, 0, 0, time.time(), []
64
- for ep in range(a.epochs):
65
- random.shuffle(train)
66
- for i in range(0, len(train), a.bs):
67
- model.train()
68
- batch = train[i:i + a.bs]
69
- enc = tok([t for t, _ in batch], padding=True, truncation=True, max_length=96, return_tensors="pt").to(dev)
70
- loss = loss_fn(model(**enc).logits, torch.tensor([L2I[l] for _, l in batch], device=dev))
71
- if not torch.isfinite(loss):
72
- raise SystemExit(f"non-finite loss at step {step}")
73
- loss.backward(); torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
74
- opt.step(); sched.step(); opt.zero_grad(); step += 1
75
- if step % 100 == 0:
76
- print(f"ep {ep} step {step}/{steps_ep*a.epochs} loss {loss.item():.4f} {time.time()-t0:.0f}s", flush=True)
77
- if step % eval_every == 0 or step == steps_ep * a.epochs:
78
- s, f1s, neg = val_score(); hist.append({"step": step, "val_mean_f1": s, "f1": f1s, "neg_f1": neg})
79
- print(f"VAL step {step}: mean mF1 {s:.4f} f1 {f1s} negF1 {neg}", flush=True)
80
- if s > best:
81
- best, bad = s, 0; model.save_pretrained(a.out); tok.save_pretrained(a.out)
82
- else:
83
- bad += 1
84
- if bad >= a.patience:
85
- break
86
- else:
87
- continue
88
- print("early stop", flush=True); break
89
- json.dump({"args": vars(a), "best_val_mean_f1": best, "best": max(hist, key=lambda h: h["val_mean_f1"]), "history": hist}, open(f"{a.out}/val.json", "w"), indent=1)
90
- print(f"done best val mean mF1 {best:.4f} in {time.time()-t0:.0f}s", flush=True)