├── .gitignore
├── LICENSE.md
├── README.md
├── clip_tokenizer.js
└── index.html
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Softwired Technologies Ltd.
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6 |
7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8 |
9 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Stable Diffusion on [tinygrad](https://github.com/tinygrad/tinygrad) WebGPU
2 |
3 | NOTE: This is an outdated model export, please try these instead:
4 | - new f32 version (~10% faster): https://github.com/wpmed92/stable-diffusion-wgpu-tinygrad
5 | - f16 version (~40% faster): https://github.com/wpmed92/stable-diffusion-tinygrad-f16
6 |
7 | This is a WebGPU port of Stable Diffusion in [tinygrad](https://github.com/tinygrad/tinygrad).
8 | Try it out [here](https://softwiredtech.github.io/stable-diffusion-webgpu/)!
9 | The python code I wrote to compile and export the model can be found [here](https://github.com/tinygrad/tinygrad/blob/master/examples/webgpu/stable_diffusion/compile.py)
10 |
11 | ## How it works
12 |
13 | The Stable Diffusion model is exported in three parts:
14 | - textModel
15 | - diffusor
16 | - decoder
17 |
18 | If you open [net.js](./net.js) you can see all the WebGPU kernels that are involved in the inference.
19 | When you open the page for the first time, the model will be downloaded from [huggingface](https://huggingface.co/wpmed/tinygrad-sd-f16/resolve/main) in tinygrad's safetensor format. The model is in f16 to optimize download speed.
20 | Since the computation is done in `f32` in the model, and since `shader-f16` is not yet supported in production Chrome, the model is decompressed to `f32` using [f16-to-f32-gpu](https://github.com/wpmed92/f16-to-f32-gpu) WebGPU-based `f16` decompression library.
21 | When you open the site a second time, the model will be loaded from the `IndexedDB` cache into which it was saved on first visit. If you have a full cache hit, the model will be decompressed, compiled and ready to use. If you have a cache miss (usually due to `QuotaExceededError`), the model will be redownloaded.
22 |
23 | ## License
24 |
25 | MIT
26 |
--------------------------------------------------------------------------------
/clip_tokenizer.js:
--------------------------------------------------------------------------------
1 | import { Html5Entities as htmlEntities } from "https://deno.land/x/html_entities@v1.0/mod.js";
2 | import bpeVocabData from "./bpe_simple_vocab_16e6.mjs";
3 | // import ftfy from "https://deno.land/x/ftfy_pyodide@v0.1.1/mod.js";
4 |
5 |
6 | function ord(c) {
7 | return c.charCodeAt(0);
8 | }
9 | function range(start, stop, step=1) {
10 | if(stop === undefined) {
11 | stop = start;
12 | start = 0;
13 | }
14 |
15 | if((step > 0 && start >= stop) || (step < 0 && start <= stop)) {
16 | return [];
17 | }
18 |
19 | const result = [];
20 | for(let i = start; step > 0 ? i < stop : i > stop; i += step) {
21 | result.push(i);
22 | }
23 |
24 | return result;
25 | }
26 |
27 |
28 |
29 | function bytesToUnicode() {
30 | let bs = [
31 | ...range(ord("!"), ord("~") + 1),
32 | ...range(ord("¡"), ord("¬") + 1),
33 | ...range(ord("®"), ord("ÿ") + 1),
34 | ];
35 | let cs = bs.slice(0);
36 | let n = 0;
37 | for(let b of range(2**8)) {
38 | if(!bs.includes(b)) {
39 | bs.push(b);
40 | cs.push(2**8 + n);
41 | n += 1;
42 | }
43 | }
44 | cs = cs.map(n => String.fromCharCode(n));
45 | return Object.fromEntries(bs.map((v, i) => [v, cs[i]]));
46 | }
47 |
48 | function getPairs(word) {
49 | let pairs = [];
50 | let prevChar = word[0];
51 | for(let char of word.slice(1)) {
52 | pairs.push([prevChar, char]);
53 | prevChar = char;
54 | }
55 | return pairs;
56 | }
57 |
58 | function basicClean(text) {
59 | // text = ftfy.fix_text(text);
60 | text = htmlEntities.decode(htmlEntities.decode(text));
61 | return text.trim();
62 | }
63 |
64 | function whitespaceClean(text) {
65 | return text.replace(/\s+/g, " ").trim();
66 | }
67 |
68 |
69 | export default class ClipTokenizer {
70 | constructor() {
71 | this.byteEncoder = bytesToUnicode();
72 | this.byteDecoder = Object.fromEntries(Object.entries(this.byteEncoder).map(([k,v]) => [v,k]));
73 | let merges = bpeVocabData.text.split("\n");
74 | merges = merges.slice(1, 49152-256-2+1);
75 | merges = merges.map(merge => merge.split(" "));
76 | // There was a bug related to the ordering of Python's .values() output. I'm lazy do I've just copy-pasted the Python output:
77 | let vocab = ['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '¡', '¢', '£', '¤', '¥', '¦', '§', '¨', '©', 'ª', '«', '¬', '®', '¯', '°', '±', '²', '³', '´', 'µ', '¶', '·', '¸', '¹', 'º', '»', '¼', '½', '¾', '¿', 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', '×', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'Þ', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ð', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', '÷', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'þ', 'ÿ', 'Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď', 'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ', 'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī', 'Ĭ', 'ĭ', 'Į', 'į', 'İ', 'ı', 'IJ', 'ij', 'Ĵ', 'ĵ', 'Ķ', 'ķ', 'ĸ', 'Ĺ', 'ĺ', 'Ļ', 'ļ', 'Ľ', 'ľ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'Ń'];
78 | vocab = [...vocab, ...vocab.map(v => v+'')];
79 | for(let merge of merges) {
80 | vocab.push(merge.join(""));
81 | }
82 | vocab.push('<|startoftext|>', '<|endoftext|>');
83 | this.encoder = Object.fromEntries(vocab.map((v,i) => [v,i]));
84 | this.decoder = Object.fromEntries(Object.entries(this.encoder).map(([k,v]) => [v,k]));
85 | this.bpeRanks = Object.fromEntries(merges.map((v,i) => [v.join("·😎·"),i])); // ·😎· because js doesn't yet have tuples
86 | this.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'};
87 | this.pat = /<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+/gui;
88 | }
89 |
90 | bpe(token) {
91 | if(this.cache[token] !== undefined) {
92 | return this.cache[token];
93 | }
94 |
95 | let word = [...token.slice(0, -1), token.slice(-1)+''];
96 | let pairs = getPairs(word);
97 |
98 | if(pairs.length === 0) {
99 | return token+'';
100 | }
101 |
102 | while(1) {
103 |
104 | let bigram = null;
105 | let minRank = Infinity;
106 | for(let p of pairs) {
107 | let r = this.bpeRanks[p.join("·😎·")];
108 | if(r === undefined) continue;
109 | if(r < minRank) {
110 | minRank = r;
111 | bigram = p;
112 | }
113 | }
114 |
115 | if(bigram === null) {
116 | break;
117 | }
118 |
119 | let [first, second] = bigram;
120 | let newWord = [];
121 | let i = 0;
122 | while(i < word.length) {
123 |
124 | let j = word.indexOf(first, i);
125 |
126 | if(j === -1) {
127 | newWord.push(...word.slice(i));
128 | break;
129 | }
130 |
131 | newWord.push(...word.slice(i, j));
132 | i = j;
133 |
134 | if(word[i] === first && i < word.length-1 && word[i+1] === second) {
135 | newWord.push(first+second);
136 | i += 2;
137 | } else {
138 | newWord.push(word[i]);
139 | i += 1;
140 | }
141 | }
142 | word = newWord;
143 | if(word.length === 1) {
144 | break;
145 | } else {
146 | pairs = getPairs(word);
147 | }
148 | }
149 | word = word.join(" ");
150 | this.cache[token] = word;
151 | return word;
152 | }
153 |
154 | encode(text) {
155 | let bpeTokens = []
156 | text = whitespaceClean(text).toLowerCase();
157 | for(let token of [...text.matchAll(this.pat)].map(m => m[0])) {
158 | token = [...token].map(b => this.byteEncoder[b.charCodeAt(0)]).join("");
159 | bpeTokens.push(...this.bpe(token).split(' ').map(bpe_token => this.encoder[bpe_token]));
160 | }
161 | return bpeTokens;
162 | }
163 |
164 | // adds start and end token, and adds padding 0's and ensures it's 77 tokens long
165 | encodeForCLIP(text) {
166 | let tokens = this.encode(text);
167 | tokens.unshift(49406); // start token
168 | tokens = tokens.slice(0, 76);
169 | tokens.push(49407); // end token
170 | while(tokens.length < 77) tokens.push(49407);
171 | return tokens;
172 | }
173 |
174 | decode(tokens) {
175 | let text = tokens.map(token => this.decoder[token]).join("");
176 | text = [...text].map(c => this.byteDecoder[c]).map(v => String.fromCharCode(v)).join("").replaceAll('', ' ');
177 | return text;
178 | }
179 | }
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |