Debian Codegraph @

examples/ai/word2vec/word2vec-prompt.ck

raw
1 //------------------------------------------------------------------------------
2 // name: word2vec-prompt.ck
3 // desc: word2vec interative prompt explorer
4 //
5 // version: need chuck version 1.5.0.0 or higher
6 // sorting: part of ChAI (ChucK for AI)
7 //
8 // NOTE: this requires ConsoleInput which needs command line chuck
9 // NOTE: download pre-trained word vector model from:
10 // https://chuck.stanford.edu/chai/data/glove/
11 // | (can use any of these)
12 // glove-wiki-gigaword-50.txt (400000 words x 50 dimensions)
13 // glove-wiki-gigaword-50-pca-3.txt (400000 words x 3 dimensions)
14 // glove-wiki-gigaword-50-tsne-2.txt (400000 words x 2 dimensions)
15 //
16 // author: Yikai Li and Ge Wang
17 // date: Spring 2023
18 //------------------------------------------------------------------------------
19
20 // make a ConsoleInput
21 ConsoleInput in;
22 // tokenizer
23 StringTokenizer tok;
24 // line
25 string line[0];
26
27 // our default model
28 Word2Vec model;
29
30 // loading any default here
31 "glove-wiki-gigaword-50.txt" => string filepath;
32 <<< "loading model:", filepath, "..." >>>;
33 // load model
34 if( !model.load( me.dir() + filepath ) )
35 {
36 <<< "cannot load model file...", "" >>>;
37 me.exit();
38 }
39 // print info about model
40 print( model );
41
42 ModalBar bar => NRev reverb => dac;
43 SndBuf doh => reverb => dac;
44 "special:dope" => doh.read;
45 0 => doh.gain;
46
47 // print info about a loaded Word2Vec model
48 fun void print( Word2Vec model )
49 {
50 // print info
51 <<< "dictionary size:", model.size() >>>;
52 <<< "embedding dimensions:", model.dim() >>>;
53 <<< "using KDTree for search:", model.useKDTree() ? "YES" : "NO" >>>;
54 // get bounds
55 float mins[0], maxs[0];
56 model.minMax( mins, maxs );
57 for( int i; i < model.dim(); i++ )
58 { cherr <= "dimension " <= i <= " range: [" <= mins[i] <= ", "
59 <= maxs[i] <= "]" <= IO.newline(); }
60 }
61
62 // loop
63 while( true )
64 {
65 // prompt
66 in.prompt( "word2vec2chuck => " ) => now;
67
68 // read
69 while( in.more() )
70 {
71 // get it
72 tok.set( in.getLine() );
73 // clear array
74 line.clear();
75 // print tokens
76 while( tok.more() )
77 {
78 // put into array
79 line << tok.next().lower();
80 // print it
81 // <<< line[line.size()-1], "" >>>;
82 }
83 // if non-empty
84 if( line.size() )
85 {
86 // execute
87 execute( line) => int result;
88 }
89 }
90 }
91
92
93 fun int execute( string line[] )
94 {
95 // check
96 line[0] => string command;
97 // index
98 1 => int index;
99
100 // which command
101 if( command == "quit" || command == "exit" )
102 {
103 // exit shred
104 me.exit();
105 }
106 else if( command == "help" || command == "h" )
107 {
108 <<< " available word2vec2chuck commands:", "" >>>;
109 <<< " load / l -- load a pre-trained model", "" >>>;
110 <<< " eval / e -- evaluate a word vector expression", "" >>>;
111 <<< " analog / a -- query a logical analogy", "" >>>;
112 <<< " vector / v -- display vector associated with a word", "" >>>;
113 <<< " go / g -- from a word to another across a duration", "" >>>;
114 <<< " similar / s -- from a vector (model size) return similar words", "" >>>;
115 <<< " print / p -- print model info", "" >>>;
116 <<< " help / h -- print this message", "" >>>;
117 <<< " exit / quit -- exit from word2vec2chuck", "" >>>;
118 <<< " load-50 -- load GloVe 50D model (glove-wiki-gigaword-50)", "" >>>;
119 <<< " load-3 -- load PCA 3D model (glove-wiki-gigaword-50-pca-3)", "" >>>;
120 <<< " load-2 -- load t-SNE 2D model (glove-wiki-gigaword-50-tsne-2)", "" >>>;
121 }
122 else if( command == "load" || command == "l" )
123 {
124 if( line.size() < 2 )
125 {
126 <<< "usage: load [model]", "" >>>;
127 }
128 else
129 {
130 // get filepath to load
131 line[1] => filepath;
132 <<< "loading model:", filepath >>>;
133 <<< "(this could take a few seconds)...", "" >>>;
134 // load
135 if( !model.load( me.dir() + filepath ) )
136 {
137 <<< "cannot load model file...", "" >>>;
138 return 1;
139 }
140 // print info
141 print( model );
142 }
143 }
144 else if( command == "print" || command == "p" )
145 {
146 if( model.size() == 0 )
147 {
148 <<< " no model has been loaded yet.", "" >>>;
149 }
150 else
151 {
152 // print info
153 print( model );
154 }
155 }
156 else if( command == "load-50" || command == "load-3" || command == "load-2" )
157 {
158 string filepath;
159 if( command == "load-50" ) "glove-wiki-gigaword-50.txt" => filepath;
160 else if( command == "load-3" ) "glove-wiki-gigaword-50-pca-3.txt" => filepath;
161 else "glove-wiki-gigaword-50-tsne-2.txt" => filepath;
162
163 <<< "loading model:", filepath >>>;
164 <<< "(this could take a few seconds)...", "" >>>;
165 // load
166 if( !model.load( me.dir() + filepath ) )
167 {
168 <<< "cannot load model file...", "" >>>;
169 return 1;
170 }
171 // print info
172 print( model );
173 }
174 else if( command == "eval" || command == "e" )
175 {
176 if( line.size() < 2 )
177 {
178 <<< "usage: eval [word expression]", "" >>>;
179 <<< " for example: eval rome - italy + china", "" >>>;
180 <<< " (note: don't forget white spaces around + and -)", "" >>>;
181 }
182 else
183 {
184 // expression string
185 line[1] => string expr;
186 // concatenate
187 for( 2 => int i; i < line.size(); i++ )
188 { expr + " " + line[i] => expr; }
189 // eval
190 W2V.eval( model, expr, 10 ) @=> string words[];
191 // print search results
192 for (0 => int i; i < words.size(); i++)
193 { <<< " ", words[i], "" >>>; }
194 }
195 }
196 else if( command == "analog" || command == "a" )
197 {
198 if( line.size() < 4 )
199 {
200 <<< "usage: analog [wordA] [wordB] [wordC]", "" >>>;
201 <<< " for example: analog cat kitten dog", "" >>>;
202 }
203 else
204 {
205 // expression string
206 line[1] => string a;
207 line[2] => string b;
208 line[3] => string c;
209 // eval
210 W2V.analogy( model, a, b, c, 10 ) @=> string words[];
211 // print
212 <<< a, "is to", b, "as", c, "is to..." >>>;
213 for (0 => int i; i < words.size(); i++)
214 {
215 // trivially reject a b c in the output
216 if( words[i] == a || words[i] == b || words[i] == c ) continue;
217 <<< " ", words[i], "" >>>;
218 }
219 }
220 }
221 else if( command == "vector" || command == "v" )
222 {
223 if( line.size() < 2 )
224 {
225 <<< "usage: vector [word]", "" >>>;
226 }
227 else
228 {
229 float vector[model.dim()];
230 model.getVector( line[1], vector );
231 // print
232 cherr <= line[1] <= ": ";
233 for( int i; i < vector.size(); i++ ) { cherr <= vector[i] <= " "; }
234 cherr <= IO.newline();
235 }
236 }
237 else if( command == "go" || command == "g" )
238 {
239 if( line.size() < 5 )
240 {
241 <<< "usage: go [word/start] [word/end] [second] [steps] [k results]", "" >>>;
242 }
243 else
244 {
245 <<< "going from", line[1], "to", line[2], "over", line[3], "seconds in", line[4], "steps" >>>;
246 float coord1[model.dim()], coord2[model.dim()];
247 model.getVector(line[1], coord1);
248 model.getVector(line[2], coord2);
249
250 // print coordinate 1
251 // cherr <= line[1] <= ": ";
252 // for( int i; i < coord1.size(); i++ ) { cherr <= coord1[i] <= " "; }
253 // cherr <= IO.newline();
254
255 // print coordinate 2
256 // cherr <= line[2] <= ": ";
257 // for( int i; i < coord2.size(); i++ ) { cherr <= coord2[i] <= " "; }
258 // cherr <= IO.newline();
259
260 // walk
261 1 => int k;
262 if( line.size() > 5 ) Std.atoi(line[5]) => k;
263 go( line[1], line[2], Std.atof(line[3])::second, Std.atoi(line[4]), k );
264 }
265 }
266 else if( command == "similar" || command == "s" )
267 {
268 if( line.size() != model.dim()+1)
269 {
270 <<< "usage: similar [float] [float] ... model dimension", "" >>>;
271 }
272 else
273 {
274 string results[10];
275 model.getSimilar( [Std.atof(line[1]),Std.atof(line[2])], 10, results );
276 for( int i; i < results.size(); i++ )<<< results[i]>>>;
277 }
278 }
279 else
280 {
281 // not found
282 <<< " command not found:", command >>>;
283 }
284
285 return 0; // 0 is good
286 }
287
288
289 fun void sonifyDoh( float params[], float vstart[], float vend[] )
290 {
291 if( params.size() < 2 )
292 {
293 <<< "not enough params!", "" >>>;
294 return;
295 }
296
297 // use param 1 for volume
298 Math.remap(params[0], vstart[0], vend[0], .1, 1 ) => doh.gain;
299 // use param 2 for rate
300 Math.remap(params[1], vstart[1], vend[1], 1, 1.5 ) => doh.rate;
301
302 // trigger from beginning
303 0 => doh.pos;
304 }
305
306
307 // this goes from one word to another word
308 // > go fun disaster 5 30 1
309 // > go technology famine 4 20
310 fun void go( string start, string end, dur T, int steps, int k )
311 {
312 float vstart[model.dim()], vend[model.dim()];
313 model.getVector(start, vstart);
314 model.getVector(end, vend);
315
316 // get bounds for mapping
317 float mins[0], maxs[0];
318 model.minMax( mins, maxs );
319
320 // duplicate
321 W2V.dup( vend ) @=> float vdiff[];
322 W2V.dup( vstart ) @=> float v[];
323
324 for( int i; i < vstart.size(); i++ ) { cherr <= vstart[i] <= " "; } cherr <= IO.newline();
325 for( int i; i < vend.size(); i++ ) { cherr <= vend[i] <= " "; } cherr <= IO.newline();
326
327 W2V.minus( vdiff, vstart );
328
329 // increment
330 1.0 / steps => float inc;
331 // time step
332 T * inc => dur Tstep;
333 // scale
334 0 => float factor;
335
336 string results[k];
337 float coord[model.dim()];
338
339 // take the steps
340 for( int i; i < steps+1; i++ )
341 {
342 // scale difference vector
343 W2V.scale( v, vdiff, factor );
344 inc +=> factor;
345 // add
346 W2V.add( v, vstart );
347 // search
348 model.getSimilar( v, k, results);
349 results[Math.random2(0,k-1)] => string word;
350 model.getVector( word, coord );
351
352 // print
353 <<< i, "->", word >>>;
354
355 // sonify
356 sonifyDoh( coord, vstart, vend);
357 // for( int i; i < v.size(); i++ ) { cherr <= v[i] <= " "; }
358 // cherr <= IO.newline();
359
360 // advance time
361 Tstep => now;
362 }
363 }
364
365
366 // word2vec helper
367 class W2V
368 {
369 fun static void copy( float to[], float from[] )
370 {
371 to.size(from.size());
372 // add into element
373 for( int i; i < to.size(); i++ ) from[i] => to[i];
374 }
375
376 fun static float[] dup( float from[] )
377 {
378 float to[from.size()];
379 // add into element
380 for( int i; i < to.size(); i++ ) from[i] => to[i];
381 // return
382 return to;
383 }
384
385 // result stored in x
386 fun static void add( float x[], float y[] )
387 {
388 // smaller of the two
389 x.size() < y.size() ? x.size() : y.size() => int size;
390 // add into element
391 for( int i; i < size; i++ ) y[i] +=> x[i];
392 }
393
394 // result stored in x
395 fun static void minus( float x[], float y[] )
396 {
397 // smaller of the two
398 x.size() < y.size() ? x.size() : y.size() => int size;
399 // add into element
400 for( int i; i < size; i++ ) y[i] -=> x[i];
401 }
402
403 fun static void scale( float x[], float scalar )
404 {
405 // scale
406 for( int i; i < x.size(); i++ ) scalar *=> x[i];
407 }
408
409 fun static void scale( float result[], float x[], float scalar )
410 {
411 // scale
412 for( int i; i < x.size(); i++ ) scalar * x[i] => result[i];
413 }
414
415 fun static string[] eval( Word2Vec @ w, string expr, int k )
416 {
417 // init
418 int pos;
419 1.0 => float multiplier;
420 string word;
421 float wordVector[w.dim()];
422 float exprVector[w.dim()];
423
424 // compute
425 while( true )
426 {
427 expr.find(" ") => pos;
428 if( pos == -1 )
429 {
430 w.getVector(expr, wordVector);
431 for( 0 => int i; i < w.dim(); i++ )
432 {
433 wordVector[i] * multiplier +=> exprVector[i];
434 }
435 break;
436 }
437 else
438 {
439 expr.substring(0, pos) => word;
440 w.getVector(word, wordVector);
441 for( 0 => int i; i < w.dim(); i++ )
442 {
443 wordVector[i] * multiplier +=> exprVector[i];
444 }
445 expr.substring(pos + 1) => expr;
446 if( expr.charAt(0) == '+' )
447 {
448 1.0 => multiplier;
449 expr.substring(2) => expr;
450 }
451 else
452 {
453 -1.0 => multiplier;
454 expr.substring(2) => expr;
455 }
456 }
457 }
458
459 // return
460 string results[k];
461 w.getSimilar( exprVector, k, results );
462
463 return results;
464 }
465
466 // logical analogy: A to B is as C is to [what this function returns]
467 fun static string[] analogy( Word2Vec @ w, string A, string B, string C, int k )
468 {
469 // the vector sum
470 B + " - " + A + " + " + C => string v;
471 return eval( w, v, k );
472 }
473 }