-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
parse_args.cc
1626 lines (1405 loc) · 57.2 KB
/
parse_args.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved. Released under a BSD (revised)
license as described in the file LICENSE.
*/
#include <stdio.h>
#include <float.h>
#include <sstream>
#include <fstream>
//#include <boost/filesystem.hpp>
#include <sys/types.h>
#include <sys/stat.h>
#include <algorithm>
#include "parse_regressor.h"
#include "parser.h"
#include "parse_primitives.h"
#include "vw.h"
#include "interactions.h"
#include "sender.h"
#include "nn.h"
#include "gd.h"
#include "cbify.h"
#include "oaa.h"
#include "boosting.h"
#include "multilabel_oaa.h"
#include "rand48.h"
#include "bs.h"
#include "topk.h"
#include "ect.h"
#include "csoaa.h"
#include "cb_algs.h"
#include "cb_adf.h"
#include "cb_explore.h"
#include "cb_explore_adf.h"
#include "mwt.h"
#include "confidence.h"
#include "scorer.h"
#include "expreplay.h"
#include "search.h"
#include "bfgs.h"
#include "lda_core.h"
#include "noop.h"
#include "print.h"
#include "gd_mf.h"
#include "learner.h"
#include "mf.h"
#include "ftrl.h"
#include "svrg.h"
#include "rand48.h"
#include "binary.h"
#include "lrq.h"
#include "lrqfa.h"
#include "autolink.h"
#include "log_multi.h"
#include "recall_tree.h"
#include "stagewise_poly.h"
#include "active.h"
#include "active_cover.h"
#include "cs_active.h"
#include "kernel_svm.h"
#include "parse_example.h"
#include "best_constant.h"
#include "interact.h"
#include "vw_exception.h"
#include "accumulate.h"
#include "vw_validate.h"
#include "vw_allreduce.h"
#include "OjaNewton.h"
#include "audit_regressor.h"
#include "marginal.h"
#include "explore_eval.h"
#include "baseline.h"
#include "classweight.h"
// #include "cntk.h"
using namespace std;
//
// Does string end with a certain substring?
//
bool ends_with(string const &fullString, string const &ending)
{
if (fullString.length() > ending.length())
{
return (fullString.compare(fullString.length() - ending.length(), ending.length(), ending) == 0);
}
else
{
return false;
}
}
unsigned long long hash_file_contents(io_buf *io, int f)
{
unsigned long long v = 5289374183516789128;
unsigned char buf[1024];
while (true)
{
ssize_t n = io->read_file(f, buf, 1024);
if (n <= 0) break;
for (ssize_t i=0; i<n; i++)
{
v *= 341789041;
v += buf[i];
}
}
return v;
}
bool directory_exists(string path)
{
struct stat info;
if (stat(path.c_str(), &info) != 0)
return false;
else
return (info.st_mode & S_IFDIR) > 0;
// boost::filesystem::path p(path);
// return boost::filesystem::exists(p) && boost::filesystem::is_directory(p);
}
string find_in_path(vector<string> paths, string fname)
{
#ifdef _WIN32
string delimiter = "\\";
#else
string delimiter = "/";
#endif
for (string path : paths)
{
string full = ends_with(path, delimiter) ? (path + fname) : (path + delimiter + fname);
ifstream f(full.c_str());
if (f.good())
return full;
}
return "";
}
void parse_dictionary_argument(vw&all, string str)
{
if (str.length() == 0) return;
// expecting 'namespace:file', for instance 'w:foo.txt'
// in the case of just 'foo.txt' it's applied to the default namespace
char ns = ' ';
const char*s = str.c_str();
if ((str.length() > 2) && (str[1] == ':'))
{
ns = str[0];
s += 2;
}
string fname = find_in_path(all.dictionary_path, string(s));
if (fname == "")
THROW("error: cannot find dictionary '" << s << "' in path; try adding --dictionary_path");
bool is_gzip = ends_with(fname, ".gz");
io_buf* io = is_gzip ? new comp_io_buf : new io_buf;
int fd = io->open_file(fname.c_str(), all.stdin_off, io_buf::READ);
if (fd < 0)
THROW("error: cannot read dictionary from file '" << fname << "'" << ", opening failed");
unsigned long long fd_hash = hash_file_contents(io, fd);
io->close_file();
if (! all.quiet)
all.opts_n_args.trace_message << "scanned dictionary '" << s << "' from '" << fname << "', hash=" << hex << fd_hash << dec << endl;
// see if we've already read this dictionary
for (size_t id=0; id<all.loaded_dictionaries.size(); id++)
if (all.loaded_dictionaries[id].file_hash == fd_hash)
{
all.namespace_dictionaries[(size_t)ns].push_back(all.loaded_dictionaries[id].dict);
io->close_file();
delete io;
return;
}
fd = io->open_file(fname.c_str(), all.stdin_off, io_buf::READ);
if (fd < 0)
{
delete io;
THROW("error: cannot re-read dictionary from file '" << fname << "'" << ", opening failed");
}
feature_dict* map = &calloc_or_throw<feature_dict>();
map->init(1023, nullptr, substring_equal);
example *ec = VW::alloc_examples(all.p->lp.label_size, 1);
size_t def = (size_t)' ';
ssize_t size = 2048, pos, nread;
char rc;
char*buffer = calloc_or_throw<char>(size);
do
{
pos = 0;
do
{
nread = io->read_file(fd, &rc, 1);
if ((rc != EOF) && (nread > 0)) buffer[pos++] = rc;
if (pos >= size - 1)
{
size *= 2;
const auto new_buffer = (char*)(realloc(buffer, size));
if (new_buffer == nullptr)
{
free(buffer);
free(ec);
VW::dealloc_example(all.p->lp.delete_label, *ec);
delete map;
io->close_file();
delete io;
THROW("error: memory allocation failed in reading dictionary");
}
else
buffer = new_buffer;
}
}
while ( (rc != EOF) && (rc != '\n') && (nread > 0) );
buffer[pos] = 0;
// we now have a line in buffer
char* c = buffer;
while (*c == ' ' || *c == '\t') ++c; // skip initial whitespace
char* d = c;
while (*d != ' ' && *d != '\t' && *d != '\n' && *d != '\0') ++d; // gobble up initial word
if (d == c) continue; // no word
if (*d != ' ' && *d != '\t') continue; // reached end of line
char* word = calloc_or_throw<char>(d-c);
memcpy(word, c, d-c);
substring ss = { word, word + (d - c) };
uint64_t hash = uniform_hash( ss.begin, ss.end-ss.begin, quadratic_constant);
if (map->get(ss, hash) != nullptr) // don't overwrite old values!
{
free(word);
continue;
}
d--;
*d = '|'; // set up for parser::read_line
VW::read_line(all, ec, d);
// now we just need to grab stuff from the default namespace of ec!
if (ec->feature_space[def].size() == 0)
{
free(word);
continue;
}
features* arr = new features;
arr->deep_copy_from(ec->feature_space[def]);
map->put(ss, hash, arr);
// clear up ec
ec->tag.erase(); ec->indices.erase();
for (size_t i=0; i<256; i++) { ec->feature_space[i].erase();}
}
while ((rc != EOF) && (nread > 0));
free(buffer);
io->close_file();
delete io;
VW::dealloc_example(all.p->lp.delete_label, *ec);
free(ec);
if (! all.quiet)
all.opts_n_args.trace_message << "dictionary " << s << " contains " << map->size() << " item" << (map->size() == 1 ? "" : "s") << endl;
all.namespace_dictionaries[(size_t)ns].push_back(map);
dictionary_info info = { calloc_or_throw<char>(strlen(s)+1), fd_hash, map };
strcpy(info.name, s);
all.loaded_dictionaries.push_back(info);
}
void parse_affix_argument(vw&all, string str)
{
if (str.length() == 0) return;
char* cstr = calloc_or_throw<char>(str.length()+1);
strcpy(cstr, str.c_str());
char*p = strtok(cstr, ",");
try
{
while (p != 0)
{
char*q = p;
uint16_t prefix = 1;
if (q[0] == '+') { q++; }
else if (q[0] == '-') { prefix = 0; q++; }
if ((q[0] < '1') || (q[0] > '7'))
THROW("malformed affix argument (length must be 1..7): " << p);
uint16_t len = (uint16_t)(q[0] - '0');
uint16_t ns = (uint16_t)' '; // default namespace
if (q[1] != 0)
{
if (valid_ns(q[1]))
ns = (uint16_t)q[1];
else
THROW("malformed affix argument (invalid namespace): " << p);
if (q[2] != 0)
THROW("malformed affix argument (too long): " << p);
}
uint16_t afx = (len << 1) | (prefix & 0x1);
all.affix_features[ns] <<= 4;
all.affix_features[ns] |= afx;
p = strtok(nullptr, ",");
}
}
catch(...)
{
free(cstr);
throw;
}
free(cstr);
}
void parse_diagnostics(arguments& arg)
{
if (arg.new_options("Diagnostic options")
("version","Version information")
(arg.all->audit, "audit,a", "print weights of features")
("progress,P", po::value< string >(), "Progress update frequency. int: additive, float: multiplicative")
(arg.all->quiet, "quiet", "Don't output disgnostics and progress updates")
("help,h","Look here: http://hunch.net/~vw/ and click on Tutorial.").missing())
return;
if (arg.vm.count("version"))
{ /* upon direct query for version -- spit it out to stdout */
cout << version.to_string() << "\n";
exit(0);
}
if (arg.vm.count("progress") && !arg.all->quiet)
{
string progress_str = arg.vm["progress"].as<string>();
arg.all->progress_arg = (float)::atof(progress_str.c_str());
// --progress interval is dual: either integer or floating-point
if (progress_str.find_first_of(".") == string::npos)
{
// No "." in arg: assume integer -> additive
arg.all->progress_add = true;
if (arg.all->progress_arg < 1)
{
arg.trace_message << "warning: additive --progress <int>"
<< " can't be < 1: forcing to 1" << endl;
arg.all->progress_arg = 1;
}
arg.all->sd->dump_interval = arg.all->progress_arg;
}
else
{
// A "." in arg: assume floating-point -> multiplicative
arg.all->progress_add = false;
if (arg.all->progress_arg <= 1.0)
{
arg.trace_message << "warning: multiplicative --progress <float>: "
<< arg.vm["progress"].as<string>()
<< " is <= 1.0: adding 1.0"
<< endl;
arg.all->progress_arg += 1.0;
}
else if (arg.all->progress_arg > 9.0)
{
arg.trace_message << "warning: multiplicative --progress <float>"
<< " is > 9.0: you probably meant to use an integer"
<< endl;
}
arg.all->sd->dump_interval = 1.0;
}
}
}
void parse_source(arguments& arg)
{
arg.new_options("Input options")
("data,d", arg.all->data_filename, "Example Set")
("daemon", "persistent daemon mode on port 26542")
("foreground", "in persistent daemon mode, do not run in the background")
("port", po::value<size_t>(),"port to listen on; use 0 to pick unused port")
("num_children", arg.all->num_children, "number of children for persistent daemon mode")
("pid_file", po::value< string >(), "Write pid file in persistent daemon mode")
("port_file", po::value< string >(), "Write port used in persistent daemon mode")
("cache,c", "Use a cache. The default is <data>.cache")
("cache_file", po::value< vector<string> >(), "The location(s) of cache_file.")
("json", "Enable JSON parsing.")
("dsjson", "Enable Decision Service JSON parsing.")
("kill_cache,k", "do not reuse existing cache: create a new one always")
("compressed", "use gzip format whenever possible. If a cache file is being created, this option creates a compressed cache file. A mixture of raw-text & compressed inputs are supported with autodetection.")
(arg.all->stdin_off, "no_stdin", "do not default to reading from stdin").missing();
// Be friendly: if -d was left out, treat positional param as data file
po::positional_options_description p;
p.add("data", -1);
po::parsed_options pos = po::command_line_parser(arg.args).
style(po::command_line_style::default_style ^ po::command_line_style::allow_guessing).
options(arg.opts).positional(p).run();
arg.vm = po::variables_map();
po::store(pos, arg.vm);
if (arg.vm.count("data") > 0)
arg.all->data_filename = arg.vm["data"].as<string>();
if ( (arg.vm.count("total") || arg.vm.count("node") || arg.vm.count("unique_id")) && !(arg.vm.count("total") && arg.vm.count("node") && arg.vm.count("unique_id")) )
THROW("you must specificy unique_id, total, and node if you specify any");
if (arg.vm.count("daemon") || arg.vm.count("pid_file") || (arg.vm.count("port") && !arg.all->active) )
{
arg.all->daemon = true;
// allow each child to process up to 1e5 connections
arg.all->numpasses = (size_t) 1e5;
}
if (arg.vm.count("compressed"))
set_compressed(arg.all->p);
if (ends_with(arg.all->data_filename, ".gz"))
set_compressed(arg.all->p);
if ((arg.vm.count("cache") || arg.vm.count("cache_file")) && arg.vm.count("invert_hash"))
THROW("invert_hash is incompatible with a cache file. Use it in single pass mode only.");
if(!arg.all->holdout_set_off && (arg.vm.count("output_feature_regularizer_binary") || arg.vm.count("output_feature_regularizer_text")))
{
arg.all->holdout_set_off = true;
arg.trace_message<<"Making holdout_set_off=true since output regularizer specified" << endl;
}
}
bool interactions_settings_doubled = false; // local setting setted in parse_modules()
namespace VW
{
const char* are_features_compatible(vw& vw1, vw& vw2)
{
if (vw1.p->hasher != vw2.p->hasher)
return "hasher";
if (!equal(vw1.spelling_features, vw1.spelling_features + (sizeof(vw1.spelling_features) / sizeof(bool)), vw2.spelling_features))
return "spelling_features";
if (!equal(vw1.affix_features, vw1.affix_features + (sizeof(vw1.affix_features) / sizeof(uint32_t)), vw2.affix_features))
return "affix_features";
if (!equal(vw1.ngram, vw1.ngram + (sizeof(vw1.ngram) / sizeof(uint32_t)), vw2.ngram))
return "ngram";
if (!equal(vw1.skips, vw1.skips + (sizeof(vw1.skips) / sizeof(uint32_t)), vw2.skips))
return "skips";
if (!equal(vw1.limit, vw1.limit + (sizeof(vw1.limit) / sizeof(uint32_t)), vw2.limit))
return "limit";
if (vw1.num_bits != vw2.num_bits)
return "num_bits";
if (vw1.permutations != vw2.permutations)
return "permutations";
if (vw1.interactions.size() != vw2.interactions.size())
return "interactions size";
if (vw1.ignore_some != vw2.ignore_some)
return "ignore_some";
if (vw1.ignore_some && !equal(vw1.ignore, vw1.ignore + (sizeof(vw1.ignore) / sizeof(bool)), vw2.ignore))
return "ignore";
if (vw1.ignore_some_linear != vw2.ignore_some_linear)
return "ignore_some_linear";
if (vw1.ignore_some_linear && !equal(vw1.ignore_linear, vw1.ignore_linear + (sizeof(vw1.ignore_linear) / sizeof(bool)), vw2.ignore_linear))
return "ignore_linear";
if (vw1.redefine_some != vw2.redefine_some)
return "redefine_some";
if (vw1.redefine_some && !equal(vw1.redefine, vw1.redefine + (sizeof(vw1.redefine) / sizeof(unsigned char)), vw2.redefine))
return "redefine";
if (vw1.add_constant != vw2.add_constant)
return "add_constant";
if (vw1.dictionary_path.size() != vw2.dictionary_path.size())
return "dictionary_path size";
if (!equal(vw1.dictionary_path.begin(), vw1.dictionary_path.end(), vw2.dictionary_path.begin()))
return "dictionary_path";
for (auto i = std::begin(vw1.interactions), j = std::begin(vw2.interactions); i != std::end(vw1.interactions); ++i, ++j)
if (*i != *j)
return "interaction mismatch";
return nullptr;
}
}
// return a copy of string replacing \x00 sequences in it
string spoof_hex_encoded_namespaces(const string& arg)
{
string res;
int pos = 0;
while (pos < (int)arg.size()-3)
{
if (arg[pos] == '\\' && arg[pos+1] == 'x')
{
string substr = arg.substr(pos+2,2);
char* p;
unsigned char c = (unsigned char) strtoul(substr.c_str(), &p, 16);
if (*p == '\0')
{
res.push_back(c);
pos += 4;
}
else
{
cerr << "Possibly malformed hex representation of a namespace: '\\x" << substr << "'\n";
res.push_back(arg[pos++]);
}
}
else
res.push_back(arg[pos++]);
}
while (pos < (int)arg.size()) //copy last 2 characters
res.push_back(arg[pos++]);
return res;
}
void parse_feature_tweaks(arguments& arg)
{
string hash_function("strings");
uint32_t new_bits;
vector<string> spelling_ns;
vector<string> quadratics;
vector<string> cubics;
vector<string> interactions;
vector<string> ignores;
vector<string> ignore_linears;
vector<string> keeps;
vector<string> redefines;
vector<string> dictionary_nses;
if (arg.new_options("Feature options")
.keep("hash", po::value(&hash_function), "how to hash the features. Available options: strings, all")
.keep("hash_seed", arg.all->hash_seed, (uint32_t)0, "seed for hash function")
.keep_vector("ignore", po::value(&ignores), "ignore namespaces beginning with character <arg>")
.keep_vector("ignore_linear", po::value(&ignore_linears), "ignore namespaces beginning with character <arg> for linear terms only")
.keep_vector("keep", po::value(&keeps), "keep namespaces beginning with character <arg>")
.keep_vector("redefine", po::value(&redefines), "redefine namespaces beginning with characters of string S as namespace N. <arg> shall be in form 'N:=S' where := is operator. Empty N or S are treated as default namespace. Use ':' as a wildcard in S.")
("bit_precision,b", new_bits, "number of bits in the feature table")
("noconstant", "Don't add a constant feature")
("constant,C", po::value(&(arg.all->initial_constant)), "Set initial value of constant")
("ngram", arg.all->ngram_strings, "Generate N grams. To generate N grams for a single namespace 'foo', arg should be fN.")
("skips", arg.all->skip_strings, "Generate skips in N grams. This in conjunction with the ngram tag can be used to generate generalized n-skip-k-gram. To generate n-skips for a single namespace 'foo', arg should be fN.")
("feature_limit", arg.all->limit_strings, "limit to N features. To apply to a single namespace 'foo', arg should be fN")
.keep<string>("affix", po::value<string>(), "generate prefixes/suffixes of features; argument '+2a,-3b,+1' means generate 2-char prefixes for namespace a, 3-char suffixes for b and 1 char prefixes for default namespace")
.keep_vector("spelling", po::value(&spelling_ns), "compute spelling features for a give namespace (use '_' for default namespace)")
.keep_vector("dictionary", po::value(&dictionary_nses), "read a dictionary for additional features (arg either 'x:file' or just 'file')")
("dictionary_path", po::value< vector<string> >(), "look in this directory for dictionaries; defaults to current directory or env{PATH}")
.keep_vector("interactions", po::value(&interactions), "Create feature interactions of any level between namespaces.")
(arg.all->permutations, "permutations", "Use permutations instead of combinations for feature interactions of same namespace.")
("leave_duplicate_interactions", "Don't remove interactions with duplicate combinations of namespaces. For ex. this is a duplicate: '-q ab -q ba' and a lot more in '-q ::'.")
.keep_vector("quadratic,q", po::value(&quadratics), "Create and use quadratic features")
("q:", po::value< string >(), ": corresponds to a wildcard for all printable characters")
.keep_vector("cubic", po::value(&cubics), "Create and use cubic features").missing())
return;
//feature manipulation
arg.all->p->hasher = getHasher(hash_function);
if (arg.vm.count("spelling"))
{
for (size_t id=0; id<spelling_ns.size(); id++)
{
spelling_ns[id] = spoof_hex_encoded_namespaces(spelling_ns[id]);
if (spelling_ns[id][0] == '_') arg.all->spelling_features[(unsigned char)' '] = true;
else arg.all->spelling_features[(size_t)spelling_ns[id][0]] = true;
}
}
if (arg.vm.count("affix"))
parse_affix_argument(*arg.all, spoof_hex_encoded_namespaces(arg.vm["affix"].as<string>()));
if(arg.vm.count("ngram"))
{
if(arg.vm.count("sort_features"))
THROW("ngram is incompatible with sort_features.");
for (size_t i = 0; i < arg.all->ngram_strings.size(); i++)
arg.all->ngram_strings[i] = spoof_hex_encoded_namespaces(arg.all->ngram_strings[i]);
compile_gram(arg.all->ngram_strings, arg.all->ngram, (char*)"grams", arg.all->quiet);
}
if(arg.vm.count("skips"))
{
if(!arg.vm.count("ngram"))
THROW("You can not skip unless ngram is > 1");
for (size_t i = 0; i < arg.all->skip_strings.size(); i++)
arg.all->skip_strings[i] = spoof_hex_encoded_namespaces(arg.all->skip_strings[i]);
compile_gram(arg.all->skip_strings, arg.all->skips, (char*)"skips", arg.all->quiet);
}
if(arg.vm.count("feature_limit"))
compile_limits(arg.all->limit_strings, arg.all->limit, arg.all->quiet);
if (arg.vm.count("bit_precision"))
{
if (arg.all->default_bits == false && new_bits != arg.all->num_bits)
THROW("Number of bits is set to " << new_bits << " and " << arg.all->num_bits << " by argument and model. That does not work.");
arg.all->default_bits = false;
arg.all->num_bits = new_bits;
VW::validate_num_bits(*arg.all);
}
// prepare namespace interactions
std::vector<std::string> expanded_interactions;
if ( ( ((!arg.all->pairs.empty() || !arg.all->triples.empty() || !arg.all->interactions.empty()) && /*data was restored from old model file directly to v_array and will be overriden automatically*/
(arg.vm.count("quadratic") || arg.vm.count("cubic") || arg.vm.count("interactions")) ) )
||
interactions_settings_doubled /*settings were restored from model file to file_options and overriden by params from command line*/)
{
arg.trace_message << "WARNING: model file has set of {-q, --cubic, --interactions} settings stored, but they'll be OVERRIDEN by set of {-q, --cubic, --interactions} settings from command line." << endl;
// in case arrays were already filled in with values from old model file - reset them
if (!arg.all->pairs.empty()) arg.all->pairs.clear();
if (!arg.all->triples.empty()) arg.all->triples.clear();
if (!arg.all->interactions.empty()) arg.all->interactions.clear();
}
if (arg.vm.count("quadratic"))
{
if (!arg.all->quiet)
arg.trace_message << "creating quadratic features for pairs: ";
for (vector<string>::iterator i = quadratics.begin(); i != quadratics.end(); ++i)
{
*i = spoof_hex_encoded_namespaces(*i);
if (!arg.all->quiet) arg.trace_message << *i << " ";
}
expanded_interactions = INTERACTIONS::expand_interactions(quadratics, 2, "error, quadratic features must involve two sets.");
if (!arg.all->quiet) arg.trace_message << endl;
}
if (arg.vm.count("cubic"))
{
if (!arg.all->quiet)
arg.trace_message << "creating cubic features for triples: ";
for (vector<string>::iterator i = cubics.begin(); i != cubics.end(); ++i)
{
*i = spoof_hex_encoded_namespaces(*i);
if (!arg.all->quiet) arg.trace_message << *i << " ";
}
std::vector<std::string> exp_cubic = INTERACTIONS::expand_interactions(cubics, 3, "error, cubic features must involve three sets.");
expanded_interactions.insert(std::begin(expanded_interactions), std::begin(exp_cubic), std::end(exp_cubic));
if (!arg.all->quiet) arg.trace_message << endl;
}
if (arg.vm.count("interactions"))
{
if (!arg.all->quiet)
arg.trace_message << "creating features for following interactions: ";
for (vector<string>::iterator i = interactions.begin(); i != interactions.end(); ++i)
{
*i = spoof_hex_encoded_namespaces(*i);
if (!arg.all->quiet) arg.trace_message << *i << " ";
}
std::vector<std::string> exp_inter = INTERACTIONS::expand_interactions(interactions, 0, "");
expanded_interactions.insert(std::begin(expanded_interactions), std::begin(exp_inter), std::end(exp_inter));
if (!arg.all->quiet) arg.trace_message << endl;
}
if (expanded_interactions.size() > 0)
{
size_t removed_cnt;
size_t sorted_cnt;
INTERACTIONS::sort_and_filter_duplicate_interactions(expanded_interactions, !arg.vm.count("leave_duplicate_interactions"), removed_cnt, sorted_cnt);
if (removed_cnt > 0)
arg.trace_message << "WARNING: duplicate namespace interactions were found. Removed: " << removed_cnt << '.' << endl << "You can use --leave_duplicate_interactions to disable this behaviour." << endl;
if (sorted_cnt > 0)
arg.trace_message << "WARNING: some interactions contain duplicate characters and their characters order has been changed. Interactions affected: " << sorted_cnt << '.' << endl;
if (arg.all->interactions.size() > 0)
{
// should be empty, but just in case...
arg.all->interactions.clear();
}
arg.all->interactions = expanded_interactions;
// copy interactions of size 2 and 3 to old vectors for backward compatibility
for (auto& i : expanded_interactions)
{
const size_t len = i.size();
if (len == 2)
arg.all->pairs.push_back(i);
else if (len == 3)
arg.all->triples.push_back(i);
}
}
for (size_t i = 0; i < 256; i++)
{
arg.all->ignore[i] = false;
arg.all->ignore_linear[i] = false;
}
arg.all->ignore_some = false;
arg.all->ignore_some_linear = false;
if (arg.vm.count("ignore"))
{
arg.all->ignore_some = true;
for (vector<string>::iterator i = ignores.begin(); i != ignores.end(); i++)
{
*i = spoof_hex_encoded_namespaces(*i);
for (string::const_iterator j = i->begin(); j != i->end(); j++)
arg.all->ignore[(size_t)(unsigned char)*j] = true;
}
if (!arg.all->quiet)
{
arg.trace_message << "ignoring namespaces beginning with: ";
for (vector<string>::iterator i = ignores.begin(); i != ignores.end(); i++)
for (string::const_iterator j = i->begin(); j != i->end(); j++)
arg.trace_message << *j << " ";
arg.trace_message << endl;
}
}
if (arg.vm.count("ignore_linear"))
{
arg.all->ignore_some_linear = true;
for (vector<string>::iterator i = ignore_linears.begin(); i != ignore_linears.end(); i++)
{
*i = spoof_hex_encoded_namespaces(*i);
for (string::const_iterator j = i->begin(); j != i->end(); j++)
arg.all->ignore_linear[(size_t)(unsigned char)*j] = true;
}
if (!arg.all->quiet)
{
arg.trace_message << "ignoring linear terms for namespaces beginning with: ";
for (vector<string>::iterator i = ignore_linears.begin(); i != ignore_linears.end(); i++)
for (string::const_iterator j = i->begin(); j != i->end(); j++)
arg.trace_message << *j << " ";
arg.trace_message << endl;
}
}
if (arg.vm.count("keep"))
{
for (size_t i = 0; i < 256; i++)
arg.all->ignore[i] = true;
arg.all->ignore_some = true;
for (vector<string>::iterator i = keeps.begin(); i != keeps.end(); i++)
{
*i = spoof_hex_encoded_namespaces(*i);
for (string::const_iterator j = i->begin(); j != i->end(); j++)
arg.all->ignore[(size_t)(unsigned char)*j] = false;
}
if (!arg.all->quiet)
{
arg.trace_message << "using namespaces beginning with: ";
for (vector<string>::iterator i = keeps.begin(); i != keeps.end(); i++)
for (string::const_iterator j = i->begin(); j != i->end(); j++)
arg.trace_message << *j << " ";
arg.trace_message << endl;
}
}
// --redefine param code
arg.all->redefine_some = false; // false by default
if (arg.vm.count("redefine"))
{
// initail values: i-th namespace is redefined to i itself
for (size_t i = 0; i < 256; i++)
arg.all->redefine[i] = (unsigned char)i;
// note: --redefine declaration order is matter
// so --redefine :=L --redefine ab:=M --ignore L will ignore all except a and b under new M namspace
for (vector<string>::iterator arg_iter = redefines.begin(); arg_iter != redefines.end(); arg_iter++)
{
string argument = spoof_hex_encoded_namespaces(*arg_iter);
size_t arg_len = argument.length();
size_t operator_pos = 0; //keeps operator pos + 1 to stay unsigned type
bool operator_found = false;
unsigned char new_namespace = ' ';
// let's find operator ':=' position in N:=S
for (size_t i = 0; i < arg_len; i++)
{
if (operator_found)
{
if (i > 2) { new_namespace = argument[0];} //N is not empty
break;
}
else if (argument[i] == ':')
operator_pos = i+1;
else if ( (argument[i] == '=') && (operator_pos == i) )
operator_found = true;
}
if (!operator_found)
THROW("argument of --redefine is malformed. Valid format is N:=S, :=S or N:=");
if (++operator_pos > 3) // seek operator end
arg.trace_message << "WARNING: multiple namespaces are used in target part of --redefine argument. Only first one ('" << new_namespace << "') will be used as target namespace." << endl;
arg.all->redefine_some = true;
// case ':=S' doesn't require any additional code as new_namespace = ' ' by default
if (operator_pos == arg_len) // S is empty, default namespace shall be used
arg.all->redefine[(int) ' '] = new_namespace;
else
for (size_t i = operator_pos; i < arg_len; i++)
{
// all namespaces from S are redefined to N
unsigned char c = argument[i];
if (c != ':')
arg.all->redefine[c] = new_namespace;
else
{
// wildcard found: redefine all except default and break
for (size_t i = 0; i < 256; i++)
arg.all->redefine[i] = new_namespace;
break; //break processing S
}
}
}
}
if (arg.vm.count("dictionary"))
{
if (arg.vm.count("dictionary_path"))
for (string path : arg.vm["dictionary_path"].as< vector<string> >())
if (directory_exists(path))
arg.all->dictionary_path.push_back(path);
if (directory_exists("."))
arg.all->dictionary_path.push_back(".");
const std::string PATH = getenv( "PATH" );
#if _WIN32
const char delimiter = ';';
#else
const char delimiter = ':';
#endif
if(!PATH.empty())
{
size_t previous = 0;
size_t index = PATH.find( delimiter );
while( index != string::npos )
{
arg.all->dictionary_path.push_back( PATH.substr(previous, index-previous));
previous=index+1;
index = PATH.find( delimiter, previous );
}
arg.all->dictionary_path.push_back( PATH.substr(previous) );
}
for (size_t id=0; id<dictionary_nses.size(); id++)
parse_dictionary_argument(*arg.all, dictionary_nses[id]);
}
if (arg.vm.count("noconstant"))
arg.all->add_constant = false;
}
void parse_example_tweaks(arguments& arg)
{
string named_labels;
string loss_function;
float loss_parameter = 0.0;
if (arg.new_options("Example options")
("testonly,t", "Ignore label information and just test")
(arg.all->holdout_set_off, "holdout_off", "no holdout data in multiple passes")
("holdout_period", arg.all->holdout_period, (uint32_t)10, "holdout period for test only")
("holdout_after", arg.all->holdout_after, "holdout after n training examples, default off (disables holdout_period)")
("early_terminate", po::value<size_t>()->default_value(3), "Specify the number of passes tolerated when holdout loss doesn't decrease before early termination")
("passes", arg.all->numpasses,"Number of Training Passes")
("initial_pass_length", arg.all->pass_length, "initial number of examples per pass")
("examples", arg.all->max_examples, "number of examples to parse")
("min_prediction", arg.all->sd->min_label, "Smallest prediction to output")
("max_prediction", arg.all->sd->max_label, "Largest prediction to output")
(arg.all->p->sort_features, "sort_features", "turn this on to disregard order in which features have been defined. This will lead to smaller cache sizes")
("loss_function", loss_function, (string)"squared", "Specify the loss function to be used, uses squared by default. Currently available ones are squared, classic, hinge, logistic, quantile and poisson.")
("quantile_tau", loss_parameter, 0.5f, "Parameter \\tau associated with Quantile loss. Defaults to 0.5")
("l1", arg.all->l1_lambda, "l_1 lambda")
("l2", arg.all->l2_lambda, "l_2 lambda")
("no_bias_regularization", arg.all->no_bias,"no bias in regularization")
.keep("named_labels", named_labels, "use names for labels (multiclass, etc.) rather than integers, argument specified all possible labels, comma-sep, eg \"--named_labels Noun,Verb,Adj,Punc\"").missing())
return;
if (arg.vm.count("testonly") || arg.all->eta == 0.)
{
if (!arg.all->quiet)
arg.trace_message << "only testing" << endl;
arg.all->training = false;
if (arg.all->lda > 0)
arg.all->eta = 0;
}
else
arg.all->training = true;
if((arg.all->numpasses > 1 || arg.all->holdout_after > 0) && !arg.vm["holdout_off"].as<bool>())
arg.all->holdout_set_off = false;//holdout is on unless explicitly off
else
arg.all->holdout_set_off = true;
if (arg.vm.count("min_prediction") || arg.vm.count("max_prediction") || arg.vm.count("testonly"))
arg.all->set_minmax = noop_mm;
if (arg.vm.count("named_labels"))
{
arg.all->sd->ldict = &calloc_or_throw<namedlabels>();
new (arg.all->sd->ldict) namedlabels(named_labels);
if (!arg.all->quiet)
arg.trace_message << "parsed " << arg.all->sd->ldict->getK() << " named labels" << endl;
}
arg.all->loss = getLossFunction(*arg.all, loss_function, loss_parameter);
if (arg.all->l1_lambda < 0.)
{
arg.trace_message << "l1_lambda should be nonnegative: resetting from " << arg.all->l1_lambda << " to 0" << endl;
arg.all->l1_lambda = 0.;
}
if (arg.all->l2_lambda < 0.)
{
arg.trace_message << "l2_lambda should be nonnegative: resetting from " << arg.all->l2_lambda << " to 0" << endl;
arg.all->l2_lambda = 0.;
}
arg.all->reg_mode += (arg.all->l1_lambda > 0.) ? 1 : 0;
arg.all->reg_mode += (arg.all->l2_lambda > 0.) ? 2 : 0;
if (!arg.all->quiet)
{
if (arg.all->reg_mode %2 && !arg.vm.count("bfgs"))
arg.trace_message << "using l1 regularization = " << arg.all->l1_lambda << endl;
if (arg.all->reg_mode > 1)
arg.trace_message << "using l2 regularization = " << arg.all->l2_lambda << endl;
}
}
void parse_output_preds(arguments& arg)
{
if (arg.new_options("Output options")
("predictions,p", po::value< string >(), "File to output predictions to")
("raw_predictions,r", po::value< string >(), "File to output unnormalized predictions to").missing())
return;
if (arg.vm.count("predictions"))
{
if (!arg.all->quiet)
arg.trace_message << "predictions = " << arg.vm["predictions"].as< string >() << endl;
if (strcmp(arg.vm["predictions"].as< string >().c_str(), "stdout") == 0)
{
arg.all->final_prediction_sink.push_back((size_t) 1);//stdout
}
else
{
const char* fstr = (arg.vm["predictions"].as< string >().c_str());
int f;
#ifdef _WIN32
_sopen_s(&f, fstr, _O_CREAT|_O_WRONLY|_O_BINARY|_O_TRUNC, _SH_DENYWR, _S_IREAD|_S_IWRITE);
#else
f = open(fstr, O_CREAT|O_WRONLY|O_LARGEFILE|O_TRUNC,0666);
#endif
if (f < 0)
arg.trace_message << "Error opening the predictions file: " << fstr << endl;
arg.all->final_prediction_sink.push_back((size_t) f);