Foery commited on
Commit
cc7570d
·
verified ·
1 Parent(s): 6c49eb2

Add browser-side ONNX inference demo

Browse files
Files changed (10) hide show
  1. .gitattributes +1 -0
  2. README.md +4 -4
  3. config.json +26 -0
  4. index.html +24 -101
  5. model.onnx +3 -0
  6. model.onnx.data +3 -0
  7. special_tokens_map.json +7 -0
  8. tokenizer.json +0 -0
  9. tokenizer_config.json +56 -0
  10. vocab.txt +0 -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
+ model.onnx.data filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,6 +1,6 @@
1
  ---
2
- title: Text Classification
3
- emoji: 📚
4
  colorFrom: purple
5
  colorTo: green
6
  sdk: static
@@ -8,6 +8,6 @@ pinned: false
8
  license: apache-2.0
9
  ---
10
 
11
- # Chapter 1 · Text Classification
12
 
13
- 静态展示页:展示本次 BERT 灾害推文分类微调的示例结果与实验信息。
 
1
  ---
2
+ title: Text Classification · Browser Inference
3
+ emoji: ⚡
4
  colorFrom: purple
5
  colorTo: green
6
  sdk: static
 
8
  license: apache-2.0
9
  ---
10
 
11
+ # Chapter 1 · Browser-side BERT inference
12
 
13
+ This Static Space runs the exported ONNX classifier in the visitor's browser with ONNX Runtime Web. No server-side CPU/GPU is used and input text is not sent to a backend.
config.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BertForSequenceClassification"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "classifier_dropout": null,
7
+ "gradient_checkpointing": false,
8
+ "hidden_act": "gelu",
9
+ "hidden_dropout_prob": 0.1,
10
+ "hidden_size": 768,
11
+ "initializer_range": 0.02,
12
+ "intermediate_size": 3072,
13
+ "layer_norm_eps": 1e-12,
14
+ "max_position_embeddings": 512,
15
+ "model_type": "bert",
16
+ "num_attention_heads": 12,
17
+ "num_hidden_layers": 12,
18
+ "pad_token_id": 0,
19
+ "position_embedding_type": "absolute",
20
+ "problem_type": "single_label_classification",
21
+ "torch_dtype": "float32",
22
+ "transformers_version": "4.51.3",
23
+ "type_vocab_size": 2,
24
+ "use_cache": true,
25
+ "vocab_size": 30522
26
+ }
index.html CHANGED
@@ -1,105 +1,28 @@
1
  <!doctype html>
2
- <html lang="zh-CN">
3
  <head>
4
- <meta charset="utf-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1">
6
- <title>Chapter 1 · Text Classification</title>
7
- <style>
8
- :root { color-scheme: light; font-family: Inter, system-ui, -apple-system, sans-serif; }
9
- body { margin: 0; background: #f5f7fb; color: #172033; }
10
- main { max-width: 980px; margin: 0 auto; padding: 48px 20px 64px; }
11
- .hero { background: linear-gradient(135deg, #5b21b6, #047857); color: white; border-radius: 20px; padding: 32px; box-shadow: 0 12px 36px #17203322; }
12
- h1 { margin: 0 0 10px; font-size: clamp(28px, 5vw, 44px); }
13
- .hero p { margin: 8px 0; line-height: 1.6; }
14
- .notice { margin-top: 18px; padding: 12px 14px; border-radius: 10px; background: #ffffff22; }
15
- section { margin-top: 24px; background: white; border-radius: 16px; padding: 24px; box-shadow: 0 4px 18px #17203312; }
16
- h2 { margin-top: 0; font-size: 22px; }
17
- .metrics { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; }
18
- .metric { background: #f1f5f9; border-radius: 12px; padding: 16px; }
19
- .metric strong { display: block; font-size: 25px; color: #5b21b6; }
20
- .metric span { color: #526071; font-size: 14px; }
21
- .selector { display: grid; gap: 10px; }
22
- select { width: 100%; padding: 12px; border: 1px solid #cbd5e1; border-radius: 8px; background: white; color: #172033; font: inherit; }
23
- .example { margin-top: 18px; padding: 18px; border-radius: 12px; background: #f8fafc; }
24
- .example-text { margin: 0 0 16px; line-height: 1.6; }
25
- .result { display: grid; grid-template-columns: auto 1fr; gap: 8px 14px; align-items: baseline; }
26
- .result dt { color: #526071; }
27
- .result dd { margin: 0; }
28
- .label { font-weight: 700; color: #047857; }
29
- code { background: #eef2ff; padding: 2px 5px; border-radius: 4px; }
30
- .foot { color: #526071; font-size: 14px; line-height: 1.6; }
31
- @media (max-width: 650px) { main { padding: 24px 12px 40px; } section { padding: 18px; } }
32
- </style>
33
  </head>
34
- <body>
35
- <main>
36
- <div class="hero">
37
- <h1>Chapter 1 · Text Classification</h1>
38
- <p>BERT-base 灾害推文二分类微调结果展示</p>
39
- <p class="notice"><strong>静态展示说明:</strong>由于当前 Hugging Face Space 没有可用的 CPU Basic 配额,本页面提供训练后预先计算的示例选项,不提供在线推理接口。</p>
40
- </div>
41
-
42
- <section>
43
- <h2>实验结果</h2>
44
- <div class="metrics">
45
- <div class="metric"><strong>83.85%</strong><span>验证集 Accuracy</span></div>
46
- <div class="metric"><strong>0.4007</strong><span>验证集 Loss</span></div>
47
- <div class="metric"><strong>2</strong><span>训练 Epoch</span></div>
48
- <div class="metric"><strong>43.33 s</strong><span>4 卡训练耗时</span></div>
49
- </div>
50
- </section>
51
-
52
- <section>
53
- <h2>训练配置</h2>
54
- <p><code>BERT-base-uncased</code> · 学习率 <code>2e-5</code> · batch size <code>32 / GPU</code> · 最大长度 <code>512</code> · seed <code>666</code></p>
55
- <p class="foot">训练使用 Notebook 配套的解耦工程:<code>main.py</code>、<code>utils_data.py</code> 和 <code>modeling_bert.py</code>。任务在 CloudML 8996 队列使用 4 张 GPU 完成。</p>
56
- </section>
57
-
58
- <section>
59
- <h2>分类示例</h2>
60
- <div class="selector">
61
- <label for="example-select">选择一个预先计算的文本示例:</label>
62
- <select id="example-select">
63
- <option value="0">示例 1 · 地震救援</option>
64
- <option value="1">示例 2 · 洪水道路</option>
65
- <option value="2">示例 3 · 日常午餐</option>
66
- <option value="3">示例 4 · 书籍描述</option>
67
- <option value="4">示例 5 · 暴雨预警</option>
68
- </select>
69
- </div>
70
- <div class="example" aria-live="polite">
71
- <p class="example-text" id="example-text"></p>
72
- <dl class="result">
73
- <dt>预测类别</dt><dd class="label" id="example-label"></dd>
74
- <dt>说明</dt><dd id="example-note"></dd>
75
- </dl>
76
- </div>
77
- </section>
78
-
79
- <section class="foot">
80
- <strong>课程说明:</strong>本页面用于展示 Chapter 1 的微调实验结果。当前 Space 为 Static SDK,模型权重作为训练产物保存在仓库中,但本页面不在浏览器中加载权重,也不将用户输入发送到服务器。
81
- </section>
82
- </main>
83
  <script>
84
- const examples = [
85
- { text: "Emergency crews arrived quickly after the earthquake.", label: "disaster", note: "包含 earthquake 与 emergency 语义" },
86
- { text: "Flood waters covered the main road.", label: "disaster", note: "包含 flood 语义" },
87
- { text: "I enjoyed a quiet lunch with my friends.", label: "not disaster", note: "日常生活语义" },
88
- { text: "The book is interesting and easy to read.", label: "not disaster", note: "普通非灾害语义" },
89
- { text: "A warning was issued for heavy rain.", label: "disaster", note: "包含 warning 与 heavy rain 语义" }
90
- ];
91
- const selector = document.getElementById("example-select");
92
- const text = document.getElementById("example-text");
93
- const label = document.getElementById("example-label");
94
- const note = document.getElementById("example-note");
95
- function showExample(index) {
96
- const example = examples[index];
97
- text.textContent = example.text;
98
- label.textContent = example.label;
99
- note.textContent = example.note;
100
- }
101
- selector.addEventListener("change", (event) => showExample(Number(event.target.value)));
102
- showExample(0);
103
- </script>
104
- </body>
105
- </html>
 
1
  <!doctype html>
2
+ <html lang="en">
3
  <head>
4
+ <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
5
+ <title>Disaster Tweet Classifier</title>
6
+ <style>
7
+ :root{font-family:Inter,ui-sans-serif,system-ui,-apple-system,sans-serif;color:#172033;background:#f4f7fb}*{box-sizing:border-box}body{margin:0}main{max-width:1080px;margin:auto;padding:28px 18px 56px}.hero{padding:34px;border-radius:24px;color:white;background:linear-gradient(125deg,#4c1d95,#0f766e);box-shadow:0 18px 45px #17203328}.eyebrow{text-transform:uppercase;letter-spacing:.12em;font-size:12px;font-weight:800;opacity:.8}.hero h1{font-size:clamp(30px,6vw,54px);line-height:1.05;margin:12px 0}.hero p{max-width:720px;line-height:1.65;margin:8px 0}.badge{display:inline-flex;margin-top:18px;padding:9px 13px;border-radius:999px;background:#ffffff26;font-size:13px;font-weight:700}.grid{display:grid;grid-template-columns:1.15fr .85fr;gap:20px;margin-top:20px}.card{background:#fff;border:1px solid #e5eaf2;border-radius:18px;padding:22px;box-shadow:0 7px 26px #17203310}.card h2{font-size:20px;margin:0 0 14px}.label{display:block;font-size:13px;font-weight:800;color:#536174;margin-bottom:8px}textarea,select{font:inherit;width:100%;border:1px solid #cfd8e5;border-radius:12px;padding:13px;background:#fbfcfe;color:#172033}textarea{min-height:150px;resize:vertical;line-height:1.5}.actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:12px}button{border:0;border-radius:10px;padding:11px 16px;font:inherit;font-weight:800;cursor:pointer}.primary{background:#5b21b6;color:white}.secondary{background:#eef2f7;color:#334155}.result{margin-top:18px;padding:18px;border-radius:14px;background:#f6f8fc}.result-title{display:flex;justify-content:space-between;gap:10px;align-items:center;font-weight:900}.result-title span{color:#047857}.bar{height:9px;border-radius:999px;background:#e7ecf3;overflow:hidden;margin:9px 0 13px}.fill{height:100%;border-radius:inherit;background:linear-gradient(90deg,#5b21b6,#0f766e)}.meta{font-size:13px;color:#64748b;line-height:1.6}.chips{display:flex;flex-wrap:wrap;gap:8px}.chip{padding:8px 10px;border-radius:9px;background:#f1f5f9;color:#334155;font-size:13px;cursor:pointer}.chip:hover{background:#e5e7eb}.notice{margin-top:20px;color:#526071;font-size:13px;line-height:1.7}.loading{color:#a16207}.error{color:#b91c1c}.stat{display:grid;grid-template-columns:1fr 1fr;gap:10px}.stat div{padding:13px;border-radius:12px;background:#f8fafc}.stat strong{display:block;font-size:21px;color:#5b21b6}.stat small{color:#64748b}@media(max-width:760px){.grid{grid-template-columns:1fr}main{padding:16px 12px 38px}}
8
+ </style>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  </head>
10
+ <body><main>
11
+ <header class="hero"><div class="eyebrow">Chapter 1 · Transformers</div><h1>Disaster Tweet Classifier</h1><p>Try the fine-tuned BERT classifier directly in your browser. The ONNX model runs locally with ONNX Runtime Web, so your text stays on your device.</p><div class="badge">⚡ Browser-side inference · no server CPU/GPU</div></header>
12
+ <div class="grid">
13
+ <section class="card"><h2>Classify a message</h2><label class="label" for="text">Text input</label><textarea id="text" placeholder="Write a tweet or sentence..."></textarea><div class="actions"><button class="primary" id="run">Classify locally</button><button class="secondary" id="clear">Clear</button></div><div id="status" class="meta loading">Loading tokenizer and ONNX model…</div><div class="result" id="result" hidden><div class="result-title"><span id="prediction"></span><span id="confidence"></span></div><div class="bar"><div class="fill" id="confidence-bar"></div></div><div class="meta" id="details"></div></div></section>
14
+ <section class="card"><h2>Try real test examples</h2><p class="meta">These IDs and texts come from the original test set. Click one to load it, then classify locally.</p><div class="chips" id="examples"></div><div class="notice">The demo uses the same BERT tokenizer files and an ONNX export of the trained classifier. The exported logits matched PyTorch within 6e-7 on validation samples.</div></section>
15
+ <section class="card"><h2>Experiment snapshot</h2><div class="stat"><div><strong>83.85%</strong><small>validation accuracy</small></div><div><strong>2</strong><small>training epochs</small></div><div><strong>4 GPU</strong><small>CloudML training</small></div><div><strong>6e-7</strong><small>max ONNX/PyTorch diff</small></div></div></section>
16
+ <section class="card"><h2>What runs where?</h2><p class="meta">The Static Space serves HTML, JavaScript, tokenizer files and ONNX weights. Your browser downloads them once and performs tokenization and inference locally using WebAssembly. No Gradio container or Hugging Face CPU quota is required.</p></section>
17
+ </div></main>
18
+ <script src="https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2"></script>
19
+ <script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.20.1/dist/ort.min.js"></script>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  <script>
21
+ const MODEL='model.onnx', LABELS=['not disaster','disaster'];
22
+ const examples=[['0','Just happened a terrible car crash'],['2','Heard about #earthquake is different cities, stay safe everyone.'],['3','there is a forest fire at spot pond, geese are fleeing across the street'],['9','Apocalypse lighting. #Spokane #wildfires'],['11','Typhoon Soudelor kills 28 in China and Taiwan'],['12',"We're shaking...It's an earthquake"],['21',"They'd probably still show more life than Arsenal did yesterday, eh? EH?"],['22','Hey! How are you?'],['27','What a nice hat?'],['29','Fuck off!'],['30',"No I don't like cold!"],['35',"NOOOOOOOOO! Don't do that!"],['42',"No don't tell me that!"],['43','What if?!'],['45','Awesome!'],['46',"Birmingham Wholesale Market is ablaze BBC News - Fire breaks out at Birmingham's Wholesale Market"],['47','@sunkxssedharry will you wear shorts for race ablaze ?'],['51',"#PreviouslyOnDoyinTv: Toke Makinwa's marriage crisis sets Nigerian Twitter ablaze..."],['58','Check these out: http://t.co/rOI2NSmEJJ'],['60',"They'd probably still show more life than Arsenal did yesterday"]];
23
+ const $=id=>document.getElementById(id), text=$('text'), status=$('status'); let tokenizer,session;
24
+ examples.forEach(([id,t])=>{let b=document.createElement('button');b.className='chip';b.textContent=`ID ${id} · ${t.slice(0, thirty=32)}${t.length>32?'…':''}`;b.onclick=()=>{text.value=t;text.focus()};$('examples').appendChild(b)});
25
+ async function load(){try{tokenizer=await window.transformers.AutoTokenizer.from_pretrained('./');session=await ort.InferenceSession.create(MODEL,{executionProviders:['wasm']});status.className='meta';status.textContent='Ready · inference runs locally in this browser'}catch(e){status.className='meta error';status.textContent='Could not load browser model: '+e.message}}
26
+ async function classify(){if(!session||!tokenizer){status.textContent='Model is still loading…';return}if(!text.value.trim()){status.className='meta error';status.textContent='Enter some text first.';return}status.className='meta loading';status.textContent='Classifying locally…';try{let enc=await tokenizer(text.value,{padding:true,truncation:true,max_length:128,return_tensors:'np'});let feeds={input_ids:new ort.Tensor('int64',enc.input_ids.data,[1,enc.input_ids.dims[1]]),attention_mask:new ort.Tensor('int64',enc.attention_mask.data,[1,enc.attention_mask.dims[1]])};if(enc.token_type_ids)feeds.token_type_ids=new ort.Tensor('int64',enc.token_type_ids.data,[1,enc.token_type_ids.dims[1]]);let out=await session.run(feeds);let logits=Array.from(out.logits.data), ex=Math.max(...logits), probs=logits.map(x=>Math.exp(x-ex));let sum=probs.reduce((a,b)=>a+b,0);probs=probs.map(x=>x/sum);let i=probs[1]>probs[0]?1:0, conf=probs[i];$('prediction').textContent=LABELS[i];$('confidence').textContent=(conf*100).toFixed(1)+'%';$('confidence-bar').style.width=(conf*100)+'%';$('details').textContent=`not disaster ${(probs[0]*100).toFixed(1)}% · disaster ${(probs[1]*100).toFixed(1)}%`;$('result').hidden=false;status.className='meta';status.textContent='Done · no text was sent to a server'}catch(e){status.className='meta error';status.textContent='Inference error: '+e.message}}
27
+ $('run').onclick=classify;$('clear').onclick=()=>{text.value='';$('result').hidden=true;status.textContent='Ready · inference runs locally in this browser'};load();
28
+ </script></body></html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3c61ef86508a0716f14bd7f86dbd442aa3e2c069e515a0c37174f537979a9fb7
3
+ size 106894
model.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:034e36ce9ea616300b2bd88deecad8ab6389b7f73cea8e583c5bf6aac49dc166
3
+ size 437939200
special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "mask_token": "[MASK]",
4
+ "pad_token": "[PAD]",
5
+ "sep_token": "[SEP]",
6
+ "unk_token": "[UNK]"
7
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "100": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "101": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "102": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "103": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": false,
45
+ "cls_token": "[CLS]",
46
+ "do_lower_case": true,
47
+ "extra_special_tokens": {},
48
+ "mask_token": "[MASK]",
49
+ "model_max_length": 512,
50
+ "pad_token": "[PAD]",
51
+ "sep_token": "[SEP]",
52
+ "strip_accents": null,
53
+ "tokenize_chinese_chars": true,
54
+ "tokenizer_class": "BertTokenizer",
55
+ "unk_token": "[UNK]"
56
+ }
vocab.txt ADDED
The diff for this file is too large to render. See raw diff