lkvantaliani commited on
Commit
39ddcbc
·
verified ·
1 Parent(s): b8511cd

SNT classifier v0.5.1

Browse files
Files changed (7) hide show
  1. .gitattributes +1 -0
  2. README.md +141 -0
  3. config.json +261 -0
  4. model.safetensors +3 -0
  5. modeling_snt.py +101 -0
  6. tokenizer.json +3 -0
  7. tokenizer_config.json +15 -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,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ base_model: FacebookAI/xlm-roberta-large
4
+ pipeline_tag: text-classification
5
+ language:
6
+ - multilingual
7
+ tags:
8
+ - news
9
+ - topic-classification
10
+ - multi-label
11
+ - xlm-roberta
12
+ library_name: transformers
13
+ ---
14
+
15
+ # SNT News Classifier v0.5.1
16
+
17
+ Multi-label news topic classifier: **12 top-level (L1) and 71 sub-level (L2)
18
+ categories**, built on `xlm-roberta-large` with two independent sigmoid heads. Both levels are
19
+ genuinely multi-label — an article about a trade deal can be `world` + `money_and_business` +
20
+ `politics` at the same time. Per-class decision thresholds (tuned on a held-out validation split)
21
+ ship inside `config.json`; `predict_labels()` applies them and falls back to argmax so no article
22
+ is ever left unlabeled.
23
+
24
+ Built by [Sweenk](https://sweenk.com) to categorize its news feed; released so others can use and
25
+ scrutinize it.
26
+
27
+ ## Quick start
28
+
29
+ ```python
30
+ from transformers import AutoModel, AutoTokenizer
31
+
32
+ model = AutoModel.from_pretrained("sweenk/snt-classifier", trust_remote_code=True)
33
+ tok = AutoTokenizer.from_pretrained("sweenk/snt-classifier")
34
+
35
+ enc = tok("OpenAI raises $6.6B. The startup announced its latest funding round...",
36
+ return_tensors="pt", truncation=True, max_length=512)
37
+ print(model.predict_labels(**enc))
38
+ # [{'l1': [{'key': 'money_and_business', 'p': 0.99}, {'key': 'tech_and_ai', 'p': 0.98}],
39
+ # 'primary_l1': 'money_and_business',
40
+ # 'l2': [{'key': 'companies_and_industries', 'p': 0.92}, ...]}]
41
+ ```
42
+
43
+ Input convention: `"{title}\n\n{body}"`, truncated at 512 tokens. The classifier was trained
44
+ on title+body; titles alone work but body text improves routing (the training prompt explicitly
45
+ prioritizes body over headline).
46
+
47
+ ## Taxonomy — 12 L1 / 71 L2
48
+
49
+ | L1 category | # L2 | L2 sub-categories |
50
+ |---|---|---|
51
+ | `sports` | 12 | `american_football`, `baseball`, `basketball`, `college_sports`, `combat_sports`, `golf`, `hockey`, `motorsports`, `olympics`, `other_sports`, `soccer`, `tennis` |
52
+ | `politics` | 6 | `elections_and_campaigns`, `government_and_policy`, `immigration_and_borders`, `political_figures_and_scandals`, `social_issues_and_activism`, `state_and_local_politics` |
53
+ | `world` | 4 | `geopolitics_and_diplomacy`, `humanitarian_crises`, `terrorism_and_security`, `war_and_conflict` |
54
+ | `entertainment_and_pop_culture` | 7 | `books_and_arts`, `celebrities_and_gossip`, `gaming`, `internet_culture_and_creators`, `media_and_journalism`, `movies_and_tv`, `music` |
55
+ | `money_and_business` | 8 | `companies_and_industries`, `cost_of_living`, `crypto_and_fintech`, `housing_and_real_estate`, `macro_economy_and_rates`, `markets_and_investing`, `personal_finance`, `work_and_careers` |
56
+ | `crime_and_justice` | 4 | `courts_and_trials`, `crime_and_policing`, `scams_and_fraud`, `true_crime` |
57
+ | `tech_and_ai` | 5 | `artificial_intelligence`, `big_tech_and_startups`, `cybersecurity_and_privacy`, `gadgets_and_apps`, `screen_time_and_digital_life` |
58
+ | `science_and_space` | 4 | `archaeology_and_history`, `psychology_and_behavior`, `scientific_discoveries`, `space_and_astronomy` |
59
+ | `health_and_wellness` | 5 | `fitness_and_exercise`, `medical_and_public_health`, `mental_health`, `nutrition_and_diet`, `sleep_and_longevity` |
60
+ | `lifestyle` | 8 | `education_and_schools`, `faith_and_spirituality`, `fashion_and_beauty`, `food_and_drink`, `home_and_garden`, `parenting_and_family`, `relationships_and_dating`, `travel_and_places` |
61
+ | `weather_and_environment` | 5 | `climate_change`, `disasters_and_accidents`, `energy_and_climate_solutions`, `nature_and_wildlife`, `severe_weather` |
62
+ | `human_stories` | 3 | `animals_and_pets`, `good_news_and_kindness`, `offbeat_and_unusual` |
63
+
64
+ The full machine-readable taxonomy (`l1_keys`, `l2_keys`, `l2_parent`, per-class thresholds) is in
65
+ `config.json`.
66
+
67
+ ## Evaluation — our own numbers, stated plainly
68
+
69
+ Held-out test split: **24,176 articles** (10% of the 241,757 train-eligible corpus
70
+ rows). "Tuned" = per-class thresholds optimized on the *validation* split, then applied unchanged
71
+ to test.
72
+
73
+ | Metric | @0.5 threshold | tuned thresholds |
74
+ |---|---|---|
75
+ | L1 macro F1 | 0.803 | **0.824** |
76
+ | L1 micro F1 | 0.832 | **0.854** |
77
+ | L1 primary accuracy (argmax) | 0.832 | — |
78
+ | L2 macro F1 | 0.624 | 0.671 |
79
+ | L2 micro F1 | 0.760 | 0.757 |
80
+
81
+ ### Per-class L1 F1 (test)
82
+
83
+ | L1 | F1 @0.5 | F1 tuned | threshold |
84
+ |---|---|---|---|
85
+ | `sports` | 0.928 | 0.936 | 0.900 |
86
+ | `politics` | 0.849 | 0.861 | 0.700 |
87
+ | `world` | 0.781 | 0.827 | 0.900 |
88
+ | `entertainment_and_pop_culture` | 0.895 | 0.904 | 0.800 |
89
+ | `money_and_business` | 0.772 | 0.810 | 0.900 |
90
+ | `crime_and_justice` | 0.821 | 0.846 | 0.900 |
91
+ | `tech_and_ai` | 0.721 | 0.726 | 0.950 |
92
+ | `science_and_space` | 0.731 | 0.754 | 0.800 |
93
+ | `health_and_wellness` | 0.830 | 0.859 | 0.900 |
94
+ | `lifestyle` | 0.872 | 0.878 | 0.700 |
95
+ | `weather_and_environment` | 0.793 | 0.817 | 0.850 |
96
+ | `human_stories` | 0.646 | 0.672 | 0.900 |
97
+
98
+ ### What you should know before trusting these numbers
99
+
100
+ Read this section — it is the honest part.
101
+
102
+ - **The gold labels are model-assisted, not human-annotated.** The corpus (255K articles from
103
+ HuffPost archives, CommonCrawl News, daily.dev, and Sweenk production) was labeled by a
104
+ mechanical migration from an earlier taxonomy plus multiple passes of a Claude Sonnet teacher
105
+ with a rule-based prompt, spot-audited by humans (QA gates at 70–87% agreement on sampled
106
+ batches). Test F1 therefore measures agreement with an LLM teacher, not with human ground truth.
107
+ - **Class imbalance is real (~21x).** `politics`/`lifestyle`/`entertainment` have ~44-47K training
108
+ rows; `science_and_space` has ~2.2K and `tech_and_ai` ~3.7K. Training used per-class
109
+ `pos_weight` (clamped at 10) to compensate. The weakest class is `human_stories`
110
+ (F1 0.672) — it is the fuzziest category by construction.
111
+ - **v0.5.1 is a corrective retrain.** A 986-article human validation of the previous release
112
+ found errors clustered in specific boundaries (accidents dumped into `weather_and_environment`,
113
+ terror attacks into `world`, pharma earnings into `health_and_wellness`). ~1,500 mislabeled rows
114
+ were re-labeled with corrected routing rules and the model retrained. On those corrected rows the
115
+ previous model matches the corrected label 25.9% of the time; this model matches 75.3%. Aggregate
116
+ F1 is *not* directly comparable across releases because the gold labels themselves were corrected.
117
+ - **Multilingual ability is inherited, not measured.** The encoder is XLM-R, but nearly all
118
+ training articles are English. Expect degraded (unquantified) quality on non-English news.
119
+ - **L3 (named topics / entities) is not part of this model** — Sweenk handles that downstream with
120
+ a separate extraction step.
121
+
122
+ ## Architecture
123
+
124
+ `xlm-roberta-large` encoder → CLS pooling → dropout(0.1) → two parallel linear heads
125
+ (L1: 12 logits, L2: 71 logits), both sigmoid. Trained 3 epochs, BCE loss with
126
+ per-class `pos_weight` (L1) and loss weights L1:1.0 / L2:2.0, bf16 autocast, gradient checkpointing.
127
+ Inference upcasts logits to fp32 before sigmoid (bf16 sigmoid saturates above logit ~6.2, which
128
+ collapses co-confident multi-label pairs).
129
+
130
+ ## Versions
131
+
132
+ | Version | What changed |
133
+ |---|---|
134
+ | v0.5 | First multi-label release (12 L1 / 71 L2, dual sigmoid heads) |
135
+ | v0.5.1 | Corrective retrain: route-accidents-by-cause, terror→crime, earnings→money, govt-personnel→politics, wildlife→weather, body-over-headline; ~1,500 corrected labels; re-tuned thresholds |
136
+
137
+ ## License & attribution
138
+
139
+ Model weights: MIT. Base model: [FacebookAI/xlm-roberta-large](https://huggingface.co/FacebookAI/xlm-roberta-large) (MIT).
140
+ The training corpus contains article text from public news sources and is **not** redistributed
141
+ with this model.
config.json ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "SNTForNewsClassification"
4
+ ],
5
+ "auto_map": {
6
+ "AutoModel": "modeling_snt.SNTForNewsClassification"
7
+ },
8
+ "dropout": 0.1,
9
+ "dtype": "float32",
10
+ "encoder_name": "xlm-roberta-large",
11
+ "l1_keys": [
12
+ "sports",
13
+ "politics",
14
+ "world",
15
+ "entertainment_and_pop_culture",
16
+ "money_and_business",
17
+ "crime_and_justice",
18
+ "tech_and_ai",
19
+ "science_and_space",
20
+ "health_and_wellness",
21
+ "lifestyle",
22
+ "weather_and_environment",
23
+ "human_stories"
24
+ ],
25
+ "l1_thresholds": {
26
+ "crime_and_justice": 0.9,
27
+ "entertainment_and_pop_culture": 0.8,
28
+ "health_and_wellness": 0.9,
29
+ "human_stories": 0.9,
30
+ "lifestyle": 0.7,
31
+ "money_and_business": 0.9,
32
+ "politics": 0.7,
33
+ "science_and_space": 0.8,
34
+ "sports": 0.9,
35
+ "tech_and_ai": 0.95,
36
+ "weather_and_environment": 0.85,
37
+ "world": 0.9
38
+ },
39
+ "l2_keys": [
40
+ "soccer",
41
+ "american_football",
42
+ "college_sports",
43
+ "basketball",
44
+ "baseball",
45
+ "hockey",
46
+ "combat_sports",
47
+ "motorsports",
48
+ "tennis",
49
+ "golf",
50
+ "olympics",
51
+ "other_sports",
52
+ "elections_and_campaigns",
53
+ "government_and_policy",
54
+ "political_figures_and_scandals",
55
+ "immigration_and_borders",
56
+ "social_issues_and_activism",
57
+ "state_and_local_politics",
58
+ "war_and_conflict",
59
+ "geopolitics_and_diplomacy",
60
+ "terrorism_and_security",
61
+ "humanitarian_crises",
62
+ "celebrities_and_gossip",
63
+ "movies_and_tv",
64
+ "music",
65
+ "gaming",
66
+ "internet_culture_and_creators",
67
+ "books_and_arts",
68
+ "media_and_journalism",
69
+ "cost_of_living",
70
+ "personal_finance",
71
+ "housing_and_real_estate",
72
+ "work_and_careers",
73
+ "markets_and_investing",
74
+ "crypto_and_fintech",
75
+ "companies_and_industries",
76
+ "macro_economy_and_rates",
77
+ "crime_and_policing",
78
+ "courts_and_trials",
79
+ "scams_and_fraud",
80
+ "true_crime",
81
+ "artificial_intelligence",
82
+ "big_tech_and_startups",
83
+ "gadgets_and_apps",
84
+ "cybersecurity_and_privacy",
85
+ "screen_time_and_digital_life",
86
+ "space_and_astronomy",
87
+ "scientific_discoveries",
88
+ "psychology_and_behavior",
89
+ "archaeology_and_history",
90
+ "mental_health",
91
+ "fitness_and_exercise",
92
+ "nutrition_and_diet",
93
+ "sleep_and_longevity",
94
+ "medical_and_public_health",
95
+ "food_and_drink",
96
+ "travel_and_places",
97
+ "fashion_and_beauty",
98
+ "home_and_garden",
99
+ "parenting_and_family",
100
+ "relationships_and_dating",
101
+ "education_and_schools",
102
+ "faith_and_spirituality",
103
+ "severe_weather",
104
+ "disasters_and_accidents",
105
+ "climate_change",
106
+ "nature_and_wildlife",
107
+ "energy_and_climate_solutions",
108
+ "good_news_and_kindness",
109
+ "offbeat_and_unusual",
110
+ "animals_and_pets"
111
+ ],
112
+ "l2_parent": {
113
+ "american_football": "sports",
114
+ "animals_and_pets": "human_stories",
115
+ "archaeology_and_history": "science_and_space",
116
+ "artificial_intelligence": "tech_and_ai",
117
+ "baseball": "sports",
118
+ "basketball": "sports",
119
+ "big_tech_and_startups": "tech_and_ai",
120
+ "books_and_arts": "entertainment_and_pop_culture",
121
+ "celebrities_and_gossip": "entertainment_and_pop_culture",
122
+ "climate_change": "weather_and_environment",
123
+ "college_sports": "sports",
124
+ "combat_sports": "sports",
125
+ "companies_and_industries": "money_and_business",
126
+ "cost_of_living": "money_and_business",
127
+ "courts_and_trials": "crime_and_justice",
128
+ "crime_and_policing": "crime_and_justice",
129
+ "crypto_and_fintech": "money_and_business",
130
+ "cybersecurity_and_privacy": "tech_and_ai",
131
+ "disasters_and_accidents": "weather_and_environment",
132
+ "education_and_schools": "lifestyle",
133
+ "elections_and_campaigns": "politics",
134
+ "energy_and_climate_solutions": "weather_and_environment",
135
+ "faith_and_spirituality": "lifestyle",
136
+ "fashion_and_beauty": "lifestyle",
137
+ "fitness_and_exercise": "health_and_wellness",
138
+ "food_and_drink": "lifestyle",
139
+ "gadgets_and_apps": "tech_and_ai",
140
+ "gaming": "entertainment_and_pop_culture",
141
+ "geopolitics_and_diplomacy": "world",
142
+ "golf": "sports",
143
+ "good_news_and_kindness": "human_stories",
144
+ "government_and_policy": "politics",
145
+ "hockey": "sports",
146
+ "home_and_garden": "lifestyle",
147
+ "housing_and_real_estate": "money_and_business",
148
+ "humanitarian_crises": "world",
149
+ "immigration_and_borders": "politics",
150
+ "internet_culture_and_creators": "entertainment_and_pop_culture",
151
+ "macro_economy_and_rates": "money_and_business",
152
+ "markets_and_investing": "money_and_business",
153
+ "media_and_journalism": "entertainment_and_pop_culture",
154
+ "medical_and_public_health": "health_and_wellness",
155
+ "mental_health": "health_and_wellness",
156
+ "motorsports": "sports",
157
+ "movies_and_tv": "entertainment_and_pop_culture",
158
+ "music": "entertainment_and_pop_culture",
159
+ "nature_and_wildlife": "weather_and_environment",
160
+ "nutrition_and_diet": "health_and_wellness",
161
+ "offbeat_and_unusual": "human_stories",
162
+ "olympics": "sports",
163
+ "other_sports": "sports",
164
+ "parenting_and_family": "lifestyle",
165
+ "personal_finance": "money_and_business",
166
+ "political_figures_and_scandals": "politics",
167
+ "psychology_and_behavior": "science_and_space",
168
+ "relationships_and_dating": "lifestyle",
169
+ "scams_and_fraud": "crime_and_justice",
170
+ "scientific_discoveries": "science_and_space",
171
+ "screen_time_and_digital_life": "tech_and_ai",
172
+ "severe_weather": "weather_and_environment",
173
+ "sleep_and_longevity": "health_and_wellness",
174
+ "soccer": "sports",
175
+ "social_issues_and_activism": "politics",
176
+ "space_and_astronomy": "science_and_space",
177
+ "state_and_local_politics": "politics",
178
+ "tennis": "sports",
179
+ "terrorism_and_security": "world",
180
+ "travel_and_places": "lifestyle",
181
+ "true_crime": "crime_and_justice",
182
+ "war_and_conflict": "world",
183
+ "work_and_careers": "money_and_business"
184
+ },
185
+ "l2_thresholds": {
186
+ "american_football": 0.55,
187
+ "animals_and_pets": 0.5,
188
+ "archaeology_and_history": 0.05,
189
+ "artificial_intelligence": 0.3,
190
+ "baseball": 0.3,
191
+ "basketball": 0.55,
192
+ "big_tech_and_startups": 0.45,
193
+ "books_and_arts": 0.55,
194
+ "celebrities_and_gossip": 0.4,
195
+ "climate_change": 0.5,
196
+ "college_sports": 0.5,
197
+ "combat_sports": 0.55,
198
+ "companies_and_industries": 0.45,
199
+ "cost_of_living": 0.05,
200
+ "courts_and_trials": 0.3,
201
+ "crime_and_policing": 0.45,
202
+ "crypto_and_fintech": 0.2,
203
+ "cybersecurity_and_privacy": 0.25,
204
+ "disasters_and_accidents": 0.4,
205
+ "education_and_schools": 0.45,
206
+ "elections_and_campaigns": 0.45,
207
+ "energy_and_climate_solutions": 0.45,
208
+ "faith_and_spirituality": 0.35,
209
+ "fashion_and_beauty": 0.45,
210
+ "fitness_and_exercise": 0.35,
211
+ "food_and_drink": 0.4,
212
+ "gadgets_and_apps": 0.55,
213
+ "gaming": 0.65,
214
+ "geopolitics_and_diplomacy": 0.45,
215
+ "golf": 0.35,
216
+ "good_news_and_kindness": 0.25,
217
+ "government_and_policy": 0.4,
218
+ "hockey": 0.15,
219
+ "home_and_garden": 0.5,
220
+ "housing_and_real_estate": 0.3,
221
+ "humanitarian_crises": 0.25,
222
+ "immigration_and_borders": 0.45,
223
+ "internet_culture_and_creators": 0.05,
224
+ "macro_economy_and_rates": 0.5,
225
+ "markets_and_investing": 0.45,
226
+ "media_and_journalism": 0.3,
227
+ "medical_and_public_health": 0.45,
228
+ "mental_health": 0.3,
229
+ "motorsports": 0.55,
230
+ "movies_and_tv": 0.55,
231
+ "music": 0.5,
232
+ "nature_and_wildlife": 0.5,
233
+ "nutrition_and_diet": 0.45,
234
+ "offbeat_and_unusual": 0.3,
235
+ "olympics": 0.6,
236
+ "other_sports": 0.35,
237
+ "parenting_and_family": 0.4,
238
+ "personal_finance": 0.1,
239
+ "political_figures_and_scandals": 0.25,
240
+ "psychology_and_behavior": 0.05,
241
+ "relationships_and_dating": 0.5,
242
+ "scams_and_fraud": 0.25,
243
+ "scientific_discoveries": 0.3,
244
+ "screen_time_and_digital_life": 0.25,
245
+ "severe_weather": 0.45,
246
+ "sleep_and_longevity": 0.05,
247
+ "soccer": 0.4,
248
+ "social_issues_and_activism": 0.25,
249
+ "space_and_astronomy": 0.4,
250
+ "state_and_local_politics": 0.1,
251
+ "tennis": 0.35,
252
+ "terrorism_and_security": 0.45,
253
+ "travel_and_places": 0.4,
254
+ "true_crime": 0.05,
255
+ "war_and_conflict": 0.55,
256
+ "work_and_careers": 0.55
257
+ },
258
+ "model_type": "snt_classifier",
259
+ "snt_version": "v0.5.1",
260
+ "transformers_version": "5.8.0"
261
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:911b368abfd5170be7b8ab73f6bb1b4b9a323e9dba76bb3069a10d9f477a0cce
3
+ size 2239950948
modeling_snt.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SNT news classifier — HF-native wrapper (uploaded to the HF repo as-is).
2
+
3
+ Usage:
4
+ from transformers import AutoModel, AutoTokenizer
5
+ model = AutoModel.from_pretrained("sweenk/snt-classifier", trust_remote_code=True)
6
+ tok = AutoTokenizer.from_pretrained("sweenk/snt-classifier")
7
+ enc = tok("Title. Body...", return_tensors="pt", truncation=True, max_length=512)
8
+ labels = model.predict_labels(**enc)
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import torch
14
+ import torch.nn as nn
15
+ from transformers import AutoModel, PretrainedConfig, PreTrainedModel
16
+
17
+
18
+ class SNTConfig(PretrainedConfig):
19
+ model_type = "snt_classifier"
20
+
21
+ def __init__(
22
+ self,
23
+ encoder_name: str = "xlm-roberta-large",
24
+ l1_keys: list[str] | None = None,
25
+ l2_keys: list[str] | None = None,
26
+ l2_parent: dict[str, str] | None = None,
27
+ l1_thresholds: dict[str, float] | None = None,
28
+ l2_thresholds: dict[str, float] | None = None,
29
+ snt_version: str = "v0.5.1",
30
+ dropout: float = 0.1,
31
+ **kwargs,
32
+ ):
33
+ self.encoder_name = encoder_name
34
+ self.l1_keys = l1_keys or []
35
+ self.l2_keys = l2_keys or []
36
+ self.l2_parent = l2_parent or {}
37
+ self.l1_thresholds = l1_thresholds or {}
38
+ self.l2_thresholds = l2_thresholds or {}
39
+ self.snt_version = snt_version
40
+ self.dropout = dropout
41
+ super().__init__(**kwargs)
42
+
43
+ @property
44
+ def n_l1(self) -> int:
45
+ return len(self.l1_keys)
46
+
47
+ @property
48
+ def n_l2(self) -> int:
49
+ return len(self.l2_keys)
50
+
51
+
52
+ class SNTForNewsClassification(PreTrainedModel):
53
+ config_class = SNTConfig
54
+
55
+ def __init__(self, config: SNTConfig):
56
+ super().__init__(config)
57
+ # Attribute names MUST match DualHeadModel so state_dicts load 1:1.
58
+ self.encoder = AutoModel.from_pretrained(config.encoder_name)
59
+ hidden = self.encoder.config.hidden_size
60
+ self.dropout = nn.Dropout(config.dropout)
61
+ self.head_top = nn.Linear(hidden, config.n_l1)
62
+ self.head_sub = nn.Linear(hidden, config.n_l2)
63
+
64
+ def forward(self, input_ids, attention_mask, **kwargs):
65
+ out = self.encoder(input_ids=input_ids, attention_mask=attention_mask)
66
+ pooled = self.dropout(out.last_hidden_state[:, 0, :])
67
+ return {"l1_logits": self.head_top(pooled), "l2_logits": self.head_sub(pooled)}
68
+
69
+ @torch.no_grad()
70
+ def predict_labels(self, input_ids, attention_mask, **kwargs) -> list[dict]:
71
+ """Thresholded multi-label prediction, one dict per batch row.
72
+
73
+ Logits are upcast to fp32 before sigmoid — bf16 sigmoid saturates to
74
+ exactly 1.0 above logit ~6.2, collapsing co-confident categories.
75
+ """
76
+ out = self.forward(input_ids, attention_mask)
77
+ l1_probs = torch.sigmoid(out["l1_logits"].float())
78
+ l2_probs = torch.sigmoid(out["l2_logits"].float())
79
+ results = []
80
+ for row in range(l1_probs.shape[0]):
81
+ l1 = sorted(
82
+ (
83
+ {"key": k, "p": round(float(p), 4)}
84
+ for k, p in zip(self.config.l1_keys, l1_probs[row].tolist())
85
+ if p >= self.config.l1_thresholds.get(k, 0.5)
86
+ ),
87
+ key=lambda hit: -hit["p"],
88
+ )
89
+ if not l1: # argmax fallback — never return unlabeled
90
+ idx = int(l1_probs[row].argmax())
91
+ l1 = [{"key": self.config.l1_keys[idx], "p": round(float(l1_probs[row][idx]), 4)}]
92
+ l2 = sorted(
93
+ (
94
+ {"key": k, "p": round(float(p), 4)}
95
+ for k, p in zip(self.config.l2_keys, l2_probs[row].tolist())
96
+ if p >= self.config.l2_thresholds.get(k, 0.5)
97
+ ),
98
+ key=lambda hit: -hit["p"],
99
+ )
100
+ results.append({"l1": l1, "primary_l1": l1[0]["key"], "l2": l2})
101
+ return results
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:acbd420e2269cdc1ef45332d3d5c418be4aef6b8cb5a0b7ccae0893485307153
3
+ size 17098086
tokenizer_config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": true,
3
+ "backend": "tokenizers",
4
+ "bos_token": "<s>",
5
+ "cls_token": "<s>",
6
+ "eos_token": "</s>",
7
+ "is_local": true,
8
+ "local_files_only": false,
9
+ "mask_token": "<mask>",
10
+ "model_max_length": 512,
11
+ "pad_token": "<pad>",
12
+ "sep_token": "</s>",
13
+ "tokenizer_class": "XLMRobertaTokenizer",
14
+ "unk_token": "<unk>"
15
+ }