@yaks/model2vec 0.0.0-stage → 0.2.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +86 -2
- package/_dist/graph.d.ts +3 -0
- package/_dist/graph.d.ts.map +1 -0
- package/_dist/mod.d.ts +80 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/table.d.ts +19 -0
- package/_dist/table.d.ts.map +1 -0
- package/deno.json +1 -0
- package/graph.js +16 -0
- package/graph.js.map +1 -0
- package/graph.ts +17 -0
- package/mod.js +134 -0
- package/mod.js.map +1 -0
- package/mod.ts +199 -0
- package/package.json +20 -4
- package/table.js +56 -0
- package/table.js.map +1 -0
- package/table.ts +70 -0
- package/testing.ts +86 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Jeff Peterson
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,87 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @yaks/model2vec
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Embeds text in-process with a
|
|
4
|
+
[Model2Vec](https://github.com/MinishLab/model2vec) static model. A static model
|
|
5
|
+
is a table with one vector per token; a text's vector is the mean of its tokens'
|
|
6
|
+
rows, at length 1. That is a tokenizer pass and a sum: about a millisecond for a
|
|
7
|
+
500-token text on one core, with no native code, no thread pool, and no network
|
|
8
|
+
once the model is loaded. The same code runs on a server, in a Worker and in a
|
|
9
|
+
browser tab, and answers the same vector in each; it matches Model2Vec's own
|
|
10
|
+
`encode` exactly.
|
|
11
|
+
|
|
12
|
+
What a static model gives up against a transformer is context: a token means the
|
|
13
|
+
same thing wherever it stands, and a long text's mean says less than a short
|
|
14
|
+
one's.
|
|
15
|
+
|
|
16
|
+
## Use
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { model2vec } from '@yaks/model2vec'
|
|
20
|
+
|
|
21
|
+
let embedder = model2vec({
|
|
22
|
+
model: 'minishlab/potion-retrieval-32M@6fc8051',
|
|
23
|
+
dim: 256,
|
|
24
|
+
})
|
|
25
|
+
// let v = await embedder.embed('a dragon asleep on its gold')
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
`model2vec()` answers an embedder in the shape [@yaks/embedding](../embedding)
|
|
29
|
+
takes, `{ model, embed }`. Nothing is fetched until the first embed, which waits
|
|
30
|
+
for the model; every embed after it is synchronous. The model's `tokenizer.json`
|
|
31
|
+
and `model.safetensors` come from the Hugging Face hub and are kept in the
|
|
32
|
+
platform's `caches`, so a later process reads them from disk. The same model
|
|
33
|
+
named twice in one process is loaded once. A load that fails rejects the embeds
|
|
34
|
+
waiting on it and is tried again on the next.
|
|
35
|
+
|
|
36
|
+
| Option | Meaning |
|
|
37
|
+
| ------- | ---------------------------------------------------------------------- |
|
|
38
|
+
| `model` | the hub repo, pinned to a revision: `owner/name@rev` |
|
|
39
|
+
| `dim` | keep this many leading columns of the table (default: all) |
|
|
40
|
+
| `max` | read at most this many tokens of a text (default 512, Model2Vec's own) |
|
|
41
|
+
| `hub` | the hub's root (default `https://huggingface.co`) |
|
|
42
|
+
| `fetch` | the fetch to call through (default: the global one) |
|
|
43
|
+
|
|
44
|
+
Pin the revision. An unpinned `model` fetches `main` once and keeps what it got,
|
|
45
|
+
so two machines can hold two different models under one name. The embedder's
|
|
46
|
+
`model`, the name every stored vector carries, is the pinned repo and its width:
|
|
47
|
+
`minishlab/potion-retrieval-32M@6fc8051#256`.
|
|
48
|
+
|
|
49
|
+
`dim` works because a Model2Vec table's columns come out of a PCA, most variance
|
|
50
|
+
first: its leading columns are the model at a smaller width, the way Model2Vec's
|
|
51
|
+
own `dimensionality` loads one. The narrower table is what is kept in memory.
|
|
52
|
+
|
|
53
|
+
## As @yaks/embedding's embedder
|
|
54
|
+
|
|
55
|
+
`@yaks/model2vec/graph` lends its host the embedder `model2vec` (@yaks/host
|
|
56
|
+
`embedders`). Compose the plugin beside @yaks/embedding and name it there:
|
|
57
|
+
|
|
58
|
+
```json
|
|
59
|
+
[
|
|
60
|
+
"@yaks/model2vec",
|
|
61
|
+
{
|
|
62
|
+
"use": "@yaks/embedding",
|
|
63
|
+
"with": {
|
|
64
|
+
"embedder": {
|
|
65
|
+
"provider": "model2vec",
|
|
66
|
+
"model": "minishlab/potion-retrieval-32M@6fc8051",
|
|
67
|
+
"dim": 256
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
]
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Pieces
|
|
75
|
+
|
|
76
|
+
- `load(model, files, { dim?, max? })` builds the embedder from the two files
|
|
77
|
+
already in hand.
|
|
78
|
+
- `embedder(model, encode, table, { max?, chars?, unk? })` is the arithmetic
|
|
79
|
+
over any tokenizer's ids and a token table.
|
|
80
|
+
- `table(bytes, dim?)` reads the `embeddings` tensor of a safetensors file. A
|
|
81
|
+
file in a newer layout (per-token weights, a vocabulary mapping) or of another
|
|
82
|
+
dtype than F32 is refused rather than read wrong.
|
|
83
|
+
- `space(said)` is the name a config's vectors live under.
|
|
84
|
+
|
|
85
|
+
Tokenizing is
|
|
86
|
+
[@huggingface/tokenizers](https://www.npmjs.com/package/@huggingface/tokenizers),
|
|
87
|
+
loaded with the first model.
|
package/_dist/graph.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"graph.d.ts","sources":["../graph.ts"],"names":[],"mappings":"AAWA,SAAS,KAAK,QAAQ,EAAE,KAAK,SAAS,mBAA6B;AAEnE,4EAA4E,GAC5E,OAAO,YAAI,iBAAgB,OAAO,MAAM,GAAG,MAAM,cAAc,UAE7D"}
|
package/_dist/mod.d.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @yaks/model2vec — an embedder fast enough to run on every prompt: a
|
|
3
|
+
* {@link https://github.com/MinishLab/model2vec | Model2Vec} static model,
|
|
4
|
+
* in-process, in plain TypeScript.
|
|
5
|
+
*
|
|
6
|
+
* A static model is a table with one vector per token. A text's vector is the
|
|
7
|
+
* mean of its tokens' rows, normalized: a tokenizer pass and a sum, about a
|
|
8
|
+
* millisecond for 500 tokens on one core, with no native code, no thread pool
|
|
9
|
+
* and no network once the model is loaded. It runs wherever a web platform
|
|
10
|
+
* does — a server, a Worker, a browser tab — and answers the same vector in
|
|
11
|
+
* each. What it gives up against a transformer is context: every token means
|
|
12
|
+
* the same thing wherever it stands.
|
|
13
|
+
*
|
|
14
|
+
* {@link model2vec} names a model on the Hugging Face hub and answers an
|
|
15
|
+
* embedder for it; the model is fetched on the first embed and kept in the
|
|
16
|
+
* platform's `caches`, so a later process reads it from disk. {@link embedder}
|
|
17
|
+
* is the same thing over a tokenizer and a table already in hand.
|
|
18
|
+
*
|
|
19
|
+
* ```ts
|
|
20
|
+
* import { assert, assertEquals } from '@std/assert'
|
|
21
|
+
* import { files } from './testing.ts' // a tokenizer.json and a table
|
|
22
|
+
* let e = await load('tiny', files)
|
|
23
|
+
* let [a, b, c] = ['a red dragon', 'dragon, red', 'a blue whale'].map(e.embed)
|
|
24
|
+
* let dot = (x: Float32Array, y: Float32Array) => x.reduce((s, v, i) => s + v * y[i], 0)
|
|
25
|
+
* assert(dot(a, b) > 0.99 && dot(a, c) < 0.5)
|
|
26
|
+
* assertEquals(e.model, 'tiny')
|
|
27
|
+
* ```
|
|
28
|
+
*
|
|
29
|
+
* @module
|
|
30
|
+
*/ import { type Table, table } from "./table.js";
|
|
31
|
+
export { type Table, table };
|
|
32
|
+
/** Text in, vector out, and the name of the space the vectors live in: the
|
|
33
|
+
* shape @yaks/embedding takes. */ export type Embedder = {
|
|
34
|
+
model: string;
|
|
35
|
+
embed: (text: string) => Float32Array | Promise<Float32Array>;
|
|
36
|
+
};
|
|
37
|
+
/** A text as token ids, without special tokens. */ export type Encode = (text: string) => number[];
|
|
38
|
+
/** How much of a text is read by default, in tokens: Model2Vec's own default.
|
|
39
|
+
* A static model's mean dilutes as a text grows, so a longer window reads
|
|
40
|
+
* more and says less. */ export declare let MAX: number;
|
|
41
|
+
/** What a text is read as. `unk` is dropped, as Model2Vec drops it; `chars`
|
|
42
|
+
* cuts the text before tokenizing, so a long one costs no more than its
|
|
43
|
+
* window. */ export type Window = {
|
|
44
|
+
max?: number;
|
|
45
|
+
chars?: number;
|
|
46
|
+
unk?: number;
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* An embedder over a tokenizer and a token table: the mean of the rows of a
|
|
50
|
+
* text's first `max` tokens, at length 1. A text with no known tokens embeds to
|
|
51
|
+
* the zero vector, which is unrelated to everything.
|
|
52
|
+
*/ export declare let embedder: (model: string, encode: Encode, t: Table, _dts_1: never) => {
|
|
53
|
+
model: string;
|
|
54
|
+
embed: (text: string) => Float32Array;
|
|
55
|
+
};
|
|
56
|
+
/** A Model2Vec model on the hub, as a config names one. */ export type Model2Vec = {
|
|
57
|
+
/** the hub repo, pinned to a revision: `minishlab/potion-retrieval-32M@6fc8051`.
|
|
58
|
+
* Unpinned, the first revision this machine fetches is the one it keeps. */ model: string;
|
|
59
|
+
/** keep this many leading columns of the table (default: all of them) */ dim?: number;
|
|
60
|
+
/** read at most this many tokens of a text (default {@link MAX}) */ max?: number;
|
|
61
|
+
/** the hub (default https://huggingface.co) */ hub?: string;
|
|
62
|
+
/** the fetch to call through (default: the global one) */ fetch?: typeof fetch;
|
|
63
|
+
};
|
|
64
|
+
/** The space a config's vectors live in: the pinned model, and its width when
|
|
65
|
+
* it is cut, since two widths of one model are two spaces. */ export declare let space: (said: Model2Vec) => string;
|
|
66
|
+
/** The model's own files, read into an embedder. */ export declare let load: (model: string, files: {
|
|
67
|
+
tokenizer: Uint8Array;
|
|
68
|
+
safetensors: Uint8Array;
|
|
69
|
+
}, _dts_2: never) => Promise<{
|
|
70
|
+
model: string;
|
|
71
|
+
embed: (text: string) => Float32Array;
|
|
72
|
+
}>;
|
|
73
|
+
/**
|
|
74
|
+
* An embedder for a Model2Vec model on the hub. Nothing is fetched until the
|
|
75
|
+
* first embed; that one waits for the model, and every one after is
|
|
76
|
+
* synchronous. The same model named again in this process is the one already
|
|
77
|
+
* loaded. A load that fails rejects the embeds waiting on it and is tried
|
|
78
|
+
* again on the next.
|
|
79
|
+
*/ export declare let model2vec: (said: Model2Vec) => Embedder;
|
|
80
|
+
//# sourceMappingURL=mod.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mod.d.ts","sources":["../mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BC,GAED,SAAS,KAAK,KAAK,EAAE,KAAK,qBAAoB;AAE9C,SAAS,KAAK,KAAK,EAAE,KAAK,GAAE;AAE5B;gCACgC,GAChC,YAAY;EACV,OAAO,MAAM;EACb,QAAQ,MAAM,MAAM,KAAK,eAAe,QAAQ;;AAGlD,iDAAiD,GACjD,YAAY,UAAU,MAAM,MAAM,KAAK,MAAM;AAE7C;;uBAEuB,GACvB,OAAO,YAAI,YAAS;AAEpB;;WAEW,GACX,YAAY;EAAW,MAAM,MAAM;EAAE,QAAQ,MAAM;EAAE,MAAM,MAAM;;AAEjE;;;;CAIC,GACD,OAAO,YAAI,WACT,OAAO,MAAM,EACb,QAAQ,QACR,GAAG,OACH;EACG,OAAO,MAAM;EAAE,QAAQ,MAAM,MAAM,KAAK;EAiB3C;AAEF,yDAAyD,GACzD,YAAY;EACV;4EAC0E,GAC1E,OAAO,MAAM;EACb,uEAAuE,GACvE,MAAM,MAAM;EACZ,kEAAkE,GAClE,MAAM,MAAM;EACZ,6CAA6C,GAC7C,MAAM,MAAM;EACZ,wDAAwD,GACxD,eAAe;;AAGjB;4DAC4D,GAC5D,OAAO,YAAI,QAAS,MAAM,cAAY,MAAM,CACS;AA8BrD,kDAAkD,GAClD,OAAO,YAAI,OACT,OAAO,MAAM,EACb;EAAS,WAAW;EAAY,aAAa;GAC7C,kBACC;EAAU,OAAO,MAAM;EAAE,QAAQ,MAAM,MAAM,KAAK;GAepD;AASD;;;;;;CAMC,GACD,OAAO,YAAI,YAAa,MAAM,cAAY,SA8BzC"}
|
package/_dist/table.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** A token table: `count` rows of `dim` floats, row `id` for token `id`. */ export type Table = {
|
|
2
|
+
rows: Float32Array;
|
|
3
|
+
dim: number;
|
|
4
|
+
count: number;
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* The `embeddings` tensor of a safetensors file, keeping its leading `dim`
|
|
8
|
+
* columns (all of them by default). A file holding anything else beside it —
|
|
9
|
+
* per-token weights, a vocabulary mapping — is a newer layout this does not
|
|
10
|
+
* read, and is refused rather than read wrong.
|
|
11
|
+
*
|
|
12
|
+
* ```ts
|
|
13
|
+
* import { assertEquals } from '@std/assert'
|
|
14
|
+
* import { safetensors } from './testing.ts'
|
|
15
|
+
* let t = table(safetensors([[1, 2, 3], [4, 5, 6]]), 2)
|
|
16
|
+
* assertEquals([t.count, t.dim, [...t.rows]], [2, 2, [1, 2, 4, 5]])
|
|
17
|
+
* ```
|
|
18
|
+
*/ export declare let table: (bytes: Uint8Array, dim?: number) => Table;
|
|
19
|
+
//# sourceMappingURL=table.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"table.d.ts","sources":["../table.ts"],"names":[],"mappings":"AASA,0EAA0E,GAC1E,YAAY;EAAU,MAAM;EAAc,KAAK,MAAM;EAAE,OAAO,MAAM;;AAIpE;;;;;;;;;;;;CAYC,GACD,OAAO,YAAI,QAAS,OAAO,YAAY,MAAM,MAAM,KAAG,MA0CrD"}
|
package/deno.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"publish":{"exclude":["**/*_test.ts"]},"name":"@yaks/model2vec","version":"0.2.36","license":"Apache-2.0","description":"Embeds text in-process with a Model2Vec static model: a token table read from the Hugging Face hub, averaged per text, in about a millisecond, with no native code.","exports":{".":"./mod.ts","./graph":"./graph.ts"},"imports":{"@yaks/model2vec":"./mod.ts","@yaks/model2vec/graph":"./graph.ts"}}
|
package/graph.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// The `@yaks/model2vec/graph` facet: the embedder this plugin lends its host,
|
|
2
|
+
// named `model2vec`, which @yaks/embedding selects with
|
|
3
|
+
// `embedder: {"provider": "model2vec", "model": …, "dim": …}`:
|
|
4
|
+
//
|
|
5
|
+
// ```json
|
|
6
|
+
// [ "@yaks/model2vec",
|
|
7
|
+
// { "use": "@yaks/embedding",
|
|
8
|
+
// "with": { "embedder": { "provider": "model2vec",
|
|
9
|
+
// "model": "minishlab/potion-retrieval-32M@6fc8051",
|
|
10
|
+
// "dim": 256 } } } ]
|
|
11
|
+
// ```
|
|
12
|
+
import { model2vec } from "./mod.js";
|
|
13
|
+
/** The `model2vec` embedder, made from the model and width a config names. */ export let embedders = ()=>({
|
|
14
|
+
model2vec
|
|
15
|
+
});
|
|
16
|
+
//# sourceMappingURL=graph.js.map
|
package/graph.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"graph.js","sources":["./graph.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,wDAAwD;AACxD,+DAA+D;AAC/D,EAAE;AACF,UAAU;AACV,uBAAuB;AACvB,gCAAgC;AAChC,uDAAuD;AACvD,iFAAiF;AACjF,iDAAiD;AACjD,MAAM;AACN,SAAwC,SAAS,mBAAkB;AAEnE,4EAA4E,GAC5E,OAAO,IAAI,YAAY,IAAqD,CAAC;IAC3E;EACF,CAAC,EAAC"}
|
package/graph.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// The `@yaks/model2vec/graph` facet: the embedder this plugin lends its host,
|
|
2
|
+
// named `model2vec`, which @yaks/embedding selects with
|
|
3
|
+
// `embedder: {"provider": "model2vec", "model": …, "dim": …}`:
|
|
4
|
+
//
|
|
5
|
+
// ```json
|
|
6
|
+
// [ "@yaks/model2vec",
|
|
7
|
+
// { "use": "@yaks/embedding",
|
|
8
|
+
// "with": { "embedder": { "provider": "model2vec",
|
|
9
|
+
// "model": "minishlab/potion-retrieval-32M@6fc8051",
|
|
10
|
+
// "dim": 256 } } } ]
|
|
11
|
+
// ```
|
|
12
|
+
import { type Embedder, type Model2Vec, model2vec } from './mod.js'
|
|
13
|
+
|
|
14
|
+
/** The `model2vec` embedder, made from the model and width a config names. */
|
|
15
|
+
export let embedders = (): Record<string, (said: Model2Vec) => Embedder> => ({
|
|
16
|
+
model2vec,
|
|
17
|
+
})
|
package/mod.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @yaks/model2vec — an embedder fast enough to run on every prompt: a
|
|
3
|
+
* {@link https://github.com/MinishLab/model2vec | Model2Vec} static model,
|
|
4
|
+
* in-process, in plain TypeScript.
|
|
5
|
+
*
|
|
6
|
+
* A static model is a table with one vector per token. A text's vector is the
|
|
7
|
+
* mean of its tokens' rows, normalized: a tokenizer pass and a sum, about a
|
|
8
|
+
* millisecond for 500 tokens on one core, with no native code, no thread pool
|
|
9
|
+
* and no network once the model is loaded. It runs wherever a web platform
|
|
10
|
+
* does — a server, a Worker, a browser tab — and answers the same vector in
|
|
11
|
+
* each. What it gives up against a transformer is context: every token means
|
|
12
|
+
* the same thing wherever it stands.
|
|
13
|
+
*
|
|
14
|
+
* {@link model2vec} names a model on the Hugging Face hub and answers an
|
|
15
|
+
* embedder for it; the model is fetched on the first embed and kept in the
|
|
16
|
+
* platform's `caches`, so a later process reads it from disk. {@link embedder}
|
|
17
|
+
* is the same thing over a tokenizer and a table already in hand.
|
|
18
|
+
*
|
|
19
|
+
* ```ts
|
|
20
|
+
* import { assert, assertEquals } from '@std/assert'
|
|
21
|
+
* import { files } from './testing.ts' // a tokenizer.json and a table
|
|
22
|
+
* let e = await load('tiny', files)
|
|
23
|
+
* let [a, b, c] = ['a red dragon', 'dragon, red', 'a blue whale'].map(e.embed)
|
|
24
|
+
* let dot = (x: Float32Array, y: Float32Array) => x.reduce((s, v, i) => s + v * y[i], 0)
|
|
25
|
+
* assert(dot(a, b) > 0.99 && dot(a, c) < 0.5)
|
|
26
|
+
* assertEquals(e.model, 'tiny')
|
|
27
|
+
* ```
|
|
28
|
+
*
|
|
29
|
+
* @module
|
|
30
|
+
*/ import { table } from "./table.js";
|
|
31
|
+
export { table };
|
|
32
|
+
/** How much of a text is read by default, in tokens: Model2Vec's own default.
|
|
33
|
+
* A static model's mean dilutes as a text grows, so a longer window reads
|
|
34
|
+
* more and says less. */ export let MAX = 512;
|
|
35
|
+
/**
|
|
36
|
+
* An embedder over a tokenizer and a token table: the mean of the rows of a
|
|
37
|
+
* text's first `max` tokens, at length 1. A text with no known tokens embeds to
|
|
38
|
+
* the zero vector, which is unrelated to everything.
|
|
39
|
+
*/ export let embedder = (model, encode, t, { max = MAX, chars = Infinity, unk } = {})=>({
|
|
40
|
+
model,
|
|
41
|
+
embed: (text)=>{
|
|
42
|
+
let v = new Float32Array(t.dim);
|
|
43
|
+
let n = 0;
|
|
44
|
+
for (let id of encode(text.slice(0, chars))){
|
|
45
|
+
if (id == unk || id >= t.count) continue;
|
|
46
|
+
if (n++ == max) break;
|
|
47
|
+
let row = t.rows.subarray(id * t.dim, (id + 1) * t.dim);
|
|
48
|
+
for(let j = 0; j < t.dim; j++)v[j] += row[j];
|
|
49
|
+
}
|
|
50
|
+
let sum = 0;
|
|
51
|
+
for (let x of v)sum += x * x;
|
|
52
|
+
let len = Math.sqrt(sum);
|
|
53
|
+
if (len) {
|
|
54
|
+
for(let j = 0; j < t.dim; j++)v[j] /= len;
|
|
55
|
+
}
|
|
56
|
+
return v;
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
/** The space a config's vectors live in: the pinned model, and its width when
|
|
60
|
+
* it is cut, since two widths of one model are two spaces. */ export let space = (said)=>said.dim ? `${said.model}#${said.dim}` : said.model;
|
|
61
|
+
// Where the fetched files are kept, keyed by their URL: a pinned revision's
|
|
62
|
+
// file never changes, so a hit is always right.
|
|
63
|
+
let SHELF = '@yaks/model2vec';
|
|
64
|
+
// A file of the model: from the shelf, or from the hub and then shelved.
|
|
65
|
+
// Without a `caches` (some runtimes have none) every load fetches.
|
|
66
|
+
let file = async (url, go)=>{
|
|
67
|
+
let shelf = await globalThis.caches?.open(SHELF);
|
|
68
|
+
let hit = await shelf?.match(url);
|
|
69
|
+
if (hit) return new Uint8Array(await hit.arrayBuffer());
|
|
70
|
+
let res = await go(url);
|
|
71
|
+
if (!res.ok) {
|
|
72
|
+
throw new Error(`@yaks/model2vec: ${url} answered ${res.status}`);
|
|
73
|
+
}
|
|
74
|
+
let bytes = new Uint8Array(await res.arrayBuffer());
|
|
75
|
+
await shelf?.put(url, new Response(bytes));
|
|
76
|
+
return bytes;
|
|
77
|
+
};
|
|
78
|
+
// The median length of a vocabulary's tokens: Model2Vec cuts a text at `max`
|
|
79
|
+
// times this many characters before tokenizing it.
|
|
80
|
+
let median = (vocab)=>{
|
|
81
|
+
let lengths = (Array.isArray(vocab) ? vocab.map(([t])=>t) : Object.keys(vocab)).map((t)=>t.length).sort((a, b)=>a - b);
|
|
82
|
+
return lengths[lengths.length >> 1] ?? 1;
|
|
83
|
+
};
|
|
84
|
+
/** The model's own files, read into an embedder. */ export let load = async (model, files, { dim, max = MAX } = {})=>{
|
|
85
|
+
let { Tokenizer } = await import("@huggingface/tokenizers");
|
|
86
|
+
let json = JSON.parse(new TextDecoder().decode(files.tokenizer));
|
|
87
|
+
let tok = new Tokenizer(json, {});
|
|
88
|
+
let unk = json.model?.unk_token;
|
|
89
|
+
return embedder(model, (text)=>tok.encode(text, {
|
|
90
|
+
add_special_tokens: false
|
|
91
|
+
}).ids, table(files.safetensors, dim), {
|
|
92
|
+
max,
|
|
93
|
+
chars: max * median(json.model?.vocab ?? {}),
|
|
94
|
+
unk: unk == null ? undefined : tok.token_to_id(unk)
|
|
95
|
+
});
|
|
96
|
+
};
|
|
97
|
+
// The models this process has loaded, or is loading, by what they were read
|
|
98
|
+
// as: a config is read again on every pass, and a model is loaded once.
|
|
99
|
+
let loading = new Map();
|
|
100
|
+
let loaded = new Map();
|
|
101
|
+
/**
|
|
102
|
+
* An embedder for a Model2Vec model on the hub. Nothing is fetched until the
|
|
103
|
+
* first embed; that one waits for the model, and every one after is
|
|
104
|
+
* synchronous. The same model named again in this process is the one already
|
|
105
|
+
* loaded. A load that fails rejects the embeds waiting on it and is tried
|
|
106
|
+
* again on the next.
|
|
107
|
+
*/ export let model2vec = (said)=>{
|
|
108
|
+
let name = space(said);
|
|
109
|
+
let [repo, rev = 'main'] = said.model.split('@');
|
|
110
|
+
let root = `${(said.hub ?? 'https://huggingface.co').replace(/\/+$/, '')}/${repo}/resolve/${rev}/`;
|
|
111
|
+
let key = `${root} ${name} ${said.max ?? MAX}`;
|
|
112
|
+
let go = said.fetch ?? fetch;
|
|
113
|
+
let start = ()=>{
|
|
114
|
+
let now = loading.get(key);
|
|
115
|
+
if (now) return now;
|
|
116
|
+
let next = Promise.all([
|
|
117
|
+
file(root + 'tokenizer.json', go),
|
|
118
|
+
file(root + 'model.safetensors', go)
|
|
119
|
+
]).then(([tokenizer, safetensors])=>load(name, {
|
|
120
|
+
tokenizer,
|
|
121
|
+
safetensors
|
|
122
|
+
}, said)).then(({ embed })=>(loaded.set(key, embed), embed)).catch((error)=>{
|
|
123
|
+
loading.delete(key);
|
|
124
|
+
throw error;
|
|
125
|
+
});
|
|
126
|
+
loading.set(key, next);
|
|
127
|
+
return next;
|
|
128
|
+
};
|
|
129
|
+
return {
|
|
130
|
+
model: name,
|
|
131
|
+
embed: (text)=>loaded.get(key)?.(text) ?? start().then((f)=>f(text))
|
|
132
|
+
};
|
|
133
|
+
};
|
|
134
|
+
//# sourceMappingURL=mod.js.map
|
package/mod.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BC,GAED,SAAqB,KAAK,qBAAoB;AAE9C,SAAqB,KAAK,GAAE;AAY5B;;uBAEuB,GACvB,OAAO,IAAI,MAAM,IAAG;AAOpB;;;;CAIC,GACD,OAAO,IAAI,WAAW,CACpB,OACA,QACA,GACA,EAAE,MAAM,GAAG,EAAE,QAAQ,QAAQ,EAAE,GAAG,EAAU,GAAG,CAAC,CAAC,GACY,CAAC;IAC9D;IACA,OAAO,CAAC;MACN,IAAI,IAAI,IAAI,aAAa,EAAE,GAAG;MAC9B,IAAI,IAAI;MACR,KAAK,IAAI,MAAM,OAAO,KAAK,KAAK,CAAC,GAAG,QAAS;QAC3C,IAAI,MAAM,OAAO,MAAM,EAAE,KAAK,EAAE;QAChC,IAAI,OAAO,KAAK;QAChB,IAAI,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG;QACtD,IAAK,IAAI,IAAI,GAAG,IAAI,EAAE,GAAG,EAAE,IAAK,CAAC,CAAC,EAAE,IAAI,GAAG,CAAC,EAAE;MAChD;MACA,IAAI,MAAM;MACV,KAAK,IAAI,KAAK,EAAG,OAAO,IAAI;MAC5B,IAAI,MAAM,KAAK,IAAI,CAAC;MACpB,IAAI,KAAK;QAAE,IAAK,IAAI,IAAI,GAAG,IAAI,EAAE,GAAG,EAAE,IAAK,CAAC,CAAC,EAAE,IAAI;MAAI;MACvD,OAAO;IACT;EACF,CAAC,EAAC;AAiBF;4DAC4D,GAC5D,OAAO,IAAI,QAAQ,CAAC,OAClB,KAAK,GAAG,GAAG,GAAG,KAAK,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,EAAE,GAAG,KAAK,KAAK,CAAA;AAErD,4EAA4E;AAC5E,gDAAgD;AAChD,IAAI,QAAQ;AAEZ,yEAAyE;AACzE,mEAAmE;AACnE,IAAI,OAAO,OAAO,KAAa;EAC7B,IAAI,QAAQ,MAAM,WAAW,MAAM,EAAE,KAAK;EAC1C,IAAI,MAAM,MAAM,OAAO,MAAM;EAC7B,IAAI,KAAK,OAAO,IAAI,WAAW,MAAM,IAAI,WAAW;EACpD,IAAI,MAAM,MAAM,GAAG;EACnB,IAAI,CAAC,IAAI,EAAE,EAAE;IACX,MAAM,IAAI,MAAM,CAAC,iBAAiB,EAAE,IAAI,UAAU,EAAE,IAAI,MAAM,EAAE;EAClE;EACA,IAAI,QAAQ,IAAI,WAAW,MAAM,IAAI,WAAW;EAChD,MAAM,OAAO,IAAI,KAAK,IAAI,SAAS;EACnC,OAAO;AACT;AAEA,6EAA6E;AAC7E,mDAAmD;AACnD,IAAI,SAAS,CAAC;EACZ,IAAI,UAAU,CAAC,MAAM,OAAO,CAAC,SAAS,MAAM,GAAG,CAAC,CAAC,CAAC,EAAE,GAAK,KAAK,OAAO,IAAI,CACvE,MACD,EAAE,GAAG,CAAC,CAAC,IAAM,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,GAAG,IAAM,IAAI;EAC3C,OAAO,OAAO,CAAC,QAAQ,MAAM,IAAI,EAAE,IAAI;AACzC;AAEA,kDAAkD,GAClD,OAAO,IAAI,OAAO,OAChB,OACA,OACA,EAAE,GAAG,EAAE,MAAM,GAAG,EAAkC,GAAG,CAAC,CAAC;EAEvD,IAAI,EAAE,SAAS,EAAE,GAAG,MAAM,MAAM,CAAC;EACjC,IAAI,OAAO,KAAK,KAAK,CAAC,IAAI,cAAc,MAAM,CAAC,MAAM,SAAS;EAC9D,IAAI,MAAM,IAAI,UAAU,MAAM,CAAC;EAC/B,IAAI,MAAM,KAAK,KAAK,EAAE;EACtB,OAAO,SACL,OACA,CAAC,OAAS,IAAI,MAAM,CAAC,MAAM;MAAE,oBAAoB;IAAM,GAAG,GAAG,EAC7D,MAAM,MAAM,WAAW,EAAE,MACzB;IACE;IACA,OAAO,MAAM,OAAO,KAAK,KAAK,EAAE,SAAS,CAAC;IAC1C,KAAK,OAAO,OAAO,YAAY,IAAI,WAAW,CAAC;EACjD;AAEJ,EAAC;AAID,4EAA4E;AAC5E,wEAAwE;AACxE,IAAI,UAAU,IAAI;AAClB,IAAI,SAAS,IAAI;AAEjB;;;;;;CAMC,GACD,OAAO,IAAI,YAAY,CAAC;EACtB,IAAI,OAAO,MAAM;EACjB,IAAI,CAAC,MAAM,MAAM,MAAM,CAAC,GAAG,KAAK,KAAK,CAAC,KAAK,CAAC;EAC5C,IAAI,OAAO,GACT,CAAC,KAAK,GAAG,IAAI,wBAAwB,EAAE,OAAO,CAAC,QAAQ,IACxD,CAAC,EAAE,KAAK,SAAS,EAAE,IAAI,CAAC,CAAC;EAC1B,IAAI,MAAM,GAAG,KAAK,CAAC,EAAE,KAAK,CAAC,EAAE,KAAK,GAAG,IAAI,KAAK;EAC9C,IAAI,KAAK,KAAK,KAAK,IAAI;EACvB,IAAI,QAAQ;IACV,IAAI,MAAM,QAAQ,GAAG,CAAC;IACtB,IAAI,KAAK,OAAO;IAChB,IAAI,OAAO,QAAQ,GAAG,CAAC;MACrB,KAAK,OAAO,kBAAkB;MAC9B,KAAK,OAAO,qBAAqB;KAClC,EACE,IAAI,CAAC,CAAC,CAAC,WAAW,YAAY,GAC7B,KAAK,MAAM;QAAE;QAAW;MAAY,GAAG,OAExC,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,GAAK,CAAC,OAAO,GAAG,CAAC,KAAK,QAAQ,KAAK,GAClD,KAAK,CAAC,CAAC;MACN,QAAQ,MAAM,CAAC;MACf,MAAM;IACR;IACF,QAAQ,GAAG,CAAC,KAAK;IACjB,OAAO;EACT;EACA,OAAO;IACL,OAAO;IACP,OAAO,CAAC,OAAS,OAAO,GAAG,CAAC,OAAO,SAAS,QAAQ,IAAI,CAAC,CAAC,IAAM,EAAE;EACpE;AACF,EAAC"}
|
package/mod.ts
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @yaks/model2vec — an embedder fast enough to run on every prompt: a
|
|
3
|
+
* {@link https://github.com/MinishLab/model2vec | Model2Vec} static model,
|
|
4
|
+
* in-process, in plain TypeScript.
|
|
5
|
+
*
|
|
6
|
+
* A static model is a table with one vector per token. A text's vector is the
|
|
7
|
+
* mean of its tokens' rows, normalized: a tokenizer pass and a sum, about a
|
|
8
|
+
* millisecond for 500 tokens on one core, with no native code, no thread pool
|
|
9
|
+
* and no network once the model is loaded. It runs wherever a web platform
|
|
10
|
+
* does — a server, a Worker, a browser tab — and answers the same vector in
|
|
11
|
+
* each. What it gives up against a transformer is context: every token means
|
|
12
|
+
* the same thing wherever it stands.
|
|
13
|
+
*
|
|
14
|
+
* {@link model2vec} names a model on the Hugging Face hub and answers an
|
|
15
|
+
* embedder for it; the model is fetched on the first embed and kept in the
|
|
16
|
+
* platform's `caches`, so a later process reads it from disk. {@link embedder}
|
|
17
|
+
* is the same thing over a tokenizer and a table already in hand.
|
|
18
|
+
*
|
|
19
|
+
* ```ts
|
|
20
|
+
* import { assert, assertEquals } from '@std/assert'
|
|
21
|
+
* import { files } from './testing.ts' // a tokenizer.json and a table
|
|
22
|
+
* let e = await load('tiny', files)
|
|
23
|
+
* let [a, b, c] = ['a red dragon', 'dragon, red', 'a blue whale'].map(e.embed)
|
|
24
|
+
* let dot = (x: Float32Array, y: Float32Array) => x.reduce((s, v, i) => s + v * y[i], 0)
|
|
25
|
+
* assert(dot(a, b) > 0.99 && dot(a, c) < 0.5)
|
|
26
|
+
* assertEquals(e.model, 'tiny')
|
|
27
|
+
* ```
|
|
28
|
+
*
|
|
29
|
+
* @module
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import { type Table, table } from './table.js'
|
|
33
|
+
|
|
34
|
+
export { type Table, table }
|
|
35
|
+
|
|
36
|
+
/** Text in, vector out, and the name of the space the vectors live in: the
|
|
37
|
+
* shape @yaks/embedding takes. */
|
|
38
|
+
export type Embedder = {
|
|
39
|
+
model: string
|
|
40
|
+
embed: (text: string) => Float32Array | Promise<Float32Array>
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** A text as token ids, without special tokens. */
|
|
44
|
+
export type Encode = (text: string) => number[]
|
|
45
|
+
|
|
46
|
+
/** How much of a text is read by default, in tokens: Model2Vec's own default.
|
|
47
|
+
* A static model's mean dilutes as a text grows, so a longer window reads
|
|
48
|
+
* more and says less. */
|
|
49
|
+
export let MAX = 512
|
|
50
|
+
|
|
51
|
+
/** What a text is read as. `unk` is dropped, as Model2Vec drops it; `chars`
|
|
52
|
+
* cuts the text before tokenizing, so a long one costs no more than its
|
|
53
|
+
* window. */
|
|
54
|
+
export type Window = { max?: number; chars?: number; unk?: number }
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* An embedder over a tokenizer and a token table: the mean of the rows of a
|
|
58
|
+
* text's first `max` tokens, at length 1. A text with no known tokens embeds to
|
|
59
|
+
* the zero vector, which is unrelated to everything.
|
|
60
|
+
*/
|
|
61
|
+
export let embedder = (
|
|
62
|
+
model: string,
|
|
63
|
+
encode: Encode,
|
|
64
|
+
t: Table,
|
|
65
|
+
{ max = MAX, chars = Infinity, unk }: Window = {},
|
|
66
|
+
): { model: string; embed: (text: string) => Float32Array } => ({
|
|
67
|
+
model,
|
|
68
|
+
embed: (text) => {
|
|
69
|
+
let v = new Float32Array(t.dim)
|
|
70
|
+
let n = 0
|
|
71
|
+
for (let id of encode(text.slice(0, chars))) {
|
|
72
|
+
if (id == unk || id >= t.count) continue
|
|
73
|
+
if (n++ == max) break
|
|
74
|
+
let row = t.rows.subarray(id * t.dim, (id + 1) * t.dim)
|
|
75
|
+
for (let j = 0; j < t.dim; j++) v[j] += row[j]
|
|
76
|
+
}
|
|
77
|
+
let sum = 0
|
|
78
|
+
for (let x of v) sum += x * x
|
|
79
|
+
let len = Math.sqrt(sum)
|
|
80
|
+
if (len) { for (let j = 0; j < t.dim; j++) v[j] /= len }
|
|
81
|
+
return v
|
|
82
|
+
},
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
/** A Model2Vec model on the hub, as a config names one. */
|
|
86
|
+
export type Model2Vec = {
|
|
87
|
+
/** the hub repo, pinned to a revision: `minishlab/potion-retrieval-32M@6fc8051`.
|
|
88
|
+
* Unpinned, the first revision this machine fetches is the one it keeps. */
|
|
89
|
+
model: string
|
|
90
|
+
/** keep this many leading columns of the table (default: all of them) */
|
|
91
|
+
dim?: number
|
|
92
|
+
/** read at most this many tokens of a text (default {@link MAX}) */
|
|
93
|
+
max?: number
|
|
94
|
+
/** the hub (default https://huggingface.co) */
|
|
95
|
+
hub?: string
|
|
96
|
+
/** the fetch to call through (default: the global one) */
|
|
97
|
+
fetch?: typeof fetch
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The space a config's vectors live in: the pinned model, and its width when
|
|
101
|
+
* it is cut, since two widths of one model are two spaces. */
|
|
102
|
+
export let space = (said: Model2Vec): string =>
|
|
103
|
+
said.dim ? `${said.model}#${said.dim}` : said.model
|
|
104
|
+
|
|
105
|
+
// Where the fetched files are kept, keyed by their URL: a pinned revision's
|
|
106
|
+
// file never changes, so a hit is always right.
|
|
107
|
+
let SHELF = '@yaks/model2vec'
|
|
108
|
+
|
|
109
|
+
// A file of the model: from the shelf, or from the hub and then shelved.
|
|
110
|
+
// Without a `caches` (some runtimes have none) every load fetches.
|
|
111
|
+
let file = async (url: string, go: typeof fetch): Promise<Uint8Array> => {
|
|
112
|
+
let shelf = await globalThis.caches?.open(SHELF)
|
|
113
|
+
let hit = await shelf?.match(url)
|
|
114
|
+
if (hit) return new Uint8Array(await hit.arrayBuffer())
|
|
115
|
+
let res = await go(url)
|
|
116
|
+
if (!res.ok) {
|
|
117
|
+
throw new Error(`@yaks/model2vec: ${url} answered ${res.status}`)
|
|
118
|
+
}
|
|
119
|
+
let bytes = new Uint8Array(await res.arrayBuffer())
|
|
120
|
+
await shelf?.put(url, new Response(bytes))
|
|
121
|
+
return bytes
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// The median length of a vocabulary's tokens: Model2Vec cuts a text at `max`
|
|
125
|
+
// times this many characters before tokenizing it.
|
|
126
|
+
let median = (vocab: Record<string, number> | [string, number][]): number => {
|
|
127
|
+
let lengths = (Array.isArray(vocab) ? vocab.map(([t]) => t) : Object.keys(
|
|
128
|
+
vocab,
|
|
129
|
+
)).map((t) => t.length).sort((a, b) => a - b)
|
|
130
|
+
return lengths[lengths.length >> 1] ?? 1
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** The model's own files, read into an embedder. */
|
|
134
|
+
export let load = async (
|
|
135
|
+
model: string,
|
|
136
|
+
files: { tokenizer: Uint8Array; safetensors: Uint8Array },
|
|
137
|
+
{ dim, max = MAX }: { dim?: number; max?: number } = {},
|
|
138
|
+
): Promise<{ model: string; embed: (text: string) => Float32Array }> => {
|
|
139
|
+
let { Tokenizer } = await import('@huggingface/tokenizers')
|
|
140
|
+
let json = JSON.parse(new TextDecoder().decode(files.tokenizer))
|
|
141
|
+
let tok = new Tokenizer(json, {})
|
|
142
|
+
let unk = json.model?.unk_token
|
|
143
|
+
return embedder(
|
|
144
|
+
model,
|
|
145
|
+
(text) => tok.encode(text, { add_special_tokens: false }).ids,
|
|
146
|
+
table(files.safetensors, dim),
|
|
147
|
+
{
|
|
148
|
+
max,
|
|
149
|
+
chars: max * median(json.model?.vocab ?? {}),
|
|
150
|
+
unk: unk == null ? undefined : tok.token_to_id(unk),
|
|
151
|
+
},
|
|
152
|
+
)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
type Embed = (text: string) => Float32Array
|
|
156
|
+
|
|
157
|
+
// The models this process has loaded, or is loading, by what they were read
|
|
158
|
+
// as: a config is read again on every pass, and a model is loaded once.
|
|
159
|
+
let loading = new Map<string, Promise<Embed>>()
|
|
160
|
+
let loaded = new Map<string, Embed>()
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* An embedder for a Model2Vec model on the hub. Nothing is fetched until the
|
|
164
|
+
* first embed; that one waits for the model, and every one after is
|
|
165
|
+
* synchronous. The same model named again in this process is the one already
|
|
166
|
+
* loaded. A load that fails rejects the embeds waiting on it and is tried
|
|
167
|
+
* again on the next.
|
|
168
|
+
*/
|
|
169
|
+
export let model2vec = (said: Model2Vec): Embedder => {
|
|
170
|
+
let name = space(said)
|
|
171
|
+
let [repo, rev = 'main'] = said.model.split('@')
|
|
172
|
+
let root = `${
|
|
173
|
+
(said.hub ?? 'https://huggingface.co').replace(/\/+$/, '')
|
|
174
|
+
}/${repo}/resolve/${rev}/`
|
|
175
|
+
let key = `${root} ${name} ${said.max ?? MAX}`
|
|
176
|
+
let go = said.fetch ?? fetch
|
|
177
|
+
let start = (): Promise<Embed> => {
|
|
178
|
+
let now = loading.get(key)
|
|
179
|
+
if (now) return now
|
|
180
|
+
let next = Promise.all([
|
|
181
|
+
file(root + 'tokenizer.json', go),
|
|
182
|
+
file(root + 'model.safetensors', go),
|
|
183
|
+
])
|
|
184
|
+
.then(([tokenizer, safetensors]) =>
|
|
185
|
+
load(name, { tokenizer, safetensors }, said)
|
|
186
|
+
)
|
|
187
|
+
.then(({ embed }) => (loaded.set(key, embed), embed))
|
|
188
|
+
.catch((error) => {
|
|
189
|
+
loading.delete(key)
|
|
190
|
+
throw error
|
|
191
|
+
})
|
|
192
|
+
loading.set(key, next)
|
|
193
|
+
return next
|
|
194
|
+
}
|
|
195
|
+
return {
|
|
196
|
+
model: name,
|
|
197
|
+
embed: (text) => loaded.get(key)?.(text) ?? start().then((f) => f(text)),
|
|
198
|
+
}
|
|
199
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yaks/model2vec",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.36",
|
|
4
|
+
"homepage": "https://jsr.io/@yaks/model2vec",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./_dist/mod.d.ts",
|
|
9
|
+
"default": "./mod.js"
|
|
10
|
+
},
|
|
11
|
+
"./graph": {
|
|
12
|
+
"types": "./_dist/graph.d.ts",
|
|
13
|
+
"default": "./graph.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"license": "Apache-2.0",
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@huggingface/tokenizers": "0.2.0"
|
|
19
|
+
},
|
|
20
|
+
"description": "Embeds text in-process with a Model2Vec static model: a token table read from the Hugging Face hub, averaged per text, in about a millisecond, with no native code.",
|
|
21
|
+
"repository": "https://github.com/yak-sh/yak.git"
|
|
22
|
+
}
|
package/table.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// The token table a Model2Vec model ships as `model.safetensors`: one row of
|
|
2
|
+
// floats per token id, the whole model. Reading it is pure: bytes in, rows out.
|
|
3
|
+
//
|
|
4
|
+
// Its columns come out of a PCA, most variance first, so the leading `dim` of
|
|
5
|
+
// them are the model at a smaller width, the way Model2Vec's own
|
|
6
|
+
// `dimensionality` loads one. Keeping only those columns here, rather than
|
|
7
|
+
// cutting each vector later, is the same arithmetic (a mean of cut rows is the
|
|
8
|
+
// cut of the mean) at a fraction of the memory.
|
|
9
|
+
/** A token table: `count` rows of `dim` floats, row `id` for token `id`. */ /**
|
|
10
|
+
* The `embeddings` tensor of a safetensors file, keeping its leading `dim`
|
|
11
|
+
* columns (all of them by default). A file holding anything else beside it —
|
|
12
|
+
* per-token weights, a vocabulary mapping — is a newer layout this does not
|
|
13
|
+
* read, and is refused rather than read wrong.
|
|
14
|
+
*
|
|
15
|
+
* ```ts
|
|
16
|
+
* import { assertEquals } from '@std/assert'
|
|
17
|
+
* import { safetensors } from './testing.ts'
|
|
18
|
+
* let t = table(safetensors([[1, 2, 3], [4, 5, 6]]), 2)
|
|
19
|
+
* assertEquals([t.count, t.dim, [...t.rows]], [2, 2, [1, 2, 4, 5]])
|
|
20
|
+
* ```
|
|
21
|
+
*/ export let table = (bytes, dim)=>{
|
|
22
|
+
let view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
23
|
+
let size = Number(view.getBigUint64(0, true));
|
|
24
|
+
let head = JSON.parse(new TextDecoder().decode(bytes.subarray(8, 8 + size)));
|
|
25
|
+
let { __metadata__: _, embeddings: t, ...rest } = head;
|
|
26
|
+
if (!t || Object.keys(rest).length) {
|
|
27
|
+
throw new Error(`@yaks/model2vec: expected one \`embeddings\` tensor, found ${Object.keys(head).join(', ')}`);
|
|
28
|
+
}
|
|
29
|
+
if (t.dtype != 'F32' || t.shape.length != 2) {
|
|
30
|
+
throw new Error(`@yaks/model2vec: embeddings are ${t.dtype} ${t.shape}, not a F32 table`);
|
|
31
|
+
}
|
|
32
|
+
let [count, width] = t.shape;
|
|
33
|
+
let keep = dim ?? width;
|
|
34
|
+
if (keep > width) {
|
|
35
|
+
throw new Error(`@yaks/model2vec: the model is ${width} wide, narrower than the ${keep} asked for`);
|
|
36
|
+
}
|
|
37
|
+
let at = bytes.byteOffset + 8 + size + t.data_offsets[0];
|
|
38
|
+
// A Float32Array needs a 4-byte-aligned offset; a file's is aligned by
|
|
39
|
+
// convention, and copied when it is not.
|
|
40
|
+
let all = at % 4 ? new Float32Array(bytes.slice(at - bytes.byteOffset).buffer, 0, count * width) : new Float32Array(bytes.buffer, at, count * width);
|
|
41
|
+
if (keep == width) return {
|
|
42
|
+
rows: all,
|
|
43
|
+
dim: width,
|
|
44
|
+
count
|
|
45
|
+
};
|
|
46
|
+
let rows = new Float32Array(count * keep);
|
|
47
|
+
for(let i = 0; i < count; i++){
|
|
48
|
+
rows.set(all.subarray(i * width, i * width + keep), i * keep);
|
|
49
|
+
}
|
|
50
|
+
return {
|
|
51
|
+
rows,
|
|
52
|
+
dim: keep,
|
|
53
|
+
count
|
|
54
|
+
};
|
|
55
|
+
};
|
|
56
|
+
//# sourceMappingURL=table.js.map
|
package/table.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"table.js","sources":["./table.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,gFAAgF;AAChF,EAAE;AACF,8EAA8E;AAC9E,iEAAiE;AACjE,2EAA2E;AAC3E,+EAA+E;AAC/E,gDAAgD;AAEhD,0EAA0E,GAK1E;;;;;;;;;;;;CAYC,GACD,OAAO,IAAI,QAAQ,CAAC,OAAmB;EACrC,IAAI,OAAO,IAAI,SAAS,MAAM,MAAM,EAAE,MAAM,UAAU,EAAE,MAAM,UAAU;EACxE,IAAI,OAAO,OAAO,KAAK,YAAY,CAAC,GAAG;EACvC,IAAI,OAAO,KAAK,KAAK,CACnB,IAAI,cAAc,MAAM,CAAC,MAAM,QAAQ,CAAC,GAAG,IAAI;EAEjD,IAAI,EAAE,cAAc,CAAC,EAAE,YAAY,CAAC,EAAE,GAAG,MAAM,GAAG;EAClD,IAAI,CAAC,KAAK,OAAO,IAAI,CAAC,MAAM,MAAM,EAAE;IAClC,MAAM,IAAI,MACR,CAAC,2DAA2D,EAC1D,OAAO,IAAI,CAAC,MAAM,IAAI,CAAC,OACvB;EAEN;EACA,IAAI,EAAE,KAAK,IAAI,SAAS,EAAE,KAAK,CAAC,MAAM,IAAI,GAAG;IAC3C,MAAM,IAAI,MACR,CAAC,gCAAgC,EAAE,EAAE,KAAK,CAAC,CAAC,EAAE,EAAE,KAAK,CAAC,iBAAiB,CAAC;EAE5E;EACA,IAAI,CAAC,OAAO,MAAM,GAAG,EAAE,KAAK;EAC5B,IAAI,OAAO,OAAO;EAClB,IAAI,OAAO,OAAO;IAChB,MAAM,IAAI,MACR,CAAC,8BAA8B,EAAE,MAAM,yBAAyB,EAAE,KAAK,UAAU,CAAC;EAEtF;EACA,IAAI,KAAK,MAAM,UAAU,GAAG,IAAI,OAAO,EAAE,YAAY,CAAC,EAAE;EACxD,uEAAuE;EACvE,yCAAyC;EACzC,IAAI,MAAM,KAAK,IACX,IAAI,aACJ,MAAM,KAAK,CAAC,KAAK,MAAM,UAAU,EAAE,MAAM,EACzC,GACA,QAAQ,SAER,IAAI,aAAa,MAAM,MAAM,EAAE,IAAI,QAAQ;EAC/C,IAAI,QAAQ,OAAO,OAAO;IAAE,MAAM;IAAK,KAAK;IAAO;EAAM;EACzD,IAAI,OAAO,IAAI,aAAa,QAAQ;EACpC,IAAK,IAAI,IAAI,GAAG,IAAI,OAAO,IAAK;IAC9B,KAAK,GAAG,CAAC,IAAI,QAAQ,CAAC,IAAI,OAAO,IAAI,QAAQ,OAAO,IAAI;EAC1D;EACA,OAAO;IAAE;IAAM,KAAK;IAAM;EAAM;AAClC,EAAC"}
|
package/table.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// The token table a Model2Vec model ships as `model.safetensors`: one row of
|
|
2
|
+
// floats per token id, the whole model. Reading it is pure: bytes in, rows out.
|
|
3
|
+
//
|
|
4
|
+
// Its columns come out of a PCA, most variance first, so the leading `dim` of
|
|
5
|
+
// them are the model at a smaller width, the way Model2Vec's own
|
|
6
|
+
// `dimensionality` loads one. Keeping only those columns here, rather than
|
|
7
|
+
// cutting each vector later, is the same arithmetic (a mean of cut rows is the
|
|
8
|
+
// cut of the mean) at a fraction of the memory.
|
|
9
|
+
|
|
10
|
+
/** A token table: `count` rows of `dim` floats, row `id` for token `id`. */
|
|
11
|
+
export type Table = { rows: Float32Array; dim: number; count: number }
|
|
12
|
+
|
|
13
|
+
type Tensor = { dtype: string; shape: number[]; data_offsets: [number, number] }
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The `embeddings` tensor of a safetensors file, keeping its leading `dim`
|
|
17
|
+
* columns (all of them by default). A file holding anything else beside it —
|
|
18
|
+
* per-token weights, a vocabulary mapping — is a newer layout this does not
|
|
19
|
+
* read, and is refused rather than read wrong.
|
|
20
|
+
*
|
|
21
|
+
* ```ts
|
|
22
|
+
* import { assertEquals } from '@std/assert'
|
|
23
|
+
* import { safetensors } from './testing.ts'
|
|
24
|
+
* let t = table(safetensors([[1, 2, 3], [4, 5, 6]]), 2)
|
|
25
|
+
* assertEquals([t.count, t.dim, [...t.rows]], [2, 2, [1, 2, 4, 5]])
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
export let table = (bytes: Uint8Array, dim?: number): Table => {
|
|
29
|
+
let view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
|
|
30
|
+
let size = Number(view.getBigUint64(0, true))
|
|
31
|
+
let head = JSON.parse(
|
|
32
|
+
new TextDecoder().decode(bytes.subarray(8, 8 + size)),
|
|
33
|
+
) as Record<string, Tensor>
|
|
34
|
+
let { __metadata__: _, embeddings: t, ...rest } = head
|
|
35
|
+
if (!t || Object.keys(rest).length) {
|
|
36
|
+
throw new Error(
|
|
37
|
+
`@yaks/model2vec: expected one \`embeddings\` tensor, found ${
|
|
38
|
+
Object.keys(head).join(', ')
|
|
39
|
+
}`,
|
|
40
|
+
)
|
|
41
|
+
}
|
|
42
|
+
if (t.dtype != 'F32' || t.shape.length != 2) {
|
|
43
|
+
throw new Error(
|
|
44
|
+
`@yaks/model2vec: embeddings are ${t.dtype} ${t.shape}, not a F32 table`,
|
|
45
|
+
)
|
|
46
|
+
}
|
|
47
|
+
let [count, width] = t.shape
|
|
48
|
+
let keep = dim ?? width
|
|
49
|
+
if (keep > width) {
|
|
50
|
+
throw new Error(
|
|
51
|
+
`@yaks/model2vec: the model is ${width} wide, narrower than the ${keep} asked for`,
|
|
52
|
+
)
|
|
53
|
+
}
|
|
54
|
+
let at = bytes.byteOffset + 8 + size + t.data_offsets[0]
|
|
55
|
+
// A Float32Array needs a 4-byte-aligned offset; a file's is aligned by
|
|
56
|
+
// convention, and copied when it is not.
|
|
57
|
+
let all = at % 4
|
|
58
|
+
? new Float32Array(
|
|
59
|
+
bytes.slice(at - bytes.byteOffset).buffer,
|
|
60
|
+
0,
|
|
61
|
+
count * width,
|
|
62
|
+
)
|
|
63
|
+
: new Float32Array(bytes.buffer, at, count * width)
|
|
64
|
+
if (keep == width) return { rows: all, dim: width, count }
|
|
65
|
+
let rows = new Float32Array(count * keep)
|
|
66
|
+
for (let i = 0; i < count; i++) {
|
|
67
|
+
rows.set(all.subarray(i * width, i * width + keep), i * keep)
|
|
68
|
+
}
|
|
69
|
+
return { rows, dim: keep, count }
|
|
70
|
+
}
|
package/testing.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// Test fixtures (not part of the published package): a model small enough to
|
|
2
|
+
// read, in the same two files a hub repo holds — a WordPiece tokenizer.json
|
|
3
|
+
// and a safetensors token table.
|
|
4
|
+
|
|
5
|
+
/** A safetensors file: this header, then these floats. */
|
|
6
|
+
export let raw = (
|
|
7
|
+
header: object,
|
|
8
|
+
data: Float32Array,
|
|
9
|
+
): Uint8Array<ArrayBuffer> => {
|
|
10
|
+
let head = new TextEncoder().encode(JSON.stringify(header))
|
|
11
|
+
// the header is padded to 8 bytes, as the format's writers do
|
|
12
|
+
let size = Math.ceil(head.length / 8) * 8
|
|
13
|
+
let out = new Uint8Array(8 + size + data.byteLength).fill(0x20, 8, 8 + size)
|
|
14
|
+
new DataView(out.buffer).setBigUint64(0, BigInt(size), true)
|
|
15
|
+
out.set(head, 8)
|
|
16
|
+
out.set(new Uint8Array(data.buffer), 8 + size)
|
|
17
|
+
return out
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** A safetensors file holding one F32 `embeddings` tensor, these rows. */
|
|
21
|
+
export let safetensors = (rows: number[][]): Uint8Array<ArrayBuffer> => {
|
|
22
|
+
let data = new Float32Array(rows.flat())
|
|
23
|
+
return raw({
|
|
24
|
+
__metadata__: { format: 'pt' },
|
|
25
|
+
embeddings: {
|
|
26
|
+
dtype: 'F32',
|
|
27
|
+
shape: [rows.length, rows[0].length],
|
|
28
|
+
data_offsets: [0, data.byteLength],
|
|
29
|
+
},
|
|
30
|
+
}, data)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A lowercasing WordPiece tokenizer.json over these words, as a BERT
|
|
34
|
+
* vocabulary lays one out: the special tokens first. */
|
|
35
|
+
export let tokenizer = (words: string[]): Uint8Array<ArrayBuffer> =>
|
|
36
|
+
new TextEncoder().encode(JSON.stringify({
|
|
37
|
+
version: '1.0',
|
|
38
|
+
added_tokens: ['[PAD]', '[UNK]', '[CLS]', '[SEP]'].map((content, id) => ({
|
|
39
|
+
id,
|
|
40
|
+
content,
|
|
41
|
+
single_word: false,
|
|
42
|
+
lstrip: false,
|
|
43
|
+
rstrip: false,
|
|
44
|
+
normalized: false,
|
|
45
|
+
special: true,
|
|
46
|
+
})),
|
|
47
|
+
normalizer: {
|
|
48
|
+
type: 'BertNormalizer',
|
|
49
|
+
clean_text: true,
|
|
50
|
+
handle_chinese_chars: true,
|
|
51
|
+
strip_accents: null,
|
|
52
|
+
lowercase: true,
|
|
53
|
+
},
|
|
54
|
+
pre_tokenizer: { type: 'BertPreTokenizer' },
|
|
55
|
+
post_processor: null,
|
|
56
|
+
decoder: null,
|
|
57
|
+
model: {
|
|
58
|
+
type: 'WordPiece',
|
|
59
|
+
unk_token: '[UNK]',
|
|
60
|
+
continuing_subword_prefix: '##',
|
|
61
|
+
max_input_chars_per_word: 100,
|
|
62
|
+
vocab: Object.fromEntries(
|
|
63
|
+
['[PAD]', '[UNK]', '[CLS]', '[SEP]', ...words].map((w, i) => [w, i]),
|
|
64
|
+
),
|
|
65
|
+
},
|
|
66
|
+
}))
|
|
67
|
+
|
|
68
|
+
let words = ['a', 'red', 'dragon', 'blue', 'whale', ',']
|
|
69
|
+
let rows = [
|
|
70
|
+
[0, 0, 0, 0],
|
|
71
|
+
[9, 9, 9, 9], // [UNK]: never read
|
|
72
|
+
[0, 0, 0, 0],
|
|
73
|
+
[0, 0, 0, 0],
|
|
74
|
+
[0.1, 0, 0, 0],
|
|
75
|
+
[1, 0, 0, 0],
|
|
76
|
+
[0, 1, 0, 0],
|
|
77
|
+
[0, 0, 1, 0],
|
|
78
|
+
[0, 0, 0, 1],
|
|
79
|
+
[0, 0, 0, 0],
|
|
80
|
+
]
|
|
81
|
+
|
|
82
|
+
/** The files of a four-dimensional model of six words. */
|
|
83
|
+
export let files = {
|
|
84
|
+
tokenizer: tokenizer(words),
|
|
85
|
+
safetensors: safetensors(rows),
|
|
86
|
+
}
|