Package: vecxx
vecxxFast C++ implementations of vectorizers for machine learning models, with bindings in Python and JS/TS.This includes a straighforward, cross-platform C++ implementation of common approaches to vectorization to integers, required for most types of DNNs to convert sentences into tensors.  It also supports nativesubword BPEbased onfastBPEwith additional support for preprocessing transforms of strings during decode, either as native functors or from the bound languages.  It also supports extra (special) tokens that can be passed through.For BPE, the library supports execution of models that were trained either using subword-nmt or fastBPE (or any other system which shares the file format).To support fast load times,vecxxvocabs can be compiled to a perfect hash and persisted to disk.  When constructing the objects from the compiled directory, the loading will use memory mapping.  For a BPE vocab, a non-compiled load that takes 24 milliseconds, may take only 200 microseconds after compilation.Handling of prefix and suffix tokensThe API supports passing in a vector of tokens for prefixing the data, and for suffixing.  These are
passed as a[]in Python, andstd::vector<std::string>in C++.  Note that for prefixing, the prefix tokens will always be present, but when converting to integer ids, if the output buffer is presized and is too short to fill the tokens, the library currently will not overwrite the last values in the buffer to the end tokens.  The rationale is that, typically an end suffix will be something marking an end-of-sentence or utterance, but since the result is truncated, the end was not actually reached.  Future versions of the library may change thisHandling of multiple input sentencesThe library supports converting multiple sentences into a "stack" of tokens with a fixed output size.  This may be useful for batching or using N-best lists as input.  The results from the ID stack are contiguous 1D arrays.  They will typically be reshaped in user code:nbests=[t.split()fortintext]ids,lengths=vec.convert_to_ids_stack(nbests,len(nbests)*args.mxlen)ids=np.array(ids).reshape(1,len(nbests),-1)example={args.feature:ids,'lengths':np.array(lengths).reshape(1,-1)}C++#include"vecxx/vecxx.h"std::vector<std::string>SENTENCE={"My","name","is","Dan",".","I","am","from","Ann","Arbor",",","Michigan",",","in","Washtenaw","County"};intmain(intargc,char**argv){std::stringvocab_file(argv[1]);std::stringcodes_file(argv[2]);autov=newBPEVocab(vocab_file,codes_file);VocabVectorizervec(v);for(autop:vec.convert_to_pieces(SENTENCE)){std::cout<<p<<std::endl;}std::vector<int>ids;intl;std::tie(ids,l)=vec.convert_to_ids(SENTENCE);for(autop:ids){std::cout<<p<<std::endl;}deletev;return0;}Vocab compilationThe initial load of the vocab is typically relatively fast, as it just reads in text files.
However, if we need much lower latency, we can optionally compile the internal data structures to memory-mapped perfect hashes.Once compiled pass the compiled target folder in as both thevocab_fileandcodes_file.autov=newBPEVocab(vocab_file,codes_file);v->compile_vocab(compiled_dir);deletev;return0;Python bindingsThe Python bindings are written withpybind11.You can install the python bindings usingpip:pip install vecxxUsing BPE vectorizer from PythonConverting sentences to lower-case subword BPE tokens as integers from the vocabulary.
Note that a python native string transform can be used to transform each token prior to subword tokenization.
Tokens from either the BPE vocab or special tokens (like<GO>and<EOS>) can be applied to the beginning and end of the sequence.
If a second argument is provided toconvert_to_idsthis will indicate a padded length required for the tensorfromvecxximport*bpe=BPEVocab(vocab_file=os.path.join(TEST_DATA,"vocab.30k"),codes_file=os.path.join(TEST_DATA,"codes.30k"))vec=VocabVectorizer(bpe,transform=str.lower,emit_begin_tok=["<GO>"],emit_end_tok=["<EOS>"])padd_vec,unpadded_len=vec.convert_to_ids("My name is Dan . I am from Ann Arbor , Michigan , in Washtenaw County".split(),256)The result of this will be:[1, 30, 265, 14, 2566, 5, 8, 158, 63, 10940, 525, 18637, 7, 3685, 7, 18, 14242, 1685, 2997, 4719, 2, 0, ..., 0]Vocab compilationAs in the C++ example, we can optionally compile the internal data structures to memory-mapped perfect hashes.  Once compiled they can be read in the same way.>>>importvecxx>>>b=vecxx.BPEVocab('/data/reddit/vocab.30k','/data/reddit/codes.30k',extra_tokens=["[CLS]","[MASK]"])>>>b.compile_vocab('blah')>>>b2=vecxx.BPEVocab('blah','blah')JS/TS bindingsThe Javascript bindings are provided by using theNode-APIAPI.A thin TypeScript wrapper provides a typed API that closely matches the underlying (and Python) APIs.Using BPE vectorizer from TypeScriptimport{BPEVocab,VocabVectorizer}from'vecxx';import{join}from'path';consttestDir=join(__dirname,'test_data');constbpe=newBPEVocab(join(testDir,'vocab.30k'),join(testDir,'codes.30k'));constvectorizer=newVocabVectorizer(bpe,{transform:(s:string)=>s.toLowerCase(),emitBeginToken:['<GO>'],emitEndToken:['<EOS>']});constsentence=`My name is Dan . I am from Ann Arbor , Michigan , in Washtenaw County`;const{ids,size}=vectorizer.convertToIds(sentence.split(/\s+/),256);DockerSampleDockerfiles are provided that can be used for sandbox development/testing.dockerbuild-tvecxx-python-fpy.Dockerfile.
dockerrun-itvecxx-pythondockerbuild-tvecxx-node-fnode.Dockerfile.
dockerrun-itvecxx-node# ...varvecxx=require('dist/index.js')