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.

530 lines
13 KiB

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