You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

492 lines
14 KiB

7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "network.h"
  2. #include "cost_layer.h"
  3. #include "utils.h"
  4. #include "blas.h"
  5. #include "parser.h"
  6. #ifdef OPENCV
  7. #include "opencv2/highgui/highgui_c.h"
  8. #endif
  9. typedef struct {
  10. float *x;
  11. float *y;
  12. } float_pair;
  13. int *read_tokenized_data(char *filename, size_t *read)
  14. {
  15. size_t size = 512;
  16. size_t count = 0;
  17. FILE *fp = fopen(filename, "r");
  18. int *d = (int*)calloc(size, sizeof(int));
  19. int n, one;
  20. one = fscanf(fp, "%d", &n);
  21. while(one == 1){
  22. ++count;
  23. if(count > size){
  24. size = size*2;
  25. d = (int*)realloc(d, size*sizeof(int));
  26. }
  27. d[count-1] = n;
  28. one = fscanf(fp, "%d", &n);
  29. }
  30. fclose(fp);
  31. d = (int*)realloc(d, count*sizeof(int));
  32. *read = count;
  33. return d;
  34. }
  35. char **read_tokens(char *filename, size_t *read)
  36. {
  37. size_t size = 512;
  38. size_t count = 0;
  39. FILE *fp = fopen(filename, "r");
  40. char **d = (char**)calloc(size, sizeof(char *));
  41. char *line;
  42. while((line=fgetl(fp)) != 0){
  43. ++count;
  44. if(count > size){
  45. size = size*2;
  46. d = (char**)realloc(d, size*sizeof(char *));
  47. }
  48. d[count-1] = line;
  49. }
  50. fclose(fp);
  51. d = (char**)realloc(d, count*sizeof(char *));
  52. *read = count;
  53. return d;
  54. }
  55. float_pair get_rnn_token_data(int *tokens, size_t *offsets, int characters, size_t len, int batch, int steps)
  56. {
  57. float *x = (float*)calloc(batch * steps * characters, sizeof(float));
  58. float *y = (float*)calloc(batch * steps * characters, sizeof(float));
  59. int i,j;
  60. for(i = 0; i < batch; ++i){
  61. for(j = 0; j < steps; ++j){
  62. int curr = tokens[(offsets[i])%len];
  63. int next = tokens[(offsets[i] + 1)%len];
  64. x[(j*batch + i)*characters + curr] = 1;
  65. y[(j*batch + i)*characters + next] = 1;
  66. offsets[i] = (offsets[i] + 1) % len;
  67. if(curr >= characters || curr < 0 || next >= characters || next < 0){
  68. error("Bad char");
  69. }
  70. }
  71. }
  72. float_pair p;
  73. p.x = x;
  74. p.y = y;
  75. return p;
  76. }
  77. float_pair get_rnn_data(unsigned char *text, size_t *offsets, int characters, size_t len, int batch, int steps)
  78. {
  79. float *x = (float*)calloc(batch * steps * characters, sizeof(float));
  80. float *y = (float*)calloc(batch * steps * characters, sizeof(float));
  81. int i,j;
  82. for(i = 0; i < batch; ++i){
  83. for(j = 0; j < steps; ++j){
  84. unsigned char curr = text[(offsets[i])%len];
  85. unsigned char next = text[(offsets[i] + 1)%len];
  86. x[(j*batch + i)*characters + curr] = 1;
  87. y[(j*batch + i)*characters + next] = 1;
  88. offsets[i] = (offsets[i] + 1) % len;
  89. if(curr > 255 || curr <= 0 || next > 255 || next <= 0){
  90. /*text[(index+j+2)%len] = 0;
  91. printf("%ld %d %d %d %d\n", index, j, len, (int)text[index+j], (int)text[index+j+1]);
  92. printf("%s", text+index);
  93. */
  94. error("Bad char");
  95. }
  96. }
  97. }
  98. float_pair p;
  99. p.x = x;
  100. p.y = y;
  101. return p;
  102. }
  103. void reset_rnn_state(network net, int b)
  104. {
  105. int i;
  106. for (i = 0; i < net.n; ++i) {
  107. #ifdef GPU
  108. layer l = net.layers[i];
  109. if(l.state_gpu){
  110. fill_ongpu(l.outputs, 0, l.state_gpu + l.outputs*b, 1);
  111. }
  112. #endif
  113. }
  114. }
  115. void train_char_rnn(char *cfgfile, char *weightfile, char *filename, int clear, int tokenized)
  116. {
  117. srand((unsigned int)time(0));
  118. unsigned char *text = 0;
  119. int *tokens = 0;
  120. size_t size;
  121. if(tokenized){
  122. tokens = read_tokenized_data(filename, &size);
  123. } else {
  124. FILE *fp = fopen(filename, "rb");
  125. fseek(fp, 0, SEEK_END);
  126. size = ftell(fp);
  127. fseek(fp, 0, SEEK_SET);
  128. text = (unsigned char*)calloc(size+1, sizeof(char));
  129. fread(text, 1, size, fp);
  130. fclose(fp);
  131. }
  132. char *backup_directory = "/home/pjreddie/backup/";
  133. char *base = basecfg(cfgfile);
  134. fprintf(stderr, "%s\n", base);
  135. float avg_loss = -1;
  136. network net = parse_network_cfg(cfgfile);
  137. if(weightfile){
  138. load_weights(&net, weightfile);
  139. }
  140. int inputs = get_network_input_size(net);
  141. fprintf(stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net.learning_rate, net.momentum, net.decay);
  142. int batch = net.batch;
  143. int steps = net.time_steps;
  144. if(clear) *net.seen = 0;
  145. int i = (*net.seen)/net.batch;
  146. int streams = batch/steps;
  147. size_t *offsets = (size_t*) calloc(streams, sizeof(size_t));
  148. int j;
  149. for(j = 0; j < streams; ++j){
  150. offsets[j] = rand_size_t()%size;
  151. }
  152. clock_t time;
  153. while(get_current_batch(net) < net.max_batches){
  154. i += 1;
  155. time=clock();
  156. float_pair p;
  157. if(tokenized){
  158. p = get_rnn_token_data(tokens, offsets, inputs, size, streams, steps);
  159. }else{
  160. p = get_rnn_data(text, offsets, inputs, size, streams, steps);
  161. }
  162. float loss = train_network_datum(net, p.x, p.y) / (batch);
  163. free(p.x);
  164. free(p.y);
  165. if (avg_loss < 0) avg_loss = loss;
  166. avg_loss = avg_loss*.9f + loss*.1f;
  167. int chars = get_current_batch(net)*batch;
  168. fprintf(stderr, "%d: %f, %f avg, %f rate, %lf seconds, %f epochs\n", i, loss, avg_loss, get_current_rate(net), sec(clock()-time), (float) chars/size);
  169. for(j = 0; j < streams; ++j){
  170. //printf("%d\n", j);
  171. if(rand()%10 == 0){
  172. //fprintf(stderr, "Reset\n");
  173. offsets[j] = rand_size_t()%size;
  174. reset_rnn_state(net, j);
  175. }
  176. }
  177. if(i%1000==0){
  178. char buff[256];
  179. sprintf(buff, "%s/%s_%d.weights", backup_directory, base, i);
  180. save_weights(net, buff);
  181. }
  182. if(i%10==0){
  183. char buff[256];
  184. sprintf(buff, "%s/%s.backup", backup_directory, base);
  185. save_weights(net, buff);
  186. }
  187. }
  188. char buff[256];
  189. sprintf(buff, "%s/%s_final.weights", backup_directory, base);
  190. save_weights(net, buff);
  191. }
  192. void print_symbol(int n, char **tokens){
  193. if(tokens){
  194. printf("%s ", tokens[n]);
  195. } else {
  196. printf("%c", n);
  197. }
  198. }
  199. void test_char_rnn(char *cfgfile, char *weightfile, int num, char *seed, float temp, int rseed, char *token_file)
  200. {
  201. char **tokens = 0;
  202. if(token_file){
  203. size_t n;
  204. tokens = read_tokens(token_file, &n);
  205. }
  206. srand(rseed);
  207. char *base = basecfg(cfgfile);
  208. fprintf(stderr, "%s\n", base);
  209. network net = parse_network_cfg(cfgfile);
  210. if(weightfile){
  211. load_weights(&net, weightfile);
  212. }
  213. int inputs = get_network_input_size(net);
  214. int i, j;
  215. for(i = 0; i < net.n; ++i) net.layers[i].temperature = temp;
  216. int c = 0;
  217. int len = (int)strlen(seed);
  218. float *input = (float*)calloc(inputs, sizeof(float));
  219. /*
  220. fill_cpu(inputs, 0, input, 1);
  221. for(i = 0; i < 10; ++i){
  222. network_predict(net, input);
  223. }
  224. fill_cpu(inputs, 0, input, 1);
  225. */
  226. for(i = 0; i < len-1; ++i){
  227. c = seed[i];
  228. input[c] = 1;
  229. network_predict(net, input);
  230. input[c] = 0;
  231. print_symbol(c, tokens);
  232. }
  233. if(len) c = seed[len-1];
  234. print_symbol(c, tokens);
  235. for(i = 0; i < num; ++i){
  236. input[c] = 1;
  237. float *out = network_predict(net, input);
  238. input[c] = 0;
  239. for(j = 32; j < 127; ++j){
  240. //printf("%d %c %f\n",j, j, out[j]);
  241. }
  242. for(j = 0; j < inputs; ++j){
  243. if (out[j] < .0001) out[j] = 0;
  244. }
  245. c = sample_array(out, inputs);
  246. print_symbol(c, tokens);
  247. }
  248. printf("\n");
  249. }
  250. void test_tactic_rnn(char *cfgfile, char *weightfile, int num, float temp, int rseed, char *token_file)
  251. {
  252. char **tokens = 0;
  253. if(token_file){
  254. size_t n;
  255. tokens = read_tokens(token_file, &n);
  256. }
  257. srand(rseed);
  258. char *base = basecfg(cfgfile);
  259. fprintf(stderr, "%s\n", base);
  260. network net = parse_network_cfg(cfgfile);
  261. if(weightfile){
  262. load_weights(&net, weightfile);
  263. }
  264. int inputs = get_network_input_size(net);
  265. int i, j;
  266. for(i = 0; i < net.n; ++i) net.layers[i].temperature = temp;
  267. int c = 0;
  268. float *input = (float*)calloc(inputs, sizeof(float));
  269. float *out = 0;
  270. while((c = getc(stdin)) != EOF){
  271. input[c] = 1;
  272. out = network_predict(net, input);
  273. input[c] = 0;
  274. }
  275. for(i = 0; i < num; ++i){
  276. for(j = 0; j < inputs; ++j){
  277. if (out[j] < .0001) out[j] = 0;
  278. }
  279. int next = sample_array(out, inputs);
  280. if(c == '.' && next == '\n') break;
  281. c = next;
  282. print_symbol(c, tokens);
  283. input[c] = 1;
  284. out = network_predict(net, input);
  285. input[c] = 0;
  286. }
  287. printf("\n");
  288. }
  289. void valid_tactic_rnn(char *cfgfile, char *weightfile, char *seed)
  290. {
  291. char *base = basecfg(cfgfile);
  292. fprintf(stderr, "%s\n", base);
  293. network net = parse_network_cfg(cfgfile);
  294. if(weightfile){
  295. load_weights(&net, weightfile);
  296. }
  297. int inputs = get_network_input_size(net);
  298. int count = 0;
  299. int words = 1;
  300. int c;
  301. int len = (int)strlen(seed);
  302. float *input = (float*)calloc(inputs, sizeof(float));
  303. int i;
  304. for(i = 0; i < len; ++i){
  305. c = seed[i];
  306. input[(int)c] = 1;
  307. network_predict(net, input);
  308. input[(int)c] = 0;
  309. }
  310. float sum = 0;
  311. c = getc(stdin);
  312. float log2 = (float)log(2.f);
  313. int in = 0;
  314. while(c != EOF){
  315. int next = getc(stdin);
  316. if(next == EOF) break;
  317. if(next < 0 || next >= 255) error("Out of range character");
  318. input[c] = 1;
  319. float *out = network_predict(net, input);
  320. input[c] = 0;
  321. if(c == '.' && next == '\n') in = 0;
  322. if(!in) {
  323. if(c == '>' && next == '>'){
  324. in = 1;
  325. ++words;
  326. }
  327. c = next;
  328. continue;
  329. }
  330. ++count;
  331. sum += (float)log(out[next])/log2;
  332. c = next;
  333. printf("%d %d Perplexity: %4.4f Word Perplexity: %4.4f\n", count, words, pow(2, -sum/count), pow(2, -sum/words));
  334. }
  335. }
  336. void valid_char_rnn(char *cfgfile, char *weightfile, char *seed)
  337. {
  338. char *base = basecfg(cfgfile);
  339. fprintf(stderr, "%s\n", base);
  340. network net = parse_network_cfg(cfgfile);
  341. if(weightfile){
  342. load_weights(&net, weightfile);
  343. }
  344. int inputs = get_network_input_size(net);
  345. int count = 0;
  346. int words = 1;
  347. int c;
  348. int len = (int)strlen(seed);
  349. float *input =(float*)calloc(inputs, sizeof(float));
  350. int i;
  351. for(i = 0; i < len; ++i){
  352. c = seed[i];
  353. input[(int)c] = 1;
  354. network_predict(net, input);
  355. input[(int)c] = 0;
  356. }
  357. float sum = 0;
  358. c = getc(stdin);
  359. float log2 = (float)log(2.f);
  360. while(c != EOF){
  361. int next = getc(stdin);
  362. if(next == EOF) break;
  363. if(next < 0 || next >= 255) error("Out of range character");
  364. ++count;
  365. if(next == ' ' || next == '\n' || next == '\t') ++words;
  366. input[c] = 1;
  367. float *out = network_predict(net, input);
  368. input[c] = 0;
  369. sum += (float)log(out[next])/log2;
  370. c = next;
  371. printf("%d Perplexity: %4.4f Word Perplexity: %4.4f\n", count, pow(2, -sum/count), pow(2, -sum/words));
  372. }
  373. }
  374. void vec_char_rnn(char *cfgfile, char *weightfile, char *seed)
  375. {
  376. char *base = basecfg(cfgfile);
  377. fprintf(stderr, "%s\n", base);
  378. network net = parse_network_cfg(cfgfile);
  379. if(weightfile){
  380. load_weights(&net, weightfile);
  381. }
  382. int inputs = get_network_input_size(net);
  383. int c;
  384. int seed_len = (int)strlen(seed);
  385. float *input = (float*)calloc(inputs, sizeof(float));
  386. int i;
  387. char *line;
  388. while((line=fgetl(stdin)) != 0){
  389. reset_rnn_state(net, 0);
  390. for(i = 0; i < seed_len; ++i){
  391. c = seed[i];
  392. input[(int)c] = 1;
  393. network_predict(net, input);
  394. input[(int)c] = 0;
  395. }
  396. strip(line);
  397. int str_len = (int)strlen(line);
  398. for(i = 0; i < str_len; ++i){
  399. c = line[i];
  400. input[(int)c] = 1;
  401. network_predict(net, input);
  402. input[(int)c] = 0;
  403. }
  404. c = ' ';
  405. input[(int)c] = 1;
  406. network_predict(net, input);
  407. input[(int)c] = 0;
  408. layer l = net.layers[0];
  409. #ifdef GPU
  410. cuda_pull_array(l.output_gpu, l.output, l.outputs);
  411. #endif
  412. printf("%s", line);
  413. for(i = 0; i < l.outputs; ++i){
  414. printf(",%g", l.output[i]);
  415. }
  416. printf("\n");
  417. }
  418. }
  419. void run_char_rnn(int argc, char **argv)
  420. {
  421. if(argc < 4){
  422. fprintf(stderr, "usage: %s %s [train/test/valid] [cfg] [weights (optional)]\n", argv[0], argv[1]);
  423. return;
  424. }
  425. char *filename = find_char_arg(argc, argv, "-file", "data/shakespeare.txt");
  426. char *seed = find_char_arg(argc, argv, "-seed", "\n\n");
  427. int len = find_int_arg(argc, argv, "-len", 1000);
  428. float temp = find_float_arg(argc, argv, "-temp", .7f);
  429. int rseed = find_int_arg(argc, argv, "-srand", (int)time(0));
  430. int clear = find_arg(argc, argv, "-clear");
  431. int tokenized = find_arg(argc, argv, "-tokenized");
  432. char *tokens = find_char_arg(argc, argv, "-tokens", 0);
  433. char *cfg = argv[3];
  434. char *weights = (argc > 4) ? argv[4] : 0;
  435. if(0==strcmp(argv[2], "train")) train_char_rnn(cfg, weights, filename, clear, tokenized);
  436. else if(0==strcmp(argv[2], "valid")) valid_char_rnn(cfg, weights, seed);
  437. else if(0==strcmp(argv[2], "validtactic")) valid_tactic_rnn(cfg, weights, seed);
  438. else if(0==strcmp(argv[2], "vec")) vec_char_rnn(cfg, weights, seed);
  439. else if(0==strcmp(argv[2], "generate")) test_char_rnn(cfg, weights, len, seed, temp, rseed, tokens);
  440. else if(0==strcmp(argv[2], "generatetactic")) test_tactic_rnn(cfg, weights, len, temp, rseed, tokens);
  441. }