Spaces:
Running
Running
|
Download README.md from WideChaos/tiny-hash-intent: direct link, hf CLI and curl.
- Browser
- Download file 16.8 kB
-
https://huggingface.co/spaces/WideChaos/tiny-hash-intent/resolve/main/README.md
- Command line
-
hf download hf://spaces/WideChaos/tiny-hash-intent/README.md
-
curl -L -o README.md https://huggingface.co/spaces/WideChaos/tiny-hash-intent/resolve/main/README.md
16.8 kB
| title: Tiny Hash Intent | |
| emoji: 🧠 | |
| colorFrom: blue | |
| colorTo: gray | |
| sdk: static | |
| app_file: index.html | |
| license: other | |
| license_name: apache-2.0-code-and-cc-by-4.0-artifacts | |
| license_link: LICENSES.md | |
| short_description: A small from-scratch classifier with local browser inference | |
| # Tiny Hash Intent | |
| ## Why a small classifier? | |
| Imagine two support messages: “The cash machine kept my card” and “The cash machine returned my card, but I did not receive the money.” Both mention a cash machine and a card. They describe different problems, and a support queue needs to keep them apart. These are illustrative requests, not a report of a customer deployment or measured predictions for these exact sentences. | |
| An intent classifier assigns a short label to a message. It does not write an answer or fix the problem. I wanted a small, inspectable example that could learn those labels on a CPU and later run inside a browser. The public BANKING77 dataset provides 77 English request categories for that experiment. | |
| I trained a network from random initialization, using short character patterns as its inputs. The model learns which patterns help distinguish the categories. Its 267,213 learned parameters are the adjustable numbers in that network; no pretrained language model is used. After the initial asset download, the demo computes predictions on the device. Try a message, then inspect or download all 77 class scores. | |
| ## What the experiment taught me | |
| I completed all 30 training epochs and chose epoch 28 using validation loss: a measure of how well the model predicts examples kept out of fitting. I then fixed the model and its score adjustment before this model's first test evaluation. The official 3,080-row test produced 2,779 correct labels and 301 errors. The full errors are part of the release, not discarded examples. I had used this benchmark before, so this is not a historically blind test. | |
| Making the stored weights smaller did not change the number of correct labels, but it changed two individual predictions. Both were wrong before and after, with different wrong labels. A headline accuracy alone would hide that change. The browser uses the compact stored weights, then converts them to floating-point numbers for computation; this is not an integer-kernel speed result. | |
| The most practical limit is visible if you enter an unrelated request. This model still chooses a banking label because it has no “none of the above” detector. A high class score does not establish that the message belongs here. The demo is a reproducible learning experiment, not a bank service, account operation or production routing system. The sections below keep the exact methods, full results and reproduction commands. | |
| A 267,213-parameter character-hash neural classifier trained from scratch on BANKING77, with a portable weight-quantized browser demo. One CPU fit covers 77 English banking intents. The app runs locally after loading a fixed model asset and does not send input text to a model service. | |
| This is a closed-set classifier. Every valid input receives one of the 77 labels, including unrelated requests. It has no OOD detector, abstention threshold, language-generation ability or banking decision authority. Other-language conformance tests verify implementation agreement, not multilingual task competence. | |
| ## Result of this fit | |
| All modes scored the same 3,080 official test rows. The validation-selected temperature is 0.75. | |
| | Representation / temperature | Correct | Accuracy | Macro F1 | NLL | Brier | ECE10 | | |
| | --- | --- | --- | --- | --- | --- | --- | | |
| | Float64 / 1 | 2,779 | 90.2273% | 0.902346 | 0.385961 | 0.154635 | 0.060603 | | |
| | Float64 / 0.75 | 2,779 | 90.2273% | 0.902346 | 0.355679 | 0.146271 | 0.011284 | | |
| | Int8-stored weights / 1 | 2,779 | 90.2273% | 0.902383 | 0.385909 | 0.154600 | 0.060625 | | |
| | Int8-stored weights / 0.75 | 2,779 | 90.2273% | 0.902383 | 0.355596 | 0.146231 | 0.011770 | | |
| One model fit has four representation/post-processing evaluations, not four independent training runs. Quantization changed the predicted labels of test row ids 281 and 562; both were already wrong and remained wrong, with different wrong labels. The identical correct count does not imply identical predictions. All 301 errors, per-class outcomes, two disagreement ids and all 12,320 prediction/metric rows remain available in `evaluation-001/`. | |
| Seven test texts match original training texts after the declared normalization. The complete official score retains them. The separately reported 3,073-row nonoverlap subset has 2,772 correct (90.2050%) in each mode. These literal/normalized checks do not rule out semantic or source-family overlap. | |
| BANKING77 was already used in my earlier Label Budget study, so this is not a historically blind benchmark. This new model's configuration and selection rules were fixed before implementation/fitting, and its selected artifacts were frozen before this model's first test evaluation. The earlier study uses different label budgets; these are not controlled head-to-head scores against it. No significance, general calibration, OOD safety or SOTA claim is made. | |
| ## Run the browser demo | |
| ```sh | |
| python3 -m http.server 8000 --bind 127.0.0.1 | |
| ``` | |
| Open the localhost address. Use a modern browser with ES modules, Unicode normalization, typed arrays, base64 decoding and Web Crypto. HTTPS or localhost is required for the model identity digest. There is no build step or client runtime dependency. Local preparation checks on 2026-11-04 do not include an HF cloud deployment. | |
| The app shows three highest class scores and can switch between raw and validation-selected temperature. It always selects the class using unscaled logits; a positive temperature does not define a new classifier. Inputs over 2,048 UTF-16 units are rejected without truncation. Input edits and temperature changes clear previous results and download links. | |
| The downloaded report includes the exact input text, model-file SHA-256, representation, temperature, logits and all 77 class scores. Review it before sharing. Initial loading fetches fixed local assets, including `run-001/model-int8.json`; subsequent inference does not fetch URLs, call APIs, write storage or send queries. Hosting still receives ordinary asset requests. The model does not operate any bank account or provide financial advice. | |
| ## What is trained | |
| Normalize text with NFC, Unicode lowercase and Python-style whitespace collapse; wrap it in literal `^` and `$`. Count code-point character ngrams of lengths 3, 4 and 5, hash UTF-8 ngrams with unsigned FNV-1a32 into 4,096 bins, and L2-normalize the count vector. Collisions share a feature; there is no vocabulary fit, pretrained tokenizer, IDF or pretrained embedding. | |
| The sparse fixed feature vector feeds learned parameters: | |
| ```text | |
| E: 4096 × 64 | |
| bh: 64 | |
| W: 64 × 77 | |
| bo: 77 | |
| h = tanh(xE + bh) | |
| z = hW + bo | |
| p = stable_softmax(z / T) | |
| ``` | |
| Training uses NumPy Float64 on CPU, seed 123, Gaussian std 0.05 for E then W, zero biases, 30 full epochs and batch size 128. Each epoch shuffles with seed 2026 + epoch. Cross-entropy is regularized by `0.5 * 1e-4 * (sum(E²) + sum(W²))`; biases are not regularized. Adam uses learning rate 0.003, betas 0.9/0.999, epsilon 1e-8 and explicit first/second-moment bias correction. L2 gradients are coupled into Adam; this is not AdamW. All steps and rows are retained. | |
| The actual split has 8,998 fit rows and 1,005 validation rows. Whole normalized-text groups are assigned to validation when the integer SHA-256 group digest modulo ten equals zero. It is a fixed hash split, not inferred document-family metadata or an IID guarantee. All 77 classes have fitting support; full split row ids and per-class support are saved in `PREFIT.json`. | |
| The fit performed 2,130 updates and 269,940 training-row visits. All 30 epochs completed; epoch 28 was selected by minimum uncalibrated validation NLL. The model was not refitted on validation or official test. The complete epoch trace and initial untrained parameter digest are retained. Wall times describe this host, not a portable speed benchmark. | |
|  | |
| ## Calibration and quantization boundaries | |
| After selecting the float model, the fixed grid `[0.5, 0.75, 1, 1.25, 1.5, 2, 3]` was evaluated on validation NLL. Temperature 0.75 won; ties would prefer closest to one, then smaller T. This is a finite grid, not an exact continuous optimum. The int8 representation inherits that temperature; neither the model nor T was tuned on its own test outputs. | |
| The E matrix is symmetrically quantized per row and W per output column. Scales are max-absolute/127 (one for an all-zero slice); rounding is nearest-even, clipped to [-127,127]. Int8 values use base64 two's-complement bytes. Scales and biases remain floating point. | |
| The browser dequantizes those stored weights and performs Float64 arithmetic. It does not use integer-only kernels, quantized activations, GPU acceleration or a faster-inference claim. The saved Float64 NPZ is 2,048,184 bytes; the portable int8 JSON is 473,507 bytes. These are different containers with metadata/compression differences, not a measurement of runtime memory or speed. | |
| Calibration metrics describe these known classes on this one benchmark. NLL uses stable logits without probability clipping. Brier is the multiclass squared probability error. ECE10 uses ten equal-width top-confidence bins, with empty-bin means recorded as null. Its value depends on that binning and is not a correctness guarantee for an individual output or an unrelated request. | |
| Method references: [Kingma and Ba, Adam](https://arxiv.org/abs/1412.6980), [Guo et al., On Calibration of Modern Neural Networks](https://arxiv.org/abs/1706.04599). The explicit formulas and finite grid in `PROTOCOL.md` define this implementation; this is not a reproduction of those papers' benchmark experiments. | |
| ## Data and license | |
| Original data belongs to PolyAI and the BANKING77 authors: Iñigo Casanueva, Tadas Temcinas, Daniela Gerz, Matthew Henderson and Ivan Vulić, 2020, [Efficient Intent Detection with Dual Sentence Encoders](https://arxiv.org/abs/2003.04807). Sources: [author repository](https://github.com/PolyAI-LDN/task-specific-datasets), [HF dataset card](https://huggingface.co/datasets/PolyAI/banking77). | |
| The original 10,003/3,080 train/test CSVs, category list and CC BY 4.0 license are unmodified. Exact original commit/file hashes and reuse provenance are in `data/SOURCE.json`. This is the same public dataset used in the prior study, not a newly collected corpus. Category ids follow the original `categories.json` order, not HF's alphabetic encoding; row ids are zero-based CSV records after the header, not physical line numbers. | |
| The code is Apache 2.0. Original data, saved weights and derived experimental artifacts retain CC BY 4.0 attribution as specified in `LICENSES.md`, `NOTICE` and the original bundled data license. No dataset ownership or PolyAI endorsement is claimed. No employer material, private records, external model weights or paid inference resources were used. | |
| ## Reproduce | |
| ```sh | |
| python3 -m venv .venv | |
| .venv/bin/python -m pip install -r requirements.txt | |
| .venv/bin/python -m unittest test_model -v | |
| OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 VECLIB_MAXIMUM_THREADS=1 .venv/bin/python train.py --data data --output fresh-run | |
| .venv/bin/python evaluate.py --data data --run fresh-run --output fresh-evaluation | |
| .venv/bin/python infer.py 'Where is my card? It has not arrived.' | |
| .venv/bin/python verify_results.py | |
| node test_inference.mjs | |
| .venv/bin/python verify_portable.py | |
| ``` | |
| Use new output directories. Existing runs are not overwritten. The trainer semantically loads original train only; source test bytes may be hashed for provenance. `PREFIT.json` was written before the first update. `PRETEST.json` froze selected model/temperature/quantization/source/code hashes before this model first loaded and scored official test; `EVALUATION-FREEZE.json` records the evaluator and pretest hashes. These local records do not externally attest historical blindness. | |
| The bundled experiment used Python 3.14.7 / NumPy 2.5.4 and capped numerical threads. Node checks used 24.19.0. Different floating algebra or runtime can change near ties; no universal byte-identical prediction promise is made. Keep frozen source/config files unchanged for the hash gates. Tests should run in a copy of a release candidate if regenerating their output fixtures. | |
| The six prefit test groups include finite differences over all parameters of a small network, a hand forward pass, stable loss, Adam first-step correction, feature/Unicode/limits and quantization error bounds. The separate verifier independently rebuilds 22 float/int8 forward rows, twenty Adam steps from closed-form moment sums, and all 12,320 metric rows plus class/subset/ECE counts from saved logits. It retains both quantization disagreements. | |
| Portable conformance tests cover twelve valid ordinary/Unicode/script-shaped/max-length vectors and three rejected inputs in both temperature modes. Actual native browser checks executed all thirty corresponding actions: 24 results and six rejected mode/input combinations, real report download, input-edit export clearing, 390-pixel layout and absence of query requests in the local server log. Browser and Python probabilities agreed within 1e-9; observed maximum difference was 6.67e-16. These are implementation conformance tests, not cross-language task-quality or external adoption evidence. | |
| To regenerate the scientific figure, install `requirements-plot.txt` and run `plot_training.py` with a local `MPLCONFIGDIR`. It uses the noninteractive Agg backend and only saved trace/calibration data; no GUI window is opened. The optional plotting dependency is not needed for inference or training. | |
| ## 中文:先从两条求助说起 | |
| 设想两个人分别说:“取款机把我的卡吞了”和“卡退回来了,但我没拿到钱”。两句话都提到取款机和银行卡,问题却不同。把它们分到合适的类别,就是这次实验要说明的“意图分类”。这是帮助理解的假设场景,不是真实客户案例,也不是对这两句原话的实测结果。 | |
| 我用公开BANKING77的77类英语请求,从随机初值开始,在CPU上训练了一个小网络。它把短字符片段变成可计算的特征,再学习这些特征与类别的关系。页面里的模型不用写回复;你输入一句话,它给出分类和分数,并允许下载完整结果。初次加载固定模型资源之后,分类计算在浏览器本地完成。 | |
| 训练共做完30轮,用留出的验证数据选择第28轮。随后固定模型及分数调整,再评测这个模型的测试结果:3080条中2779条分类正确,301条分错,全部错误保留。这个公开基准在前作里已经用过,不能把本次写成从未见过数据的盲测。 | |
| 一个值得看细节的结果是:把权重压缩为较小的存储形式后,正确总数没变,却有两条原本就分错的请求,换成了另一种错误标签。只看准确率,就看不到这件事。页面里的压缩权重仍会先还原成浮点数再计算,不能据文件变小就宣称推理更快。 | |
| 另一个限制更直接:输入天气或其他不相关内容,它也会硬选一个银行类别。模型没有“以上都不是”的判断,所以高分不等于请求适用,更不代表可以接入银行业务。这个作品交付的是可以检查、重训和试用的小模型实验;下面保留完整方法、失败和许可。 | |
| ## 中文说明 | |
| 这是在公开BANKING77上真实从零CPU训练的小型字符哈希神经分类器,267213个参数,浏览器可本地运行。完整3080条测试中浮点和量化都答对2779条,但两条错误记录换了另一种错误标签,因此不能说量化预测完全一样。完整错误、概率指标和3073条无规范化重复的子集结果均保留。 | |
| 同一训练得到浮点、量化以及不同温度的评测形式,不算四个独立模型。训练与验证方案先固定,30轮全部完成,以验证NLL选第28轮,再用验证集固定温度网格选0.75,之后才测这个模型的测试结果。数据集在前一项目中已用过,不冒称新盲测或新采集资料。 | |
| 模型只有77个英语闭集类别,没有域外拒答能力;中文等输入的一致性检查不代表跨语种分类能力。量化是权重存储形式,浏览器解量化后用浮点计算,不宣传纯整数内核、推理提速或银行业务决策能力。输入仅本地处理,下载报告含原文,分享前应检查。本包记录2026-11-04本地准备,云端公开运行另按实际发布回执核验。 | |