Text Classification
Transformers
Safetensors
English
hs6_classifier
feature-extraction
hs-code
hs6
harmonized-system
hts
tariff
tariff-classification
customs
customs-clearance
trade-compliance
import-export
international-trade
logistics
supply-chain
ecommerce
product-classification
product-categorization
multi-class-classification
english
xlm-roberta
bge-m3
custom_code
Instructions to use Kenpache/hs-code-classifier-en with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Kenpache/hs-code-classifier-en with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="Kenpache/hs-code-classifier-en", trust_remote_code=True)# Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("Kenpache/hs-code-classifier-en", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Add files using upload-large-folder tool
Browse files- .gitattributes +1 -0
- README.md +267 -0
- config.json +0 -0
- configuration_hs6.py +37 -0
- model.safetensors +3 -0
- modeling_hs6.py +127 -0
- sentencepiece.bpe.model +3 -0
- special_tokens_map.json +51 -0
- tokenizer.json +3 -0
- tokenizer_config.json +14 -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,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- en
|
| 4 |
+
license: mit
|
| 5 |
+
library_name: transformers
|
| 6 |
+
pipeline_tag: text-classification
|
| 7 |
+
base_model: BAAI/bge-m3
|
| 8 |
+
inference: false
|
| 9 |
+
metrics:
|
| 10 |
+
- accuracy
|
| 11 |
+
- recall
|
| 12 |
+
tags:
|
| 13 |
+
- hs-code
|
| 14 |
+
- hs6
|
| 15 |
+
- harmonized-system
|
| 16 |
+
- hts
|
| 17 |
+
- tariff
|
| 18 |
+
- tariff-classification
|
| 19 |
+
- customs
|
| 20 |
+
- customs-clearance
|
| 21 |
+
- trade-compliance
|
| 22 |
+
- import-export
|
| 23 |
+
- international-trade
|
| 24 |
+
- logistics
|
| 25 |
+
- supply-chain
|
| 26 |
+
- ecommerce
|
| 27 |
+
- product-classification
|
| 28 |
+
- product-categorization
|
| 29 |
+
- text-classification
|
| 30 |
+
- multi-class-classification
|
| 31 |
+
- english
|
| 32 |
+
- xlm-roberta
|
| 33 |
+
- bge-m3
|
| 34 |
+
---
|
| 35 |
+
|
| 36 |
+
# HS Code Classifier (HS6, English)
|
| 37 |
+
|
| 38 |
+
**Give it an English product description, get back the 6-digit Harmonized System (HS)
|
| 39 |
+
code** — the commodity code that drives customs tariff classification, duty rates, HTS
|
| 40 |
+
lookups and trade compliance.
|
| 41 |
+
|
| 42 |
+
```
|
| 43 |
+
"men's cotton knitted t-shirt, short sleeve" → 610910 (0.998)
|
| 44 |
+
"portable laptop computer, 14 inch display, 1.2 kg" → 847130 (0.994)
|
| 45 |
+
"lithium-ion rechargeable battery, 3.7 V, 5000 mAh" → 850760 (0.929)
|
| 46 |
+
"roasted arabica coffee beans, not decaffeinated" → 090121 (0.811)
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
Fine-tuned end-to-end over the full **6,750-class HS6 space** — not a toy subset of
|
| 50 |
+
the most common chapters. HS4 (1,266 headings) and HS2 (97 chapters) come out of the
|
| 51 |
+
same forward pass and are **guaranteed consistent** with the HS6 answer.
|
| 52 |
+
|
| 53 |
+
| | |
|
| 54 |
+
|---|---|
|
| 55 |
+
| **Task** | Product description → HS6 tariff code |
|
| 56 |
+
| **Input language** | **English** |
|
| 57 |
+
| **Label space** | 6,750 HS6 · 1,266 HS4 · 97 HS2 |
|
| 58 |
+
| **Accuracy on full product descriptions** | **71.94% top-1 · 91.08% top-5** |
|
| 59 |
+
| **Parameters** | 573.6M (fp32, 2.2 GB) |
|
| 60 |
+
| **Context window** | 1,024 tokens at inference |
|
| 61 |
+
|
| 62 |
+
What you get depends on what you give it: a full description runs at ~72% top-1, a
|
| 63 |
+
two-word catalogue stub at ~38%. The complete breakdown — by input type, by length, by
|
| 64 |
+
confidence — is right below.
|
| 65 |
+
|
| 66 |
+
---
|
| 67 |
+
|
| 68 |
+
## Accuracy
|
| 69 |
+
|
| 70 |
+
Measured on a frozen held-out test set of **8,065 product descriptions** that has zero
|
| 71 |
+
overlap with training and was never used for tuning any hyperparameter or threshold.
|
| 72 |
+
|
| 73 |
+
### Accuracy depends heavily on how much you tell it
|
| 74 |
+
|
| 75 |
+
This is the single most important table in this card:
|
| 76 |
+
|
| 77 |
+
| Input | Share of test | Top-1 | Top-5 |
|
| 78 |
+
|---|---:|---:|---:|
|
| 79 |
+
| **Full product description** | 35% | **71.94%** | **91.08%** |
|
| 80 |
+
| Short subject line | 22% | 46.34% | 73.17% |
|
| 81 |
+
| Two- or three-word phrase | 43% | 38.01% | 61.70% |
|
| 82 |
+
|
| 83 |
+
By raw character length:
|
| 84 |
+
|
| 85 |
+
| Length | Top-1 |
|
| 86 |
+
|---|---:|
|
| 87 |
+
| 0–40 chars | 39.00% |
|
| 88 |
+
| 40–100 | 45.15% |
|
| 89 |
+
| 100–200 | 46.98% |
|
| 90 |
+
| 200–500 | 73.75% |
|
| 91 |
+
| 500–1500 | **74.72%** |
|
| 92 |
+
| 1500+ | 64.77% |
|
| 93 |
+
|
| 94 |
+
**Do not truncate your inputs.** Material, construction, and intended use are exactly
|
| 95 |
+
the features that separate one subheading from another; `"two folding cots"` does not
|
| 96 |
+
contain them and no model can recover them. Feed the whole description — the spec
|
| 97 |
+
sheet, the paragraph, the invoice line with attributes — and accuracy roughly doubles.
|
| 98 |
+
|
| 99 |
+
### Averaged over the whole benchmark
|
| 100 |
+
|
| 101 |
+
The benchmark is deliberately hostile: 62% of its inputs are under 100 characters, so
|
| 102 |
+
the average is dragged down by fragments that carry no classifiable features at all.
|
| 103 |
+
Averaged over all 8,065 items:
|
| 104 |
+
|
| 105 |
+
| Metric | Score |
|
| 106 |
+
|---|---|
|
| 107 |
+
| HS6 top-1 (exact 6-digit match) | 51.70% |
|
| 108 |
+
| HS4 top-1 (heading) | 60.99% |
|
| 109 |
+
| HS2 top-1 (chapter) | 74.28% |
|
| 110 |
+
| HS6 top-5 recall | 74.48% |
|
| 111 |
+
|
| 112 |
+
Which of the two numbers applies to you is decided by your input, not by the model:
|
| 113 |
+
feed full descriptions and expect the 72% row, feed catalogue stubs and expect the 38%
|
| 114 |
+
row. Nothing is hidden here — both are stated so you can predict your own result
|
| 115 |
+
before you download 2.2 GB.
|
| 116 |
+
|
| 117 |
+
### Confidence is usable as a threshold
|
| 118 |
+
|
| 119 |
+
Top-1 softmax probability is monotonically informative, which makes a
|
| 120 |
+
straight-through / review split practical:
|
| 121 |
+
|
| 122 |
+
| Confidence | Share of traffic | Accuracy |
|
| 123 |
+
|---|---:|---:|
|
| 124 |
+
| 0.8 – 1.0 | 62.8% | 63.7% |
|
| 125 |
+
| 0.6 – 0.8 | 12.6% | 28.4% |
|
| 126 |
+
| 0.4 – 0.6 | 12.3% | 21.6% |
|
| 127 |
+
| 0.2 – 0.4 | 9.1% | 12.0% |
|
| 128 |
+
| 0.0 – 0.2 | 3.2% | 3.1% |
|
| 129 |
+
|
| 130 |
+
With temperature `T ≈ 1.75` applied to the logits, calibration improves further: you
|
| 131 |
+
can auto-accept 41.5% of the flow at 80.0% accuracy. Recommended pattern — auto-clear
|
| 132 |
+
high-confidence items, route the rest to a human with the top-5 list attached
|
| 133 |
+
(top-5 covers 74% of everything and 91% of full descriptions).
|
| 134 |
+
|
| 135 |
+
### Where the errors go
|
| 136 |
+
|
| 137 |
+
| Outcome | Share |
|
| 138 |
+
|---|---:|
|
| 139 |
+
| Correct at top-1 | 51.70% |
|
| 140 |
+
| Correct code present in top-5, but not ranked first | 22.78% |
|
| 141 |
+
| Correct code absent from top-5 | 25.52% |
|
| 142 |
+
|
| 143 |
+
Of the misses, 18.1% stay inside the correct HS4 heading and 26.6% inside the correct
|
| 144 |
+
HS2 chapter — i.e. a large part of the error is near-miss, not nonsense.
|
| 145 |
+
|
| 146 |
+
---
|
| 147 |
+
|
| 148 |
+
## Quick start
|
| 149 |
+
|
| 150 |
+
```bash
|
| 151 |
+
pip install transformers torch sentencepiece
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
Verified on `transformers` 5.5 / `torch` 2.11. The model code uses only long-stable
|
| 155 |
+
`transformers` APIs, so 4.4x and later should work as well.
|
| 156 |
+
|
| 157 |
+
```python
|
| 158 |
+
from transformers import AutoModel, AutoTokenizer
|
| 159 |
+
|
| 160 |
+
REPO = "Kenpache/hs-code-classifier-en"
|
| 161 |
+
model = AutoModel.from_pretrained(REPO, trust_remote_code=True).eval()
|
| 162 |
+
tokenizer = AutoTokenizer.from_pretrained(REPO)
|
| 163 |
+
|
| 164 |
+
model.classify(["men's cotton knitted t-shirt, short sleeve"], tokenizer, top_k=5)
|
| 165 |
+
# [[{'hs6': '610910', 'score': 0.9983},
|
| 166 |
+
# {'hs6': '610990', 'score': 0.0010},
|
| 167 |
+
# {'hs6': '611020', 'score': 0.0005}, ...]]
|
| 168 |
+
```
|
| 169 |
+
|
| 170 |
+
`classify()` batches for you and accepts a list of any length:
|
| 171 |
+
|
| 172 |
+
```python
|
| 173 |
+
codes = model.classify(descriptions, tokenizer, top_k=5, batch_size=32)
|
| 174 |
+
```
|
| 175 |
+
|
| 176 |
+
### On GPU
|
| 177 |
+
|
| 178 |
+
```python
|
| 179 |
+
model = AutoModel.from_pretrained(REPO, trust_remote_code=True).to("cuda").eval()
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
CUDA, Apple Silicon (`mps`) and CPU all work. Roughly 3 GB of VRAM at batch 16 /
|
| 183 |
+
length 1024; about 4 GB of RAM on CPU.
|
| 184 |
+
|
| 185 |
+
**Leave the context window at 1,024 tokens.** It is already the default in
|
| 186 |
+
`config.json`; lowering `recommended_max_length` costs about 2.9 points on texts longer
|
| 187 |
+
than 1,500 characters, and raising it to 2,048 adds nothing.
|
| 188 |
+
|
| 189 |
+
### All three HS levels at once
|
| 190 |
+
|
| 191 |
+
```python
|
| 192 |
+
import torch
|
| 193 |
+
|
| 194 |
+
enc = tokenizer(["woven cotton fabric, dyed, 200 g/m2"], truncation=True,
|
| 195 |
+
max_length=1024, return_tensors="pt")
|
| 196 |
+
with torch.no_grad():
|
| 197 |
+
out = model(**enc)
|
| 198 |
+
|
| 199 |
+
hs6 = model.config.id2label[out.logits.argmax(-1).item()] # '520839'
|
| 200 |
+
hs4 = model.config.id2hs4[out.logits_hs4.argmax(-1).item()] # '5208'
|
| 201 |
+
hs2 = model.config.id2hs2[out.logits_hs2.argmax(-1).item()] # '52'
|
| 202 |
+
```
|
| 203 |
+
|
| 204 |
+
`hs4` and `hs2` are marginals of the same distribution (logsumexp over the children
|
| 205 |
+
of each parent), so **the levels can never contradict each other**: the model cannot
|
| 206 |
+
return heading `6109` and a subheading that lives under `6110`.
|
| 207 |
+
|
| 208 |
+
---
|
| 209 |
+
|
| 210 |
+
## Limitations
|
| 211 |
+
|
| 212 |
+
1. **English only.** The encoder is multilingual, but the head was trained on English
|
| 213 |
+
product descriptions. Other languages are untested and expected to be much weaker.
|
| 214 |
+
2. **HS6 only.** The first six digits are internationally harmonized; national
|
| 215 |
+
8–10 digit tariff lines are out of scope and this model does not predict them.
|
| 216 |
+
3. **Short inputs are hard**, as the tables above show. Under ~40 characters, expect
|
| 217 |
+
~39% top-1.
|
| 218 |
+
4. **Coverage is uneven across the 6,750 classes.** Rarely-seen codes are much weaker
|
| 219 |
+
than the headline number suggests; roughly 3,800 codes carry the bulk of the
|
| 220 |
+
model's competence.
|
| 221 |
+
5. **The ceiling is domain-imposed, not model-imposed.** Identical descriptions
|
| 222 |
+
legitimately receive different codes depending on context (end use, material
|
| 223 |
+
composition, degree of processing), which caps any text-only classifier.
|
| 224 |
+
6. **Not legal or customs advice.** Output is a ranked suggestion. Binding
|
| 225 |
+
classification is a decision of the competent authority. Use this to triage, to
|
| 226 |
+
pre-fill, and to route to a human — not to file unattended.
|
| 227 |
+
|
| 228 |
+
---
|
| 229 |
+
|
| 230 |
+
## Intended use
|
| 231 |
+
|
| 232 |
+
Good fits:
|
| 233 |
+
|
| 234 |
+
- pre-filling HS6 on customs declarations, then human review of low-confidence rows
|
| 235 |
+
- catalogue / marketplace enrichment at scale
|
| 236 |
+
- landed-cost and duty estimation tooling
|
| 237 |
+
- deduplicating and sanity-checking existing classifications (flag rows where the
|
| 238 |
+
model is confident and disagrees)
|
| 239 |
+
|
| 240 |
+
Poor fits: unattended filing, national tariff lines beyond 6 digits, non-English input.
|
| 241 |
+
|
| 242 |
+
---
|
| 243 |
+
|
| 244 |
+
## Files
|
| 245 |
+
|
| 246 |
+
| File | What it is |
|
| 247 |
+
|---|---|
|
| 248 |
+
| `model.safetensors` | weights, fp32, 2.2 GB |
|
| 249 |
+
| `config.json` | encoder config + head config + `id2label` for all 6,750 HS6 codes |
|
| 250 |
+
| `modeling_hs6.py`, `configuration_hs6.py` | model definition (loaded via `trust_remote_code=True`) |
|
| 251 |
+
| `tokenizer.json`, `sentencepiece.bpe.model`, … | XLM-R tokenizer, `model_max_length` 1024 |
|
| 252 |
+
|
| 253 |
+
## License
|
| 254 |
+
|
| 255 |
+
MIT, following the `BAAI/bge-m3` base model.
|
| 256 |
+
|
| 257 |
+
## Citation
|
| 258 |
+
|
| 259 |
+
```bibtex
|
| 260 |
+
@misc{hs6_classifier_en,
|
| 261 |
+
title = {HS Code Classifier (HS6, English)},
|
| 262 |
+
year = {2026},
|
| 263 |
+
note = {XLM-RoBERTa-large (bge-m3) with a flat 6,750-class HS6 head
|
| 264 |
+
and marginalized HS4/HS2 levels},
|
| 265 |
+
url = {https://huggingface.co/Kenpache/hs-code-classifier-en}
|
| 266 |
+
}
|
| 267 |
+
```
|
config.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
configuration_hs6.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Configuration for the HS6 product classifier.
|
| 2 |
+
|
| 3 |
+
Subclasses XLMRobertaConfig, so every encoder field (hidden_size, num_hidden_layers,
|
| 4 |
+
...) keeps its usual name and meaning. Only the classification head and the label
|
| 5 |
+
spaces for the coarser HS levels are added on top.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from transformers.models.xlm_roberta.configuration_xlm_roberta import XLMRobertaConfig
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class HS6ClassifierConfig(XLMRobertaConfig):
|
| 12 |
+
model_type = "hs6_classifier"
|
| 13 |
+
|
| 14 |
+
def __init__(
|
| 15 |
+
self,
|
| 16 |
+
n2: int = 97,
|
| 17 |
+
n4: int = 1266,
|
| 18 |
+
n6: int = 6750,
|
| 19 |
+
head_dropout: float = 0.15,
|
| 20 |
+
pooling: str = "cls",
|
| 21 |
+
recommended_max_length: int = 1024,
|
| 22 |
+
id2hs4=None,
|
| 23 |
+
id2hs2=None,
|
| 24 |
+
**kwargs,
|
| 25 |
+
):
|
| 26 |
+
super().__init__(**kwargs)
|
| 27 |
+
self.n2 = n2
|
| 28 |
+
self.n4 = n4
|
| 29 |
+
self.n6 = n6
|
| 30 |
+
self.head_dropout = head_dropout
|
| 31 |
+
self.pooling = pooling
|
| 32 |
+
# Training used 512 tokens; inference at 1024 is free (the encoder has 8194
|
| 33 |
+
# positions) and worth +2.91 points on texts longer than 1500 characters.
|
| 34 |
+
self.recommended_max_length = recommended_max_length
|
| 35 |
+
# HS4 / HS2 code strings, indexed by class id. Used to name the marginal logits.
|
| 36 |
+
self.id2hs4 = id2hs4 or []
|
| 37 |
+
self.id2hs2 = id2hs2 or []
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f15e074dc16b5869c4a855fb32e891fde314158af9ea916eb69fbc64d1ba8202
|
| 3 |
+
size 2294652304
|
modeling_hs6.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""HS6 product classifier: XLM-RoBERTa encoder + one flat linear head.
|
| 2 |
+
|
| 3 |
+
HS4 and HS2 are not separate heads. They are marginals of the same HS6
|
| 4 |
+
distribution (logsumexp over the children of each parent), so the levels are
|
| 5 |
+
consistent by construction: the model cannot name one heading at 4 digits and a
|
| 6 |
+
code from a different heading at 6 digits.
|
| 7 |
+
|
| 8 |
+
The forward pass below must stay identical to the one used in training,
|
| 9 |
+
otherwise the released weights do not mean what the metrics say they mean.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from dataclasses import dataclass
|
| 13 |
+
from typing import List, Optional
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torch.nn as nn
|
| 17 |
+
from transformers.modeling_outputs import ModelOutput
|
| 18 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 19 |
+
from transformers.models.xlm_roberta.configuration_xlm_roberta import XLMRobertaConfig
|
| 20 |
+
from transformers.models.xlm_roberta.modeling_xlm_roberta import XLMRobertaModel
|
| 21 |
+
|
| 22 |
+
from .configuration_hs6 import HS6ClassifierConfig
|
| 23 |
+
|
| 24 |
+
# fields that belong to the classifier, not to the encoder
|
| 25 |
+
_HEAD_ONLY = ("n2", "n4", "n6", "head_dropout", "pooling", "recommended_max_length",
|
| 26 |
+
"id2hs4", "id2hs2", "id2label", "label2id", "auto_map", "architectures",
|
| 27 |
+
"model_type")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _encoder_config(config: HS6ClassifierConfig) -> XLMRobertaConfig:
|
| 31 |
+
"""A plain XLM-R config, so the encoder does not warn about the wrapper type."""
|
| 32 |
+
raw = {k: v for k, v in config.to_dict().items() if k not in _HEAD_ONLY}
|
| 33 |
+
return XLMRobertaConfig(**raw)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@dataclass
|
| 37 |
+
class HS6ClassifierOutput(ModelOutput):
|
| 38 |
+
"""`logits` is the HS6 level, so the standard text-classification tooling works.
|
| 39 |
+
|
| 40 |
+
`logits_hs4` / `logits_hs2` are the marginals over the same distribution.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
loss: Optional[torch.FloatTensor] = None
|
| 44 |
+
logits: Optional[torch.FloatTensor] = None
|
| 45 |
+
logits_hs4: Optional[torch.FloatTensor] = None
|
| 46 |
+
logits_hs2: Optional[torch.FloatTensor] = None
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class HS6ClassifierModel(PreTrainedModel):
|
| 50 |
+
config_class = HS6ClassifierConfig
|
| 51 |
+
base_model_prefix = "encoder"
|
| 52 |
+
supports_gradient_checkpointing = True
|
| 53 |
+
|
| 54 |
+
def __init__(self, config: HS6ClassifierConfig):
|
| 55 |
+
super().__init__(config)
|
| 56 |
+
# no pooling layer: the head reads the CLS token of the last hidden state
|
| 57 |
+
self.encoder = XLMRobertaModel(_encoder_config(config), add_pooling_layer=False)
|
| 58 |
+
self.pooling = config.pooling
|
| 59 |
+
self.drop = nn.Dropout(config.head_dropout)
|
| 60 |
+
self.head_6 = nn.Linear(config.hidden_size, config.n6)
|
| 61 |
+
self.n4, self.n2 = config.n4, config.n2
|
| 62 |
+
# parent of every HS6 class: its first 4 and first 2 digits. Stored in the
|
| 63 |
+
# checkpoint so the mapping cannot drift away from the trained weights.
|
| 64 |
+
self.register_buffer("parent4", torch.zeros(config.n6, dtype=torch.long))
|
| 65 |
+
self.register_buffer("parent2", torch.zeros(config.n6, dtype=torch.long))
|
| 66 |
+
self.post_init()
|
| 67 |
+
|
| 68 |
+
def _marginal(self, l6, parent, n_parent):
|
| 69 |
+
mx = l6.max(1, keepdim=True).values
|
| 70 |
+
e = (l6 - mx).exp()
|
| 71 |
+
s = torch.zeros(l6.size(0), n_parent, device=l6.device, dtype=e.dtype)
|
| 72 |
+
s.index_add_(1, parent, e)
|
| 73 |
+
return s.clamp_min(1e-20).log() + mx
|
| 74 |
+
|
| 75 |
+
def forward(
|
| 76 |
+
self,
|
| 77 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 78 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 79 |
+
labels: Optional[torch.LongTensor] = None,
|
| 80 |
+
return_dict: Optional[bool] = None,
|
| 81 |
+
**kwargs,
|
| 82 |
+
):
|
| 83 |
+
return_dict = True if return_dict is None else return_dict
|
| 84 |
+
out = self.encoder(input_ids=input_ids, attention_mask=attention_mask)
|
| 85 |
+
|
| 86 |
+
if self.pooling == "mean":
|
| 87 |
+
h = out.last_hidden_state
|
| 88 |
+
m = attention_mask.unsqueeze(-1).to(h.dtype)
|
| 89 |
+
pooled = (h * m).sum(1) / m.sum(1).clamp(min=1)
|
| 90 |
+
else:
|
| 91 |
+
pooled = out.last_hidden_state[:, 0, :]
|
| 92 |
+
|
| 93 |
+
l6 = self.head_6(self.drop(pooled))
|
| 94 |
+
l4 = self._marginal(l6, self.parent4, self.n4)
|
| 95 |
+
l2 = self._marginal(l6, self.parent2, self.n2)
|
| 96 |
+
|
| 97 |
+
loss = None
|
| 98 |
+
if labels is not None:
|
| 99 |
+
loss = nn.functional.cross_entropy(l6, labels)
|
| 100 |
+
|
| 101 |
+
if not return_dict:
|
| 102 |
+
return (loss, l6, l4, l2) if loss is not None else (l6, l4, l2)
|
| 103 |
+
return HS6ClassifierOutput(loss=loss, logits=l6, logits_hs4=l4, logits_hs2=l2)
|
| 104 |
+
|
| 105 |
+
@torch.no_grad()
|
| 106 |
+
def classify(self, texts, tokenizer, top_k: int = 5, batch_size: int = 16,
|
| 107 |
+
max_length: Optional[int] = None) -> List[List[dict]]:
|
| 108 |
+
"""Convenience wrapper: texts in, ranked HS6 codes with probabilities out."""
|
| 109 |
+
if isinstance(texts, str):
|
| 110 |
+
texts = [texts]
|
| 111 |
+
max_length = max_length or self.config.recommended_max_length
|
| 112 |
+
device = next(self.parameters()).device
|
| 113 |
+
results = []
|
| 114 |
+
for start in range(0, len(texts), batch_size):
|
| 115 |
+
chunk = [t if isinstance(t, str) and t.strip() else " "
|
| 116 |
+
for t in texts[start:start + batch_size]]
|
| 117 |
+
enc = tokenizer(chunk, truncation=True, max_length=max_length,
|
| 118 |
+
padding=True, return_tensors="pt").to(device)
|
| 119 |
+
logits = self(**enc).logits
|
| 120 |
+
probs = torch.softmax(logits.float(), dim=1)
|
| 121 |
+
conf, idx = probs.topk(min(top_k, probs.size(1)), dim=1)
|
| 122 |
+
for c, i in zip(conf.cpu().tolist(), idx.cpu().tolist()):
|
| 123 |
+
results.append([
|
| 124 |
+
{"hs6": self.config.id2label[j], "score": round(v, 6)}
|
| 125 |
+
for j, v in zip(i, c)
|
| 126 |
+
])
|
| 127 |
+
return results
|
sentencepiece.bpe.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cfc8146abe2a0488e9e2a0c56de7952f7c11ab059eca145a0a727afce0db2865
|
| 3 |
+
size 5069051
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token": {
|
| 3 |
+
"content": "<s>",
|
| 4 |
+
"lstrip": false,
|
| 5 |
+
"normalized": false,
|
| 6 |
+
"rstrip": false,
|
| 7 |
+
"single_word": false
|
| 8 |
+
},
|
| 9 |
+
"cls_token": {
|
| 10 |
+
"content": "<s>",
|
| 11 |
+
"lstrip": false,
|
| 12 |
+
"normalized": false,
|
| 13 |
+
"rstrip": false,
|
| 14 |
+
"single_word": false
|
| 15 |
+
},
|
| 16 |
+
"eos_token": {
|
| 17 |
+
"content": "</s>",
|
| 18 |
+
"lstrip": false,
|
| 19 |
+
"normalized": false,
|
| 20 |
+
"rstrip": false,
|
| 21 |
+
"single_word": false
|
| 22 |
+
},
|
| 23 |
+
"mask_token": {
|
| 24 |
+
"content": "<mask>",
|
| 25 |
+
"lstrip": true,
|
| 26 |
+
"normalized": false,
|
| 27 |
+
"rstrip": false,
|
| 28 |
+
"single_word": false
|
| 29 |
+
},
|
| 30 |
+
"pad_token": {
|
| 31 |
+
"content": "<pad>",
|
| 32 |
+
"lstrip": false,
|
| 33 |
+
"normalized": false,
|
| 34 |
+
"rstrip": false,
|
| 35 |
+
"single_word": false
|
| 36 |
+
},
|
| 37 |
+
"sep_token": {
|
| 38 |
+
"content": "</s>",
|
| 39 |
+
"lstrip": false,
|
| 40 |
+
"normalized": false,
|
| 41 |
+
"rstrip": false,
|
| 42 |
+
"single_word": false
|
| 43 |
+
},
|
| 44 |
+
"unk_token": {
|
| 45 |
+
"content": "<unk>",
|
| 46 |
+
"lstrip": false,
|
| 47 |
+
"normalized": false,
|
| 48 |
+
"rstrip": false,
|
| 49 |
+
"single_word": false
|
| 50 |
+
}
|
| 51 |
+
}
|
tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5df1f55d60c9705a501ab9a75550728625740741fe4be308dac4806c16b7d51d
|
| 3 |
+
size 17098085
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_prefix_space": true,
|
| 3 |
+
"bos_token": "<s>",
|
| 4 |
+
"clean_up_tokenization_spaces": true,
|
| 5 |
+
"cls_token": "<s>",
|
| 6 |
+
"eos_token": "</s>",
|
| 7 |
+
"mask_token": "<mask>",
|
| 8 |
+
"model_max_length": 1024,
|
| 9 |
+
"pad_token": "<pad>",
|
| 10 |
+
"sep_token": "</s>",
|
| 11 |
+
"sp_model_kwargs": {},
|
| 12 |
+
"tokenizer_class": "XLMRobertaTokenizer",
|
| 13 |
+
"unk_token": "<unk>"
|
| 14 |
+
}
|