davanstrien HF Staff commited on
Commit
47907a2
·
verified ·
1 Parent(s): cbaff47

Add timm checkpoint (model.safetensors) and timm config; card: Use with timm

Browse files
Files changed (4) hide show
  1. README.md +55 -10
  2. config.json +153 -20
  3. example.py +3 -3
  4. model.safetensors +3 -0
README.md CHANGED
@@ -37,7 +37,7 @@ language:
37
  - zh
38
  - ja
39
  - ko
40
- library_name: onnx
41
  pipeline_tag: image-classification
42
  base_model: timm/mobilenetv4_conv_small.e2400_r224_in1k
43
  tags:
@@ -54,13 +54,13 @@ tags:
54
  > **DRAFT — notes for review (delete this block before release)**
55
  >
56
  > 1. **Licence:** Apache-2.0 is set. Basis, from the licence fields on the Hub as checked on 2026-11-25: backbone `timm/mobilenetv4_conv_small.e2400_r224_in1k` Apache-2.0; the labelling models Valen-Decision-1.5-4B and Intern-Decision-4B Apache-2.0; Synthdog-Multilingual-100 Apache-2.0; FinePDFs ODC-By (attribution, given under Training); the sibling models page-ocr-flags and text-page-filter Apache-2.0. The pages themselves (web PDFs, library scans) carry their own rights, which is why only weights are released. This is a reading of licence fields, not legal advice.
57
- > 2. **Still open:** whether to also ship the PyTorch/timm checkpoint (the GPU speed figure is for PyTorch); the MDPBench and Indra OCR citations are not verified; only one checkpoint (the best of three training seeds on validation pages) was exported.
58
 
59
  # Page script ID
60
 
61
  A small image model that looks at a whole document page and says which writing script it is in, without running OCR. It returns an independent probability for each of 21 scripts, so a page can have two scripts, or none the model is sure of ("unknown"). Use it to route pages to the right OCR model or language pack, to sort a large collection by script, or to find pages whose script does not match their metadata.
62
 
63
- MobileNetV4-conv-small, 2.5M parameters, 10 MB ONNX file. Greyscale page squashed to 640 × 640. 33 ms per page on one CPU thread, 12 ms on four (model only).
64
 
65
  Trained on Hugging Face Jobs: one A10G, about 23 minutes per run. Details are under [Training](#training).
66
 
@@ -75,7 +75,7 @@ pip install onnxruntime pillow numpy
75
  python example.py page.jpg
76
  ```
77
 
78
- It prints the decision (a list of scripts, or `unknown`) and the three highest probabilities. `example.py` reads its settings from `config.json`:
79
 
80
  ```python
81
  import json
@@ -87,8 +87,8 @@ import onnxruntime as ort
87
  from PIL import Image
88
 
89
  HERE = Path(__file__).parent
90
- CFG = json.loads((HERE / "config.json").read_text())
91
- SESSION = ort.InferenceSession(str(HERE / CFG["model_file"]), providers=["CPUExecutionProvider"])
92
 
93
 
94
  def load_page(path):
@@ -101,7 +101,7 @@ def load_page(path):
101
 
102
 
103
  def script_probs(path):
104
- probs = SESSION.run([CFG["output_name"]], {CFG["input_name"]: load_page(path)})[0][0]
105
  return dict(zip(CFG["scripts"], probs.tolist()))
106
 
107
 
@@ -121,6 +121,51 @@ if __name__ == "__main__":
121
 
122
  Preprocessing matters: grey, bilinear squash to 640 × 640 (no crop, no padding), values 0 to 255. Normalisation, the temperature (2.3) and the sigmoid are inside the model, which returns the 21 probabilities directly.
123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  ## How to read the output
125
 
126
  - **Unknown:** the largest probability is below 0.627: an unfamiliar script, not a normal text page, or too hard. Expect this on about 5% of ordinary pages.
@@ -128,7 +173,7 @@ Preprocessing matters: grey, bilinear squash to 640 × 640 (no crop, no padding)
128
  - **Several scripts:** two or more at or above it, usually a mixed page.
129
  - **No text:** not an output of this model. Blank pages usually come out "unknown", but not always. Take "no text" from a separate no-text model, such as the `no_text` output of [page-ocr-flags](https://huggingface.co/small-models-for-glam/page-ocr-flags).
130
 
131
- 0.627 is the value at which 95% of 2,071 validation pages are still answered; the temperature was fitted on the same pages. Both thresholds are in `config.json`: change them there once you have checked them on your own pages.
132
 
133
  **Why 0.55 for the script threshold.** It is the value chosen on the validation pages for this checkpoint. A lower value finds more mixed pages but gives more single-script pages a spurious second script. Computed for this card from the saved predictions on the 2,056 web-PDF test pages (unknown 5.3% in both cases):
134
 
@@ -212,9 +257,9 @@ Model forward pass only, on random input, on a 48-vCPU cloud machine with one A1
212
  |---|---|
213
  | ONNX Runtime, 1 CPU thread, batch 1 | 33.3 ms per page |
214
  | ONNX Runtime, 4 CPU threads, batch 1 | 11.8 ms per page |
215
- | PyTorch, A10G, bf16, batch 64 | 1,771 pages per second |
216
 
217
- CPU times were measured on an earlier export of the same network with the normalisation and temperature outside the graph. The ONNX file gives the same probabilities as the PyTorch checkpoint (largest difference 1.7e-6 on 400 pages).
218
 
219
  ## Training
220
 
 
37
  - zh
38
  - ja
39
  - ko
40
+ library_name: timm
41
  pipeline_tag: image-classification
42
  base_model: timm/mobilenetv4_conv_small.e2400_r224_in1k
43
  tags:
 
54
  > **DRAFT — notes for review (delete this block before release)**
55
  >
56
  > 1. **Licence:** Apache-2.0 is set. Basis, from the licence fields on the Hub as checked on 2026-11-25: backbone `timm/mobilenetv4_conv_small.e2400_r224_in1k` Apache-2.0; the labelling models Valen-Decision-1.5-4B and Intern-Decision-4B Apache-2.0; Synthdog-Multilingual-100 Apache-2.0; FinePDFs ODC-By (attribution, given under Training); the sibling models page-ocr-flags and text-page-filter Apache-2.0. The pages themselves (web PDFs, library scans) carry their own rights, which is why only weights are released. This is a reading of licence fields, not legal advice.
57
+ > 2. **Still open:** the MDPBench and Indra OCR citations are not verified; only one checkpoint (the best of three training seeds on validation pages) was exported.
58
 
59
  # Page script ID
60
 
61
  A small image model that looks at a whole document page and says which writing script it is in, without running OCR. It returns an independent probability for each of 21 scripts, so a page can have two scripts, or none the model is sure of ("unknown"). Use it to route pages to the right OCR model or language pack, to sort a large collection by script, or to find pages whose script does not match their metadata.
62
 
63
+ MobileNetV4-conv-small, 2.5M parameters, 10 MB as ONNX or as timm weights. Greyscale page squashed to 640 × 640. 33 ms per page on one CPU thread, 12 ms on four (model only).
64
 
65
  Trained on Hugging Face Jobs: one A10G, about 23 minutes per run. Details are under [Training](#training).
66
 
 
75
  python example.py page.jpg
76
  ```
77
 
78
+ It prints the decision (a list of scripts, or `unknown`) and the three highest probabilities. `example.py` reads its settings from the `inference` section of `config.json` (the rest of that file is the timm configuration):
79
 
80
  ```python
81
  import json
 
87
  from PIL import Image
88
 
89
  HERE = Path(__file__).parent
90
+ CFG = json.loads((HERE / "config.json").read_text())["inference"] # our settings; the rest is for timm
91
+ SESSION = ort.InferenceSession(str(HERE / CFG["onnx_file"]), providers=["CPUExecutionProvider"])
92
 
93
 
94
  def load_page(path):
 
101
 
102
 
103
  def script_probs(path):
104
+ probs = SESSION.run([CFG["onnx_output_name"]], {CFG["onnx_input_name"]: load_page(path)})[0][0]
105
  return dict(zip(CFG["scripts"], probs.tolist()))
106
 
107
 
 
121
 
122
  Preprocessing matters: grey, bilinear squash to 640 × 640 (no crop, no padding), values 0 to 255. Normalisation, the temperature (2.3) and the sigmoid are inside the model, which returns the 21 probabilities directly.
123
 
124
+ ## Use with timm
125
+
126
+ `model.safetensors` holds the same weights for [timm](https://github.com/huggingface/pytorch-image-models): `mobilenetv4_conv_small` with exactly the 21 script outputs, in the order of `label_names`. It returns logits, with no temperature or sigmoid inside, so apply `sigmoid(logits / 2.3)` yourself. Its input is three channels: the grey page divided by 255, copied to all three channels, then normalised with the ImageNet mean and std in `pretrained_cfg`, exactly as in training. Needs `pip install timm pillow`.
127
+
128
+ ```python
129
+ import json
130
+ import sys
131
+ from pathlib import Path
132
+
133
+ import timm
134
+ import torch
135
+ from huggingface_hub import hf_hub_download
136
+ from PIL import Image
137
+
138
+ model_id = sys.argv[1] # "hf-hub:<namespace>/page-script-id" or "local-dir:/path/to/folder"
139
+ model = timm.create_model(model_id, pretrained=True).eval()
140
+ src, name = model_id.split(":", 1)
141
+ cfg_file = Path(name) / "config.json" if src == "local-dir" else hf_hub_download(name, "config.json")
142
+ INF = json.loads(Path(cfg_file).read_text())["inference"]
143
+ size = model.pretrained_cfg["input_size"][-1]
144
+ mean = torch.tensor(model.pretrained_cfg["mean"]).view(3, 1, 1)
145
+ std = torch.tensor(model.pretrained_cfg["std"]).view(3, 1, 1)
146
+
147
+
148
+ def load_page(path):
149
+ im = Image.open(path)
150
+ if im.format == "JPEG":
151
+ im.draft("L", (2 * size, 2 * size))
152
+ grey = im.convert("L").resize((size, size), Image.BILINEAR) # grey, squash, no crop
153
+ x = torch.frombuffer(bytearray(grey.tobytes()), dtype=torch.uint8).float().view(1, size, size) / 255
154
+ return (x.expand(3, -1, -1) - mean) / std # grey copied to 3 channels, ImageNet mean/std
155
+
156
+
157
+ pages = sys.argv[2:]
158
+ with torch.inference_mode():
159
+ probs = torch.sigmoid(model(torch.stack([load_page(p) for p in pages])) / INF["temperature"])
160
+ for path, p in zip(pages, probs):
161
+ if p.max() < INF["unknown_threshold"]:
162
+ print(path, ["unknown"])
163
+ else:
164
+ print(path, [INF["scripts"][i] for i in p.argsort(descending=True) if p[i] >= INF["script_threshold"]])
165
+ ```
166
+
167
+ Run it as `python run_timm.py hf-hub:<namespace>/page-script-id page.jpg` or with `local-dir:/path/to/folder`. Prefer the ONNX file for CPU pipelines and when you do not want a PyTorch dependency; prefer timm for GPU batches and for fine-tuning.
168
+
169
  ## How to read the output
170
 
171
  - **Unknown:** the largest probability is below 0.627: an unfamiliar script, not a normal text page, or too hard. Expect this on about 5% of ordinary pages.
 
173
  - **Several scripts:** two or more at or above it, usually a mixed page.
174
  - **No text:** not an output of this model. Blank pages usually come out "unknown", but not always. Take "no text" from a separate no-text model, such as the `no_text` output of [page-ocr-flags](https://huggingface.co/small-models-for-glam/page-ocr-flags).
175
 
176
+ 0.627 is the value at which 95% of 2,071 validation pages are still answered; the temperature was fitted on the same pages. Both thresholds are in the `inference` section of `config.json`: change them there once you have checked them on your own pages.
177
 
178
  **Why 0.55 for the script threshold.** It is the value chosen on the validation pages for this checkpoint. A lower value finds more mixed pages but gives more single-script pages a spurious second script. Computed for this card from the saved predictions on the 2,056 web-PDF test pages (unknown 5.3% in both cases):
179
 
 
257
  |---|---|
258
  | ONNX Runtime, 1 CPU thread, batch 1 | 33.3 ms per page |
259
  | ONNX Runtime, 4 CPU threads, batch 1 | 11.8 ms per page |
260
+ | PyTorch (the `model.safetensors` network), A10G, bf16, batch 64 | 1,771 pages per second |
261
 
262
+ CPU times were measured on an earlier export of the same network with the normalisation and temperature outside the graph. `model.onnx` and `model.safetensors` give the same probabilities (largest difference 1.7e-6 on 400 test pages, the same decision on every page).
263
 
264
  ## Training
265
 
config.json CHANGED
@@ -1,23 +1,156 @@
1
  {
2
- "model_file": "model.onnx",
3
- "input_name": "grey",
4
- "output_name": "probabilities",
5
- "input_size": 640,
6
- "input_layout": "float32, N x 640 x 640, grey values 0 to 255 (no channel axis)",
7
- "colour": "greyscale page, one channel",
8
- "resize": "bilinear squash to 640 x 640 (aspect ratio not kept, no crop, no padding)",
9
- "jpeg_draft": "for JPEG input, decode at reduced scale with PIL draft('L', (1280, 1280)) before the resize, as in training",
10
- "inside_the_model": "x / 255, grey copied to three channels, ImageNet mean and std, temperature (2.3), sigmoid",
11
- "output": "N x 21 independent script probabilities, in the order of 'scripts'",
12
- "scripts": ["Arab", "Beng", "Cyrl", "Deva", "Grek", "Hang", "Hani", "Hebr", "Jpan", "Latn", "Taml", "Thai", "Armn", "Ethi", "Geor", "Gujr", "Khmr", "Knda", "Mlym", "Mymr", "Telu"],
13
- "script_names": {
14
- "Arab": "Arabic", "Beng": "Bengali", "Cyrl": "Cyrillic", "Deva": "Devanagari", "Grek": "Greek",
15
- "Hang": "Hangul", "Hani": "Han", "Hebr": "Hebrew", "Jpan": "Japanese", "Latn": "Latin",
16
- "Taml": "Tamil", "Thai": "Thai", "Armn": "Armenian", "Ethi": "Ethiopic", "Geor": "Georgian",
17
- "Gujr": "Gujarati", "Khmr": "Khmer", "Knda": "Kannada", "Mlym": "Malayalam", "Mymr": "Myanmar", "Telu": "Telugu"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  },
19
- "unknown_threshold": 0.6271,
20
- "script_threshold": 0.55,
21
- "mixed_page_threshold": 0.5,
22
- "rule": "if the largest probability is below unknown_threshold, the page is 'unknown'; otherwise report every script with probability >= script_threshold. Use mixed_page_threshold instead when finding mixed-script pages matters more than a clean single answer."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  }
 
1
  {
2
+ "architecture": "mobilenetv4_conv_small",
3
+ "num_classes": 21,
4
+ "num_features": 960,
5
+ "global_pool": "avg",
6
+ "label_names": [
7
+ "Arab",
8
+ "Beng",
9
+ "Cyrl",
10
+ "Deva",
11
+ "Grek",
12
+ "Hang",
13
+ "Hani",
14
+ "Hebr",
15
+ "Jpan",
16
+ "Latn",
17
+ "Taml",
18
+ "Thai",
19
+ "Armn",
20
+ "Ethi",
21
+ "Geor",
22
+ "Gujr",
23
+ "Khmr",
24
+ "Knda",
25
+ "Mlym",
26
+ "Mymr",
27
+ "Telu"
28
+ ],
29
+ "model_args": {
30
+ "num_classes": 21,
31
+ "in_chans": 3,
32
+ "global_pool": "avg"
33
  },
34
+ "pretrained_cfg": {
35
+ "custom_load": false,
36
+ "input_size": [
37
+ 3,
38
+ 640,
39
+ 640
40
+ ],
41
+ "test_input_size": [
42
+ 3,
43
+ 640,
44
+ 640
45
+ ],
46
+ "fixed_input_size": false,
47
+ "interpolation": "bilinear",
48
+ "crop_pct": 1.0,
49
+ "test_crop_pct": 1.0,
50
+ "crop_mode": "squash",
51
+ "mean": [
52
+ 0.485,
53
+ 0.456,
54
+ 0.406
55
+ ],
56
+ "std": [
57
+ 0.229,
58
+ 0.224,
59
+ 0.225
60
+ ],
61
+ "num_classes": 21,
62
+ "pool_size": [
63
+ 20,
64
+ 20
65
+ ],
66
+ "first_conv": "conv_stem",
67
+ "classifier": "classifier",
68
+ "license": "apache-2.0",
69
+ "label_names": [
70
+ "Arab",
71
+ "Beng",
72
+ "Cyrl",
73
+ "Deva",
74
+ "Grek",
75
+ "Hang",
76
+ "Hani",
77
+ "Hebr",
78
+ "Jpan",
79
+ "Latn",
80
+ "Taml",
81
+ "Thai",
82
+ "Armn",
83
+ "Ethi",
84
+ "Geor",
85
+ "Gujr",
86
+ "Khmr",
87
+ "Knda",
88
+ "Mlym",
89
+ "Mymr",
90
+ "Telu"
91
+ ]
92
+ },
93
+ "inference": {
94
+ "onnx_file": "model.onnx",
95
+ "onnx_input_name": "grey",
96
+ "onnx_output_name": "probabilities",
97
+ "input_size": 640,
98
+ "colour": "greyscale page",
99
+ "resize": "bilinear squash to 640 x 640 (aspect ratio not kept, no crop, no padding)",
100
+ "jpeg_draft": "for JPEG input, decode at reduced scale with PIL draft('L', (1280, 1280)) before the resize, as in training",
101
+ "onnx_input": "float32, N x 640 x 640, grey values 0 to 255; normalisation, temperature and sigmoid are inside the ONNX graph; output N x 21 probabilities",
102
+ "timm_input": "float32, N x 3 x 640 x 640: grey / 255 copied to three channels, then (x - mean) / std with the pretrained_cfg mean and std; output N x 21 logits",
103
+ "temperature": 2.3,
104
+ "probability": "timm: sigmoid(logit / temperature) per script (the ONNX file already returns this)",
105
+ "scripts": [
106
+ "Arab",
107
+ "Beng",
108
+ "Cyrl",
109
+ "Deva",
110
+ "Grek",
111
+ "Hang",
112
+ "Hani",
113
+ "Hebr",
114
+ "Jpan",
115
+ "Latn",
116
+ "Taml",
117
+ "Thai",
118
+ "Armn",
119
+ "Ethi",
120
+ "Geor",
121
+ "Gujr",
122
+ "Khmr",
123
+ "Knda",
124
+ "Mlym",
125
+ "Mymr",
126
+ "Telu"
127
+ ],
128
+ "script_names": {
129
+ "Arab": "Arabic",
130
+ "Beng": "Bengali",
131
+ "Cyrl": "Cyrillic",
132
+ "Deva": "Devanagari",
133
+ "Grek": "Greek",
134
+ "Hang": "Hangul",
135
+ "Hani": "Han",
136
+ "Hebr": "Hebrew",
137
+ "Jpan": "Japanese",
138
+ "Latn": "Latin",
139
+ "Taml": "Tamil",
140
+ "Thai": "Thai",
141
+ "Armn": "Armenian",
142
+ "Ethi": "Ethiopic",
143
+ "Geor": "Georgian",
144
+ "Gujr": "Gujarati",
145
+ "Khmr": "Khmer",
146
+ "Knda": "Kannada",
147
+ "Mlym": "Malayalam",
148
+ "Mymr": "Myanmar",
149
+ "Telu": "Telugu"
150
+ },
151
+ "unknown_threshold": 0.6271,
152
+ "script_threshold": 0.55,
153
+ "mixed_page_threshold": 0.5,
154
+ "rule": "if the largest probability is below unknown_threshold, the page is 'unknown'; otherwise report every script with probability >= script_threshold. Use mixed_page_threshold instead when finding mixed-script pages matters more than a clean single answer."
155
+ }
156
  }
example.py CHANGED
@@ -12,8 +12,8 @@ import onnxruntime as ort
12
  from PIL import Image
13
 
14
  HERE = Path(__file__).parent
15
- CFG = json.loads((HERE / "config.json").read_text())
16
- SESSION = ort.InferenceSession(str(HERE / CFG["model_file"]), providers=["CPUExecutionProvider"])
17
 
18
 
19
  def load_page(path):
@@ -26,7 +26,7 @@ def load_page(path):
26
 
27
 
28
  def script_probs(path):
29
- probs = SESSION.run([CFG["output_name"]], {CFG["input_name"]: load_page(path)})[0][0]
30
  return dict(zip(CFG["scripts"], probs.tolist()))
31
 
32
 
 
12
  from PIL import Image
13
 
14
  HERE = Path(__file__).parent
15
+ CFG = json.loads((HERE / "config.json").read_text())["inference"] # our settings; the rest is for timm
16
+ SESSION = ort.InferenceSession(str(HERE / CFG["onnx_file"]), providers=["CPUExecutionProvider"])
17
 
18
 
19
  def load_page(path):
 
26
 
27
 
28
  def script_probs(path):
29
+ probs = SESSION.run([CFG["onnx_output_name"]], {CFG["onnx_input_name"]: load_page(path)})[0][0]
30
  return dict(zip(CFG["scripts"], probs.tolist()))
31
 
32
 
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0914b4a4c45ea78c3566dbe1782ba4ecb42ad2f15f16c95ac49d47d7345e86c5
3
+ size 10206612