Import KenLM

This commit is contained in:
Reuben Morais 2017-08-28 12:50:37 +02:00
parent 481aa6ff53
commit af71da0d4d
228 changed files with 38442 additions and 0 deletions

18
native_client/kenlm/.gitignore vendored Normal file
View File

@ -0,0 +1,18 @@
util/file_piece.cc.gz
*.swp
*.o
doc/
build/
._*
windows/Win32
windows/x64
windows/*.user
windows/*.sdf
windows/*.opensdf
windows/*.suo
CMakeFiles
cmake_install.cmake
CMakeCache.txt
CTestTestfile.cmake
DartConfiguration.tcl
Makefile

View File

@ -0,0 +1,14 @@
KenLM has switched to cmake
cmake .
make -j 4
But they recommend building out of tree
mkdir -p build && cd build
cmake ..
make -j 4
If you only want the query code and do not care about compression (.gz, .bz2, and .xz):
./compile_query_only.sh
Windows:
The windows directory has visual studio files. Note that you need to compile
the kenlm project before build_binary and ngram_query projects.

View File

@ -0,0 +1,82 @@
cmake_minimum_required(VERSION 2.6)
# Define a single cmake project
project(kenlm)
option(FORCE_STATIC "Build static executables" OFF)
if (FORCE_STATIC)
#presumably overkill, is there a better way?
#http://cmake.3232098.n2.nabble.com/Howto-compile-static-executable-td5580269.html
set(Boost_USE_STATIC_LIBS ON)
set_property(GLOBAL PROPERTY LINK_SEARCH_START_STATIC ON)
set_property(GLOBAL PROPERTY LINK_SEARCH_END_STATIC ON)
set(BUILD_SHARED_LIBRARIES OFF)
if (MSVC)
set(flag_vars
CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO
CMAKE_C_FLAGS CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE
CMAKE_C_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELWITHDEBINFO)
foreach(flag_var ${flag_vars})
if(${flag_var} MATCHES "/MD")
string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
endif(${flag_var} MATCHES "/MD")
endforeach(flag_var)
else (MSVC)
if (NOT CMAKE_C_COMPILER_ID MATCHES ".*Clang")
set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++ -static")
endif ()
set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
endif ()
#Annoyingly the exectuables say "File not found" unless these are set
set(CMAKE_EXE_LINK_DYNAMIC_C_FLAGS)
set(CMAKE_EXE_LINK_DYNAMIC_CXX_FLAGS)
set(CMAKE_SHARED_LIBRARY_C_FLAGS)
set(CMAKE_SHARED_LIBRARY_CXX_FLAGS)
set(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS)
set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS)
endif ()
# Compile all executables into bin/
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
# Compile all libraries into lib/
set(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib)
if (NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
endif()
# Tell cmake that we want unit tests to be compiled
include(CTest)
enable_testing()
# Add our CMake helper functions
include(cmake/KenLMFunctions.cmake)
if(MSVC)
set(CMAKE_C_FLAGS "${CMAKE_CXX_FLAGS} /w34716")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /w34716")
endif()
# And our helper modules
list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/modules)
# We need boost
find_package(Boost 1.41.0 REQUIRED COMPONENTS
program_options
system
thread
unit_test_framework
)
# Define where include files live
include_directories(
${PROJECT_SOURCE_DIR}
${Boost_INCLUDE_DIRS}
)
# Process subdirectories
add_subdirectory(util)
add_subdirectory(lm)

502
native_client/kenlm/COPYING Normal file
View File

@ -0,0 +1,502 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

1519
native_client/kenlm/Doxyfile Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1 @@
cdd794598ea15dc23a7daaf7a8cf89423c97f7e6

View File

@ -0,0 +1,25 @@
Most of the code here is licensed under the LGPL. There are exceptions that
have their own licenses, listed below. See comments in those files for more
details.
util/getopt.* is getopt for Windows
util/murmur_hash.cc
util/string_piece.hh and util/string_piece.cc
util/double-conversion/LICENSE covers util/double-conversion except the build files
util/file.cc contains a modified implementation of mkstemp under the LGPL
util/integer_to_string.* is BSD
For the rest:
KenLM is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 2.1 of the License, or
(at your option) any later version.
KenLM is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License 2.1
along with KenLM code. If not, see <http://www.gnu.org/licenses/lgpl-2.1.html>.

View File

@ -0,0 +1,9 @@
# file GENERATED by distutils, do NOT edit
include setup.py
include lm/*.cc
include lm/*.hh
include python/*.cpp
include util/*.cc
include util/*.hh
include util/double-conversion/*.cc
include util/double-conversion/*.h

View File

@ -0,0 +1,104 @@
# kenlm
Language model inference code by Kenneth Heafield (kenlm at kheafield.com)
I do development in master on https://github.com/kpu/kenlm/. Normally, it works, but I do not guarantee it will compile, give correct answers, or generate non-broken binary files. For a more stable release, get http://kheafield.com/code/kenlm.tar.gz .
The website http://kheafield.com/code/kenlm/ has more documentation. If you're a decoder developer, please download the latest version from there instead of copying from another decoder.
## Compiling
Use cmake, see [BUILDING](BUILDING) for more detail.
```bash
mkdir -p build
cd build
cmake ..
make -j 4
```
## Compiling with your own build system
If you want to compile with your own build system (Makefile etc) or to use as a library, there are a number of macros you can set on the g++ command line or in util/have.hh .
* `KENLM_MAX_ORDER` is the maximum order that can be loaded. This is done to make state an efficient POD rather than a vector.
* `HAVE_ICU` If your code links against ICU, define this to disable the internal StringPiece and replace it with ICU's copy of StringPiece, avoiding naming conflicts.
ARPA files can be read in compressed format with these options:
* `HAVE_ZLIB` Supports gzip. Link with -lz.
* `HAVE_BZLIB` Supports bzip2. Link with -lbz2.
* `HAVE_XZLIB` Supports xz. Link with -llzma.
Note that these macros impact only `read_compressed.cc` and `read_compressed_test.cc`. The bjam build system will auto-detect bzip2 and xz support.
## Estimation
lmplz estimates unpruned language models with modified Kneser-Ney smoothing. After compiling with bjam, run
```bash
bin/lmplz -o 5 <text >text.arpa
```
The algorithm is on-disk, using an amount of memory that you specify. See http://kheafield.com/code/kenlm/estimation/ for more.
MT Marathon 2012 team members Ivan Pouzyrevsky and Mohammed Mediani contributed to the computation design and early implementation. Jon Clark contributed to the design, clarified points about smoothing, and added logging.
## Filtering
filter takes an ARPA or count file and removes entries that will never be queried. The filter criterion can be corpus-level vocabulary, sentence-level vocabulary, or sentence-level phrases. Run
```bash
bin/filter
```
and see http://kheafield.com/code/kenlm/filter/ for more documentation.
## Querying
Two data structures are supported: probing and trie. Probing is a probing hash table with keys that are 64-bit hashes of n-grams and floats as values. Trie is a fairly standard trie but with bit-level packing so it uses the minimum number of bits to store word indices and pointers. The trie node entries are sorted by word index. Probing is the fastest and uses the most memory. Trie uses the least memory and a bit slower.
As is the custom in language modeling, all probabilities are log base 10.
With trie, resident memory is 58% of IRST's smallest version and 21% of SRI's compact version. Simultaneously, trie CPU's use is 81% of IRST's fastest version and 84% of SRI's fast version. KenLM's probing hash table implementation goes even faster at the expense of using more memory. See http://kheafield.com/code/kenlm/benchmark/.
Binary format via mmap is supported. Run `./build_binary` to make one then pass the binary file name to the appropriate Model constructor.
## Platforms
`murmur_hash.cc` and `bit_packing.hh` perform unaligned reads and writes that make the code architecture-dependent.
It has been sucessfully tested on x86\_64, x86, and PPC64.
ARM support is reportedly working, at least on the iphone.
Runs on Linux, OS X, Cygwin, and MinGW.
Hideo Okuma and Tomoyuki Yoshimura from NICT contributed ports to ARM and MinGW.
## Decoder developers
- I recommend copying the code and distributing it with your decoder. However, please send improvements upstream.
- It's possible to compile the query-only code without Boost, but useful things like estimating models require Boost.
- Select the macros you want, listed in the previous section.
- There are two build systems: compile.sh and Jamroot+Jamfile. They're pretty simple and are intended to be reimplemented in your build system.
- Use either the interface in `lm/model.hh` or `lm/virtual_interface.hh`. Interface documentation is in comments of `lm/virtual_interface.hh` and `lm/model.hh`.
- There are several possible data structures in `model.hh`. Use `RecognizeBinary` in `binary_format.hh` to determine which one a user has provided. You probably already implement feature functions as an abstract virtual base class with several children. I suggest you co-opt this existing virtual dispatch by templatizing the language model feature implementation on the KenLM model identified by `RecognizeBinary`. This is the strategy used in Moses and cdec.
- See `lm/config.hh` for run-time tuning options.
## Contributors
Contributions to KenLM are welcome. Please base your contributions on https://github.com/kpu/kenlm and send pull requests (or I might give you commit access). Downstream copies in Moses and cdec are maintained by overwriting them so do not make changes there.
## Python module
Contributed by Victor Chahuneau.
### Installation
```bash
pip install https://github.com/kpu/kenlm/archive/master.zip
```
### Basic Usage
```python
import kenlm
model = kenlm.Model('lm/test.arpa')
print(model.score('this is a sentence .', bos = True, eos = True))
```
See [python/example.py](python/example.py) and [python/kenlm.pyx](python/kenlm.pyx) for more, including stateful APIs.
---
The name was Hieu Hoang's idea, not mine.

View File

@ -0,0 +1,9 @@
Downloaded from http://kheafield.com/code/kenlm.tar.gz on 2017/08/05
sha256 c4c9f587048470c9a6a592914f0609a71fbb959f0a4cad371e8c355ce81f7c6b
This corresponds to https://github.com/kpu/kenlm/commit/cdd794598ea15dc23a7daaf7a8cf89423c97f7e6
The following procedure was run to remove unneeded files:
cd kenlm
rm -rf windows include lm/filter lm/builder util/stream

View File

@ -0,0 +1,2 @@
#!/bin/bash
rm -rf {lm,util,util/double-conversion}/*.o bin/{query,build_binary}

View File

@ -0,0 +1,85 @@
# Helper functions used across the CMake build system
include(CMakeParseArguments)
# Adds a bunch of executables to the build, each depending on the specified
# dependent object files and linking against the specified libraries
function(AddExes)
set(multiValueArgs EXES DEPENDS LIBRARIES)
cmake_parse_arguments(AddExes "" "" "${multiValueArgs}" ${ARGN})
# Iterate through the executable list
foreach(exe ${AddExes_EXES})
# Compile the executable, linking against the requisite dependent object files
add_executable(${exe} ${exe}_main.cc ${AddExes_DEPENDS})
# Link the executable against the supplied libraries
target_link_libraries(${exe} ${AddExes_LIBRARIES})
# Group executables together
set_target_properties(${exe} PROPERTIES FOLDER executables)
# End for loop
endforeach(exe)
# Install the executable files
install(TARGETS ${AddExes_EXES} DESTINATION bin)
endfunction()
# Adds a single test to the build, depending on the specified dependent
# object files, linking against the specified libraries, and with the
# specified command line arguments
function(KenLMAddTest)
cmake_parse_arguments(KenLMAddTest "" "TEST"
"DEPENDS;LIBRARIES;TEST_ARGS" ${ARGN})
# Compile the executable, linking against the requisite dependent object files
add_executable(${KenLMAddTest_TEST}
${KenLMAddTest_TEST}.cc
${KenLMAddTest_DEPENDS})
if (Boost_USE_STATIC_LIBS)
set(DYNLINK_FLAGS)
else()
set(DYNLINK_FLAGS COMPILE_FLAGS -DBOOST_TEST_DYN_LINK)
endif()
# Require the following compile flag
set_target_properties(${KenLMAddTest_TEST} PROPERTIES
${DYNLINK_FLAGS}
RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/tests)
target_link_libraries(${KenLMAddTest_TEST} ${KenLMAddTest_LIBRARIES} ${TIMER_LINK})
set(test_params "")
if(KenLMAddTest_TEST_ARGS)
set(test_params ${KenLMAddTest_TEST_ARGS})
endif()
# Specify command arguments for how to run each unit test
#
# Assuming that foo was defined via add_executable(foo ...),
# the syntax $<TARGET_FILE:foo> gives the full path to the executable.
#
add_test(NAME ${KenLMAddTest_TEST}
COMMAND $<TARGET_FILE:${KenLMAddTest_TEST}> ${test_params})
# Group unit tests together
set_target_properties(${KenLMAddTest_TEST} PROPERTIES FOLDER "unit_tests")
endfunction()
# Adds a bunch of tests to the build, each depending on the specified
# dependent object files and linking against the specified libraries
function(AddTests)
set(multiValueArgs TESTS DEPENDS LIBRARIES TEST_ARGS)
cmake_parse_arguments(AddTests "" "" "${multiValueArgs}" ${ARGN})
# Iterate through the Boost tests list
foreach(test ${AddTests_TESTS})
KenLMAddTest(TEST ${test}
DEPENDS ${AddTests_DEPENDS}
LIBRARIES ${AddTests_LIBRARIES}
TEST_ARGS ${AddTests_TEST_ARGS})
endforeach(test)
endfunction()

View File

@ -0,0 +1,90 @@
# - Try to find Eigen3 lib
#
# This module supports requiring a minimum version, e.g. you can do
# find_package(Eigen3 3.1.2)
# to require version 3.1.2 or newer of Eigen3.
#
# Once done this will define
#
# EIGEN3_FOUND - system has eigen lib with correct version
# EIGEN3_INCLUDE_DIR - the eigen include directory
# EIGEN3_VERSION - eigen version
#
# This module reads hints about search locations from
# the following enviroment variables:
#
# EIGEN3_ROOT
# EIGEN3_ROOT_DIR
# Copyright (c) 2006, 2007 Montel Laurent, <montel@kde.org>
# Copyright (c) 2008, 2009 Gael Guennebaud, <g.gael@free.fr>
# Copyright (c) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
# Redistribution and use is allowed according to the terms of the 2-clause BSD license.
if(NOT Eigen3_FIND_VERSION)
if(NOT Eigen3_FIND_VERSION_MAJOR)
set(Eigen3_FIND_VERSION_MAJOR 2)
endif(NOT Eigen3_FIND_VERSION_MAJOR)
if(NOT Eigen3_FIND_VERSION_MINOR)
set(Eigen3_FIND_VERSION_MINOR 91)
endif(NOT Eigen3_FIND_VERSION_MINOR)
if(NOT Eigen3_FIND_VERSION_PATCH)
set(Eigen3_FIND_VERSION_PATCH 0)
endif(NOT Eigen3_FIND_VERSION_PATCH)
set(Eigen3_FIND_VERSION "${Eigen3_FIND_VERSION_MAJOR}.${Eigen3_FIND_VERSION_MINOR}.${Eigen3_FIND_VERSION_PATCH}")
endif(NOT Eigen3_FIND_VERSION)
macro(_eigen3_check_version)
file(READ "${EIGEN3_INCLUDE_DIR}/Eigen/src/Core/util/Macros.h" _eigen3_version_header)
string(REGEX MATCH "define[ \t]+EIGEN_WORLD_VERSION[ \t]+([0-9]+)" _eigen3_world_version_match "${_eigen3_version_header}")
set(EIGEN3_WORLD_VERSION "${CMAKE_MATCH_1}")
string(REGEX MATCH "define[ \t]+EIGEN_MAJOR_VERSION[ \t]+([0-9]+)" _eigen3_major_version_match "${_eigen3_version_header}")
set(EIGEN3_MAJOR_VERSION "${CMAKE_MATCH_1}")
string(REGEX MATCH "define[ \t]+EIGEN_MINOR_VERSION[ \t]+([0-9]+)" _eigen3_minor_version_match "${_eigen3_version_header}")
set(EIGEN3_MINOR_VERSION "${CMAKE_MATCH_1}")
set(EIGEN3_VERSION ${EIGEN3_WORLD_VERSION}.${EIGEN3_MAJOR_VERSION}.${EIGEN3_MINOR_VERSION})
if(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION})
set(EIGEN3_VERSION_OK FALSE)
else(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION})
set(EIGEN3_VERSION_OK TRUE)
endif(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION})
if(NOT EIGEN3_VERSION_OK)
message(STATUS "Eigen3 version ${EIGEN3_VERSION} found in ${EIGEN3_INCLUDE_DIR}, "
"but at least version ${Eigen3_FIND_VERSION} is required")
endif(NOT EIGEN3_VERSION_OK)
endmacro(_eigen3_check_version)
if (EIGEN3_INCLUDE_DIR)
# in cache already
_eigen3_check_version()
set(EIGEN3_FOUND ${EIGEN3_VERSION_OK})
else (EIGEN3_INCLUDE_DIR)
find_path(EIGEN3_INCLUDE_DIR NAMES signature_of_eigen3_matrix_library
HINTS
ENV EIGEN3_ROOT
ENV EIGEN3_ROOT_DIR
PATHS
${CMAKE_INSTALL_PREFIX}/include
${KDE4_INCLUDE_DIR}
PATH_SUFFIXES eigen3 eigen
)
if(EIGEN3_INCLUDE_DIR)
_eigen3_check_version()
endif(EIGEN3_INCLUDE_DIR)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Eigen3 DEFAULT_MSG EIGEN3_INCLUDE_DIR EIGEN3_VERSION_OK)
mark_as_advanced(EIGEN3_INCLUDE_DIR)
endif(EIGEN3_INCLUDE_DIR)

View File

@ -0,0 +1,34 @@
#!/bin/bash
#This is just an example compilation. You should integrate these files into your build system. Boost jam is provided and preferred.
echo You must use ./bjam if you want language model estimation, filtering, or support for compressed files \(.gz, .bz2, .xz\) 1>&2
rm {lm,util}/*.o 2>/dev/null
set -e
CXX=${CXX:-g++}
CXXFLAGS+=" -I. -O3 -DNDEBUG -DKENLM_MAX_ORDER=6"
#If this fails for you, consider using bjam.
if [ ${#NPLM} != 0 ]; then
CXXFLAGS+=" -DHAVE_NPLM -lneuralLM -L$NPLM/src -I$NPLM/src -lboost_thread-mt -fopenmp"
ADDED_PATHS="lm/wrappers/*.cc"
fi
echo 'Compiling with '$CXX $CXXFLAGS
#Grab all cc files in these directories except those ending in test.cc or main.cc
objects=""
for i in util/double-conversion/*.cc util/*.cc lm/*.cc $ADDED_PATHS; do
if [ "${i%test.cc}" == "$i" ] && [ "${i%main.cc}" == "$i" ]; then
$CXX $CXXFLAGS -c $i -o ${i%.cc}.o
objects="$objects ${i%.cc}.o"
fi
done
mkdir -p bin
if [ "$(uname)" != Darwin ]; then
CXXFLAGS="$CXXFLAGS -lrt"
fi
$CXX lm/build_binary_main.cc $objects -o bin/build_binary $CXXFLAGS $LDFLAGS
$CXX lm/query_main.cc $objects -o bin/query $CXXFLAGS $LDFLAGS

View File

@ -0,0 +1,73 @@
# Explicitly list the source files for this subdirectory
#
# If you add any source files to this subdirectory
# that should be included in the kenlm library,
# (this excludes any unit test files)
# you should add them to the following list:
set(KENLM_LM_SOURCE
bhiksha.cc
binary_format.cc
config.cc
lm_exception.cc
model.cc
quantize.cc
read_arpa.cc
search_hashed.cc
search_trie.cc
sizes.cc
trie.cc
trie_sort.cc
value_build.cc
virtual_interface.cc
vocab.cc
)
# Group these objects together for later use.
#
# Given add_library(foo OBJECT ${my_foo_sources}),
# refer to these objects as $<TARGET_OBJECTS:foo>
#
add_subdirectory(common)
if (NOT MSVC)
set(THREADS pthread)
endif()
add_library(kenlm ${KENLM_LM_SOURCE} ${KENLM_LM_COMMON_SOURCE})
target_link_libraries(kenlm kenlm_util ${Boost_LIBRARIES} ${THREADS})
set(KENLM_MAX_ORDER 6 CACHE STRING "Maximum supported ngram order")
target_compile_definitions(kenlm PUBLIC -DKENLM_MAX_ORDER=${KENLM_MAX_ORDER})
# This directory has children that need to be processed
add_subdirectory(builder)
add_subdirectory(filter)
add_subdirectory(interpolate)
# Explicitly list the executable files to be compiled
set(EXE_LIST
query
fragment
build_binary
kenlm_benchmark
)
set(LM_LIBS kenlm kenlm_util ${Boost_LIBRARIES} ${THREADS})
AddExes(EXES ${EXE_LIST}
LIBRARIES ${LM_LIBS})
if(BUILD_TESTING)
set(KENLM_BOOST_TESTS_LIST left_test partial_test)
AddTests(TESTS ${KENLM_BOOST_TESTS_LIST}
LIBRARIES ${LM_LIBS}
TEST_ARGS ${CMAKE_CURRENT_SOURCE_DIR}/test.arpa)
# model_test requires an extra command line parameter
KenLMAddTest(TEST model_test
LIBRARIES ${LM_LIBS}
TEST_ARGS ${CMAKE_CURRENT_SOURCE_DIR}/test.arpa
${CMAKE_CURRENT_SOURCE_DIR}/test_nounk.arpa)
endif()

View File

@ -0,0 +1,94 @@
#include "lm/bhiksha.hh"
#include "lm/binary_format.hh"
#include "lm/config.hh"
#include "util/file.hh"
#include "util/exception.hh"
#include <limits>
namespace lm {
namespace ngram {
namespace trie {
DontBhiksha::DontBhiksha(const void * /*base*/, uint64_t /*max_offset*/, uint64_t max_next, const Config &/*config*/) :
next_(util::BitsMask::ByMax(max_next)) {}
const uint8_t kArrayBhikshaVersion = 0;
// TODO: put this in binary file header instead when I change the binary file format again.
void ArrayBhiksha::UpdateConfigFromBinary(const BinaryFormat &file, uint64_t offset, Config &config) {
uint8_t buffer[2];
file.ReadForConfig(buffer, 2, offset);
uint8_t version = buffer[0];
uint8_t configured_bits = buffer[1];
if (version != kArrayBhikshaVersion) UTIL_THROW(FormatLoadException, "This file has sorted array compression version " << (unsigned) version << " but the code expects version " << (unsigned)kArrayBhikshaVersion);
config.pointer_bhiksha_bits = configured_bits;
}
namespace {
// Find argmin_{chopped \in [0, RequiredBits(max_next)]} ChoppedDelta(max_offset)
uint8_t ChopBits(uint64_t max_offset, uint64_t max_next, const Config &config) {
uint8_t required = util::RequiredBits(max_next);
uint8_t best_chop = 0;
int64_t lowest_change = std::numeric_limits<int64_t>::max();
// There are probably faster ways but I don't care because this is only done once per order at construction time.
for (uint8_t chop = 0; chop <= std::min(required, config.pointer_bhiksha_bits); ++chop) {
int64_t change = (max_next >> (required - chop)) * 64 /* table cost in bits */
- max_offset * static_cast<int64_t>(chop); /* savings in bits*/
if (change < lowest_change) {
lowest_change = change;
best_chop = chop;
}
}
return best_chop;
}
std::size_t ArrayCount(uint64_t max_offset, uint64_t max_next, const Config &config) {
uint8_t required = util::RequiredBits(max_next);
uint8_t chopping = ChopBits(max_offset, max_next, config);
return (max_next >> (required - chopping)) + 1 /* we store 0 too */;
}
} // namespace
uint64_t ArrayBhiksha::Size(uint64_t max_offset, uint64_t max_next, const Config &config) {
return sizeof(uint64_t) * (1 /* header */ + ArrayCount(max_offset, max_next, config)) + 7 /* 8-byte alignment */;
}
uint8_t ArrayBhiksha::InlineBits(uint64_t max_offset, uint64_t max_next, const Config &config) {
return util::RequiredBits(max_next) - ChopBits(max_offset, max_next, config);
}
namespace {
void *AlignTo8(void *from) {
uint8_t *val = reinterpret_cast<uint8_t*>(from);
std::size_t remainder = reinterpret_cast<std::size_t>(val) & 7;
if (!remainder) return val;
return val + 8 - remainder;
}
} // namespace
ArrayBhiksha::ArrayBhiksha(void *base, uint64_t max_offset, uint64_t max_next, const Config &config)
: next_inline_(util::BitsMask::ByBits(InlineBits(max_offset, max_next, config))),
offset_begin_(reinterpret_cast<const uint64_t*>(AlignTo8(base)) + 1 /* 8-byte header */),
offset_end_(offset_begin_ + ArrayCount(max_offset, max_next, config)),
write_to_(reinterpret_cast<uint64_t*>(AlignTo8(base)) + 1 /* 8-byte header */ + 1 /* first entry is 0 */),
original_base_(base) {}
void ArrayBhiksha::FinishedLoading(const Config &config) {
// *offset_begin_ = 0 but without a const_cast.
*(write_to_ - (write_to_ - offset_begin_)) = 0;
if (write_to_ != offset_end_) UTIL_THROW(util::Exception, "Did not get all the array entries that were expected.");
uint8_t *head_write = reinterpret_cast<uint8_t*>(original_base_);
*(head_write++) = kArrayBhikshaVersion;
*(head_write++) = config.pointer_bhiksha_bits;
}
} // namespace trie
} // namespace ngram
} // namespace lm

View File

@ -0,0 +1,122 @@
/* Simple implementation of
* @inproceedings{bhikshacompression,
* author={Bhiksha Raj and Ed Whittaker},
* year={2003},
* title={Lossless Compression of Language Model Structure and Word Identifiers},
* booktitle={Proceedings of IEEE International Conference on Acoustics, Speech and Signal Processing},
* pages={388--391},
* }
*
* Currently only used for next pointers.
*/
#ifndef LM_BHIKSHA_H
#define LM_BHIKSHA_H
#include "lm/model_type.hh"
#include "lm/trie.hh"
#include "util/bit_packing.hh"
#include "util/sorted_uniform.hh"
#include <algorithm>
#include <stdint.h>
#include <cassert>
namespace lm {
namespace ngram {
struct Config;
class BinaryFormat;
namespace trie {
class DontBhiksha {
public:
static const ModelType kModelTypeAdd = static_cast<ModelType>(0);
static void UpdateConfigFromBinary(const BinaryFormat &, uint64_t, Config &/*config*/) {}
static uint64_t Size(uint64_t /*max_offset*/, uint64_t /*max_next*/, const Config &/*config*/) { return 0; }
static uint8_t InlineBits(uint64_t /*max_offset*/, uint64_t max_next, const Config &/*config*/) {
return util::RequiredBits(max_next);
}
DontBhiksha(const void *base, uint64_t max_offset, uint64_t max_next, const Config &config);
void ReadNext(const void *base, uint64_t bit_offset, uint64_t /*index*/, uint8_t total_bits, NodeRange &out) const {
out.begin = util::ReadInt57(base, bit_offset, next_.bits, next_.mask);
out.end = util::ReadInt57(base, bit_offset + total_bits, next_.bits, next_.mask);
//assert(out.end >= out.begin);
}
void WriteNext(void *base, uint64_t bit_offset, uint64_t /*index*/, uint64_t value) {
util::WriteInt57(base, bit_offset, next_.bits, value);
}
void FinishedLoading(const Config &/*config*/) {}
uint8_t InlineBits() const { return next_.bits; }
private:
util::BitsMask next_;
};
class ArrayBhiksha {
public:
static const ModelType kModelTypeAdd = kArrayAdd;
static void UpdateConfigFromBinary(const BinaryFormat &file, uint64_t offset, Config &config);
static uint64_t Size(uint64_t max_offset, uint64_t max_next, const Config &config);
static uint8_t InlineBits(uint64_t max_offset, uint64_t max_next, const Config &config);
ArrayBhiksha(void *base, uint64_t max_offset, uint64_t max_value, const Config &config);
void ReadNext(const void *base, uint64_t bit_offset, uint64_t index, uint8_t total_bits, NodeRange &out) const {
// Some assertions are commented out because they are expensive.
// assert(*offset_begin_ == 0);
// std::upper_bound returns the first element that is greater. Want the
// last element that is <= to the index.
const uint64_t *begin_it = std::upper_bound(offset_begin_, offset_end_, index) - 1;
// Since *offset_begin_ == 0, the position should be in range.
// assert(begin_it >= offset_begin_);
const uint64_t *end_it;
for (end_it = begin_it + 1; (end_it < offset_end_) && (*end_it <= index + 1); ++end_it) {}
// assert(end_it == std::upper_bound(offset_begin_, offset_end_, index + 1));
--end_it;
// assert(end_it >= begin_it);
out.begin = ((begin_it - offset_begin_) << next_inline_.bits) |
util::ReadInt57(base, bit_offset, next_inline_.bits, next_inline_.mask);
out.end = ((end_it - offset_begin_) << next_inline_.bits) |
util::ReadInt57(base, bit_offset + total_bits, next_inline_.bits, next_inline_.mask);
// If this fails, consider rebuilding your model using KenLM after 1e333d786b748555e8f368d2bbba29a016c98052
assert(out.end >= out.begin);
}
void WriteNext(void *base, uint64_t bit_offset, uint64_t index, uint64_t value) {
uint64_t encode = value >> next_inline_.bits;
for (; write_to_ <= offset_begin_ + encode; ++write_to_) *write_to_ = index;
util::WriteInt57(base, bit_offset, next_inline_.bits, value & next_inline_.mask);
}
void FinishedLoading(const Config &config);
uint8_t InlineBits() const { return next_inline_.bits; }
private:
const util::BitsMask next_inline_;
const uint64_t *const offset_begin_;
const uint64_t *const offset_end_;
uint64_t *write_to_;
void *original_base_;
};
} // namespace trie
} // namespace ngram
} // namespace lm
#endif // LM_BHIKSHA_H

View File

@ -0,0 +1,302 @@
#include "lm/binary_format.hh"
#include "lm/lm_exception.hh"
#include "util/file.hh"
#include "util/file_piece.hh"
#include <cstddef>
#include <cstring>
#include <limits>
#include <string>
#include <cstdlib>
#include <stdint.h>
namespace lm {
namespace ngram {
const char *kModelNames[6] = {"probing hash tables", "probing hash tables with rest costs", "trie", "trie with quantization", "trie with array-compressed pointers", "trie with quantization and array-compressed pointers"};
namespace {
const char kMagicBeforeVersion[] = "mmap lm http://kheafield.com/code format version";
const char kMagicBytes[] = "mmap lm http://kheafield.com/code format version 5\n\0";
// This must be shorter than kMagicBytes and indicates an incomplete binary file (i.e. build failed).
const char kMagicIncomplete[] = "mmap lm http://kheafield.com/code incomplete\n";
const long int kMagicVersion = 5;
// Old binary files built on 32-bit machines have this header.
// TODO: eliminate with next binary release.
struct OldSanity {
char magic[sizeof(kMagicBytes)];
float zero_f, one_f, minus_half_f;
WordIndex one_word_index, max_word_index;
uint64_t one_uint64;
void SetToReference() {
std::memset(this, 0, sizeof(OldSanity));
std::memcpy(magic, kMagicBytes, sizeof(magic));
zero_f = 0.0; one_f = 1.0; minus_half_f = -0.5;
one_word_index = 1;
max_word_index = std::numeric_limits<WordIndex>::max();
one_uint64 = 1;
}
};
// Test values aligned to 8 bytes.
struct Sanity {
char magic[ALIGN8(sizeof(kMagicBytes))];
float zero_f, one_f, minus_half_f;
WordIndex one_word_index, max_word_index, padding_to_8;
uint64_t one_uint64;
void SetToReference() {
std::memset(this, 0, sizeof(Sanity));
std::memcpy(magic, kMagicBytes, sizeof(kMagicBytes));
zero_f = 0.0; one_f = 1.0; minus_half_f = -0.5;
one_word_index = 1;
max_word_index = std::numeric_limits<WordIndex>::max();
padding_to_8 = 0;
one_uint64 = 1;
}
};
std::size_t TotalHeaderSize(unsigned char order) {
return ALIGN8(sizeof(Sanity) + sizeof(FixedWidthParameters) + sizeof(uint64_t) * order);
}
void WriteHeader(void *to, const Parameters &params) {
Sanity header = Sanity();
header.SetToReference();
std::memcpy(to, &header, sizeof(Sanity));
char *out = reinterpret_cast<char*>(to) + sizeof(Sanity);
*reinterpret_cast<FixedWidthParameters*>(out) = params.fixed;
out += sizeof(FixedWidthParameters);
uint64_t *counts = reinterpret_cast<uint64_t*>(out);
for (std::size_t i = 0; i < params.counts.size(); ++i) {
counts[i] = params.counts[i];
}
}
} // namespace
bool IsBinaryFormat(int fd) {
const uint64_t size = util::SizeFile(fd);
if (size == util::kBadSize || (size <= static_cast<uint64_t>(sizeof(Sanity)))) return false;
// Try reading the header.
util::scoped_memory memory;
try {
util::MapRead(util::LAZY, fd, 0, sizeof(Sanity), memory);
} catch (const util::Exception &e) {
return false;
}
Sanity reference_header = Sanity();
reference_header.SetToReference();
if (!std::memcmp(memory.get(), &reference_header, sizeof(Sanity))) return true;
if (!std::memcmp(memory.get(), kMagicIncomplete, strlen(kMagicIncomplete))) {
UTIL_THROW(FormatLoadException, "This binary file did not finish building");
}
if (!std::memcmp(memory.get(), kMagicBeforeVersion, strlen(kMagicBeforeVersion))) {
char *end_ptr;
const char *begin_version = static_cast<const char*>(memory.get()) + strlen(kMagicBeforeVersion);
long int version = std::strtol(begin_version, &end_ptr, 10);
if ((end_ptr != begin_version) && version != kMagicVersion) {
UTIL_THROW(FormatLoadException, "Binary file has version " << version << " but this implementation expects version " << kMagicVersion << " so you'll have to use the ARPA to rebuild your binary");
}
OldSanity old_sanity = OldSanity();
old_sanity.SetToReference();
UTIL_THROW_IF(!std::memcmp(memory.get(), &old_sanity, sizeof(OldSanity)), FormatLoadException, "Looks like this is an old 32-bit format. The old 32-bit format has been removed so that 64-bit and 32-bit files are exchangeable.");
UTIL_THROW(FormatLoadException, "File looks like it should be loaded with mmap, but the test values don't match. Try rebuilding the binary format LM using the same code revision, compiler, and architecture");
}
return false;
}
void ReadHeader(int fd, Parameters &out) {
util::SeekOrThrow(fd, sizeof(Sanity));
util::ReadOrThrow(fd, &out.fixed, sizeof(out.fixed));
if (out.fixed.probing_multiplier < 1.0)
UTIL_THROW(FormatLoadException, "Binary format claims to have a probing multiplier of " << out.fixed.probing_multiplier << " which is < 1.0.");
out.counts.resize(static_cast<std::size_t>(out.fixed.order));
if (out.fixed.order) util::ReadOrThrow(fd, &*out.counts.begin(), sizeof(uint64_t) * out.fixed.order);
}
void MatchCheck(ModelType model_type, unsigned int search_version, const Parameters &params) {
if (params.fixed.model_type != model_type) {
if (static_cast<unsigned int>(params.fixed.model_type) >= (sizeof(kModelNames) / sizeof(const char *)))
UTIL_THROW(FormatLoadException, "The binary file claims to be model type " << static_cast<unsigned int>(params.fixed.model_type) << " but this is not implemented for in this inference code.");
UTIL_THROW(FormatLoadException, "The binary file was built for " << kModelNames[params.fixed.model_type] << " but the inference code is trying to load " << kModelNames[model_type]);
}
UTIL_THROW_IF(search_version != params.fixed.search_version, FormatLoadException, "The binary file has " << kModelNames[params.fixed.model_type] << " version " << params.fixed.search_version << " but this code expects " << kModelNames[params.fixed.model_type] << " version " << search_version);
}
const std::size_t kInvalidSize = static_cast<std::size_t>(-1);
BinaryFormat::BinaryFormat(const Config &config)
: write_method_(config.write_method), write_mmap_(config.write_mmap), load_method_(config.load_method),
header_size_(kInvalidSize), vocab_size_(kInvalidSize), vocab_string_offset_(kInvalidOffset) {}
void BinaryFormat::InitializeBinary(int fd, ModelType model_type, unsigned int search_version, Parameters &params) {
file_.reset(fd);
write_mmap_ = NULL; // Ignore write requests; this is already in binary format.
ReadHeader(fd, params);
MatchCheck(model_type, search_version, params);
header_size_ = TotalHeaderSize(params.counts.size());
}
void BinaryFormat::ReadForConfig(void *to, std::size_t amount, uint64_t offset_excluding_header) const {
assert(header_size_ != kInvalidSize);
util::ErsatzPRead(file_.get(), to, amount, offset_excluding_header + header_size_);
}
void *BinaryFormat::LoadBinary(std::size_t size) {
assert(header_size_ != kInvalidSize);
const uint64_t file_size = util::SizeFile(file_.get());
// The header is smaller than a page, so we have to map the whole header as well.
uint64_t total_map = static_cast<uint64_t>(header_size_) + static_cast<uint64_t>(size);
UTIL_THROW_IF(file_size != util::kBadSize && file_size < total_map, FormatLoadException, "Binary file has size " << file_size << " but the headers say it should be at least " << total_map);
util::MapRead(load_method_, file_.get(), 0, util::CheckOverflow(total_map), mapping_);
vocab_string_offset_ = total_map;
return reinterpret_cast<uint8_t*>(mapping_.get()) + header_size_;
}
void *BinaryFormat::SetupJustVocab(std::size_t memory_size, uint8_t order) {
vocab_size_ = memory_size;
if (!write_mmap_) {
header_size_ = 0;
util::HugeMalloc(memory_size, true, memory_vocab_);
return reinterpret_cast<uint8_t*>(memory_vocab_.get());
}
header_size_ = TotalHeaderSize(order);
std::size_t total = util::CheckOverflow(static_cast<uint64_t>(header_size_) + static_cast<uint64_t>(memory_size));
file_.reset(util::CreateOrThrow(write_mmap_));
// some gccs complain about uninitialized variables even though all enum values are covered.
void *vocab_base = NULL;
switch (write_method_) {
case Config::WRITE_MMAP:
mapping_.reset(util::MapZeroedWrite(file_.get(), total), total, util::scoped_memory::MMAP_ALLOCATED);
util::AdviseHugePages(vocab_base, total);
vocab_base = mapping_.get();
break;
case Config::WRITE_AFTER:
util::ResizeOrThrow(file_.get(), 0);
util::HugeMalloc(total, true, memory_vocab_);
vocab_base = memory_vocab_.get();
break;
}
strncpy(reinterpret_cast<char*>(vocab_base), kMagicIncomplete, header_size_);
return reinterpret_cast<uint8_t*>(vocab_base) + header_size_;
}
void *BinaryFormat::GrowForSearch(std::size_t memory_size, std::size_t vocab_pad, void *&vocab_base) {
assert(vocab_size_ != kInvalidSize);
vocab_pad_ = vocab_pad;
std::size_t new_size = header_size_ + vocab_size_ + vocab_pad_ + memory_size;
vocab_string_offset_ = new_size;
if (!write_mmap_ || write_method_ == Config::WRITE_AFTER) {
util::HugeMalloc(memory_size, true, memory_search_);
assert(header_size_ == 0 || write_mmap_);
vocab_base = reinterpret_cast<uint8_t*>(memory_vocab_.get()) + header_size_;
util::AdviseHugePages(memory_search_.get(), memory_size);
return reinterpret_cast<uint8_t*>(memory_search_.get());
}
assert(write_method_ == Config::WRITE_MMAP);
// Also known as total size without vocab words.
// Grow the file to accomodate the search, using zeros.
// According to man mmap, behavior is undefined when the file is resized
// underneath a mmap that is not a multiple of the page size. So to be
// safe, we'll unmap it and map it again.
mapping_.reset();
util::ResizeOrThrow(file_.get(), new_size);
void *ret;
MapFile(vocab_base, ret);
util::AdviseHugePages(ret, new_size);
return ret;
}
void BinaryFormat::WriteVocabWords(const std::string &buffer, void *&vocab_base, void *&search_base) {
// Checking Config's include_vocab is the responsibility of the caller.
assert(header_size_ != kInvalidSize && vocab_size_ != kInvalidSize);
if (!write_mmap_) {
// Unchanged base.
vocab_base = reinterpret_cast<uint8_t*>(memory_vocab_.get());
search_base = reinterpret_cast<uint8_t*>(memory_search_.get());
return;
}
if (write_method_ == Config::WRITE_MMAP) {
mapping_.reset();
}
util::SeekOrThrow(file_.get(), VocabStringReadingOffset());
util::WriteOrThrow(file_.get(), &buffer[0], buffer.size());
if (write_method_ == Config::WRITE_MMAP) {
MapFile(vocab_base, search_base);
} else {
vocab_base = reinterpret_cast<uint8_t*>(memory_vocab_.get()) + header_size_;
search_base = reinterpret_cast<uint8_t*>(memory_search_.get());
}
}
void BinaryFormat::FinishFile(const Config &config, ModelType model_type, unsigned int search_version, const std::vector<uint64_t> &counts) {
if (!write_mmap_) return;
switch (write_method_) {
case Config::WRITE_MMAP:
util::SyncOrThrow(mapping_.get(), mapping_.size());
break;
case Config::WRITE_AFTER:
util::SeekOrThrow(file_.get(), 0);
util::WriteOrThrow(file_.get(), memory_vocab_.get(), memory_vocab_.size());
util::SeekOrThrow(file_.get(), header_size_ + vocab_size_ + vocab_pad_);
util::WriteOrThrow(file_.get(), memory_search_.get(), memory_search_.size());
util::FSyncOrThrow(file_.get());
break;
}
// header and vocab share the same mmap.
Parameters params = Parameters();
memset(&params, 0, sizeof(Parameters));
params.counts = counts;
params.fixed.order = counts.size();
params.fixed.probing_multiplier = config.probing_multiplier;
params.fixed.model_type = model_type;
params.fixed.has_vocabulary = config.include_vocab;
params.fixed.search_version = search_version;
switch (write_method_) {
case Config::WRITE_MMAP:
WriteHeader(mapping_.get(), params);
util::SyncOrThrow(mapping_.get(), mapping_.size());
break;
case Config::WRITE_AFTER:
{
std::vector<uint8_t> buffer(TotalHeaderSize(counts.size()));
WriteHeader(&buffer[0], params);
util::SeekOrThrow(file_.get(), 0);
util::WriteOrThrow(file_.get(), &buffer[0], buffer.size());
}
break;
}
}
void BinaryFormat::MapFile(void *&vocab_base, void *&search_base) {
mapping_.reset(util::MapOrThrow(vocab_string_offset_, true, util::kFileFlags, false, file_.get()), vocab_string_offset_, util::scoped_memory::MMAP_ALLOCATED);
vocab_base = reinterpret_cast<uint8_t*>(mapping_.get()) + header_size_;
search_base = reinterpret_cast<uint8_t*>(mapping_.get()) + header_size_ + vocab_size_ + vocab_pad_;
}
bool RecognizeBinary(const char *file, ModelType &recognized) {
util::scoped_fd fd(util::OpenReadOrThrow(file));
if (!IsBinaryFormat(fd.get())) {
return false;
}
Parameters params;
ReadHeader(fd.get(), params);
recognized = params.fixed.model_type;
return true;
}
} // namespace ngram
} // namespace lm

View File

@ -0,0 +1,106 @@
#ifndef LM_BINARY_FORMAT_H
#define LM_BINARY_FORMAT_H
#include "lm/config.hh"
#include "lm/model_type.hh"
#include "lm/read_arpa.hh"
#include "util/file_piece.hh"
#include "util/mmap.hh"
#include "util/scoped.hh"
#include <cstddef>
#include <vector>
#include <stdint.h>
namespace lm {
namespace ngram {
extern const char *kModelNames[6];
/*Inspect a file to determine if it is a binary lm. If not, return false.
* If so, return true and set recognized to the type. This is the only API in
* this header designed for use by decoder authors.
*/
bool RecognizeBinary(const char *file, ModelType &recognized);
struct FixedWidthParameters {
unsigned char order;
float probing_multiplier;
// What type of model is this?
ModelType model_type;
// Does the end of the file have the actual strings in the vocabulary?
bool has_vocabulary;
unsigned int search_version;
};
// This is a macro instead of an inline function so constants can be assigned using it.
#define ALIGN8(a) ((std::ptrdiff_t(((a)-1)/8)+1)*8)
// Parameters stored in the header of a binary file.
struct Parameters {
FixedWidthParameters fixed;
std::vector<uint64_t> counts;
};
class BinaryFormat {
public:
explicit BinaryFormat(const Config &config);
// Reading a binary file:
// Takes ownership of fd
void InitializeBinary(int fd, ModelType model_type, unsigned int search_version, Parameters &params);
// Used to read parts of the file to update the config object before figuring out full size.
void ReadForConfig(void *to, std::size_t amount, uint64_t offset_excluding_header) const;
// Actually load the binary file and return a pointer to the beginning of the search area.
void *LoadBinary(std::size_t size);
uint64_t VocabStringReadingOffset() const {
assert(vocab_string_offset_ != kInvalidOffset);
return vocab_string_offset_;
}
// Writing a binary file or initializing in RAM from ARPA:
// Size for vocabulary.
void *SetupJustVocab(std::size_t memory_size, uint8_t order);
// Warning: can change the vocaulary base pointer.
void *GrowForSearch(std::size_t memory_size, std::size_t vocab_pad, void *&vocab_base);
// Warning: can change vocabulary and search base addresses.
void WriteVocabWords(const std::string &buffer, void *&vocab_base, void *&search_base);
// Write the header at the beginning of the file.
void FinishFile(const Config &config, ModelType model_type, unsigned int search_version, const std::vector<uint64_t> &counts);
private:
void MapFile(void *&vocab_base, void *&search_base);
// Copied from configuration.
const Config::WriteMethod write_method_;
const char *write_mmap_;
util::LoadMethod load_method_;
// File behind memory, if any.
util::scoped_fd file_;
// If there is a file involved, a single mapping.
util::scoped_memory mapping_;
// If the data is only in memory, separately allocate each because the trie
// knows vocab's size before it knows search's size (because SRILM might
// have pruned).
util::scoped_memory memory_vocab_, memory_search_;
// Memory ranges. Note that these may not be contiguous and may not all
// exist.
std::size_t header_size_, vocab_size_, vocab_pad_;
// aka end of search.
uint64_t vocab_string_offset_;
static const uint64_t kInvalidOffset = (uint64_t)-1;
};
bool IsBinaryFormat(int fd);
} // namespace ngram
} // namespace lm
#endif // LM_BINARY_FORMAT_H

View File

@ -0,0 +1,42 @@
#ifndef LM_BLANK_H
#define LM_BLANK_H
#include <limits>
#include <stdint.h>
#include <cmath>
namespace lm {
namespace ngram {
/* Suppose "foo bar" appears with zero backoff but there is no trigram
* beginning with these words. Then, when scoring "foo bar", the model could
* return out_state containing "bar" or even null context if "bar" also has no
* backoff and is never followed by another word. Then the backoff is set to
* kNoExtensionBackoff. If the n-gram might be extended, then out_state must
* contain the full n-gram, in which case kExtensionBackoff is set. In any
* case, if an n-gram has non-zero backoff, the full state is returned so
* backoff can be properly charged.
* These differ only in sign bit because the backoff is in fact zero in either
* case.
*/
const float kNoExtensionBackoff = -0.0;
const float kExtensionBackoff = 0.0;
const uint64_t kNoExtensionQuant = 0;
const uint64_t kExtensionQuant = 1;
inline void SetExtension(float &backoff) {
if (backoff == kNoExtensionBackoff) backoff = kExtensionBackoff;
}
// This compiles down nicely.
inline bool HasExtension(const float &backoff) {
typedef union { float f; uint32_t i; } UnionValue;
UnionValue compare, interpret;
compare.f = kNoExtensionBackoff;
interpret.f = backoff;
return compare.i != interpret.i;
}
} // namespace ngram
} // namespace lm
#endif // LM_BLANK_H

View File

@ -0,0 +1,234 @@
#include "lm/model.hh"
#include "lm/sizes.hh"
#include "util/file_piece.hh"
#include "util/usage.hh"
#include <algorithm>
#include <cstdlib>
#include <exception>
#include <iostream>
#include <iomanip>
#include <limits>
#include <cmath>
#include <cstdlib>
#ifdef WIN32
#include "util/getopt.hh"
#else
#include <unistd.h>
#endif
namespace lm {
namespace ngram {
namespace {
void Usage(const char *name, const char *default_mem) {
std::cerr << "Usage: " << name << " [-u log10_unknown_probability] [-s] [-i] [-w mmap|after] [-p probing_multiplier] [-T trie_temporary] [-S trie_building_mem] [-q bits] [-b bits] [-a bits] [type] input.arpa [output.mmap]\n\n"
"-u sets the log10 probability for <unk> if the ARPA file does not have one.\n"
" Default is -100. The ARPA file will always take precedence.\n"
"-s allows models to be built even if they do not have <s> and </s>.\n"
"-i allows buggy models from IRSTLM by mapping positive log probability to 0.\n"
"-w mmap|after determines how writing is done.\n"
" mmap maps the binary file and writes to it. Default for trie.\n"
" after allocates anonymous memory, builds, and writes. Default for probing.\n"
"-r \"order1.arpa order2 order3 order4\" adds lower-order rest costs from these\n"
" model files. order1.arpa must be an ARPA file. All others may be ARPA or\n"
" the same data structure as being built. All files must have the same\n"
" vocabulary. For probing, the unigrams must be in the same order.\n\n"
"type is either probing or trie. Default is probing.\n\n"
"probing uses a probing hash table. It is the fastest but uses the most memory.\n"
"-p sets the space multiplier and must be >1.0. The default is 1.5.\n\n"
"trie is a straightforward trie with bit-level packing. It uses the least\n"
"memory and is still faster than SRI or IRST. Building the trie format uses an\n"
"on-disk sort to save memory.\n"
"-T is the temporary directory prefix. Default is the output file name.\n"
"-S determines memory use for sorting. Default is " << default_mem << ". This is compatible\n"
" with GNU sort. The number is followed by a unit: \% for percent of physical\n"
" memory, b for bytes, K for Kilobytes, M for megabytes, then G,T,P,E,Z,Y. \n"
" Default unit is K for Kilobytes.\n"
"-q turns quantization on and sets the number of bits (e.g. -q 8).\n"
"-b sets backoff quantization bits. Requires -q and defaults to that value.\n"
"-a compresses pointers using an array of offsets. The parameter is the\n"
" maximum number of bits encoded by the array. Memory is minimized subject\n"
" to the maximum, so pick 255 to minimize memory.\n\n"
"-h print this help message.\n\n"
"Get a memory estimate by passing an ARPA file without an output file name.\n";
exit(1);
}
// I could really use boost::lexical_cast right about now.
float ParseFloat(const char *from) {
char *end;
float ret = strtod(from, &end);
if (*end) throw util::ParseNumberException(from);
return ret;
}
unsigned long int ParseUInt(const char *from) {
char *end;
unsigned long int ret = strtoul(from, &end, 10);
if (*end) throw util::ParseNumberException(from);
return ret;
}
uint8_t ParseBitCount(const char *from) {
unsigned long val = ParseUInt(from);
if (val > 25) {
util::ParseNumberException e(from);
e << " bit counts are limited to 25.";
}
return val;
}
void ParseFileList(const char *from, std::vector<std::string> &to) {
to.clear();
while (true) {
const char *i;
for (i = from; *i && *i != ' '; ++i) {}
to.push_back(std::string(from, i - from));
if (!*i) break;
from = i + 1;
}
}
void ProbingQuantizationUnsupported() {
std::cerr << "Quantization is only implemented in the trie data structure." << std::endl;
exit(1);
}
} // namespace ngram
} // namespace lm
} // namespace
int main(int argc, char *argv[]) {
using namespace lm::ngram;
const char *default_mem = util::GuessPhysicalMemory() ? "80%" : "1G";
if (argc == 2 && !strcmp(argv[1], "--help"))
Usage(argv[0], default_mem);
try {
bool quantize = false, set_backoff_bits = false, bhiksha = false, set_write_method = false, rest = false;
lm::ngram::Config config;
config.building_memory = util::ParseSize(default_mem);
int opt;
while ((opt = getopt(argc, argv, "q:b:a:u:p:t:T:m:S:w:sir:h")) != -1) {
switch(opt) {
case 'q':
config.prob_bits = ParseBitCount(optarg);
if (!set_backoff_bits) config.backoff_bits = config.prob_bits;
quantize = true;
break;
case 'b':
config.backoff_bits = ParseBitCount(optarg);
set_backoff_bits = true;
break;
case 'a':
config.pointer_bhiksha_bits = ParseBitCount(optarg);
bhiksha = true;
break;
case 'u':
config.unknown_missing_logprob = ParseFloat(optarg);
break;
case 'p':
config.probing_multiplier = ParseFloat(optarg);
break;
case 't': // legacy
case 'T':
config.temporary_directory_prefix = optarg;
util::NormalizeTempPrefix(config.temporary_directory_prefix);
break;
case 'm': // legacy
config.building_memory = ParseUInt(optarg) * 1048576;
break;
case 'S':
config.building_memory = std::min(static_cast<uint64_t>(std::numeric_limits<std::size_t>::max()), util::ParseSize(optarg));
break;
case 'w':
set_write_method = true;
if (!strcmp(optarg, "mmap")) {
config.write_method = Config::WRITE_MMAP;
} else if (!strcmp(optarg, "after")) {
config.write_method = Config::WRITE_AFTER;
} else {
Usage(argv[0], default_mem);
}
break;
case 's':
config.sentence_marker_missing = lm::SILENT;
break;
case 'i':
config.positive_log_probability = lm::SILENT;
break;
case 'r':
rest = true;
ParseFileList(optarg, config.rest_lower_files);
config.rest_function = Config::REST_LOWER;
break;
case 'h': // help
default:
Usage(argv[0], default_mem);
}
}
if (!quantize && set_backoff_bits) {
std::cerr << "You specified backoff quantization (-b) but not probability quantization (-q)" << std::endl;
abort();
}
if (optind + 1 == argc) {
ShowSizes(argv[optind], config);
return 0;
}
const char *model_type;
const char *from_file;
if (optind + 2 == argc) {
model_type = "probing";
from_file = argv[optind];
config.write_mmap = argv[optind + 1];
} else if (optind + 3 == argc) {
model_type = argv[optind];
from_file = argv[optind + 1];
config.write_mmap = argv[optind + 2];
} else {
Usage(argv[0], default_mem);
return 1;
}
if (!strcmp(model_type, "probing")) {
if (!set_write_method) config.write_method = Config::WRITE_AFTER;
if (quantize || set_backoff_bits) ProbingQuantizationUnsupported();
if (rest) {
RestProbingModel(from_file, config);
} else {
ProbingModel(from_file, config);
}
} else if (!strcmp(model_type, "trie")) {
if (rest) {
std::cerr << "Rest + trie is not supported yet." << std::endl;
return 1;
}
if (!set_write_method) config.write_method = Config::WRITE_MMAP;
if (quantize) {
if (bhiksha) {
QuantArrayTrieModel(from_file, config);
} else {
QuantTrieModel(from_file, config);
}
} else {
if (bhiksha) {
ArrayTrieModel(from_file, config);
} else {
TrieModel(from_file, config);
}
}
} else {
Usage(argv[0], default_mem);
}
}
catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
std::cerr << "ERROR" << std::endl;
return 1;
}
std::cerr << "SUCCESS" << std::endl;
return 0;
}

View File

@ -0,0 +1,25 @@
# This CMake file was created by Lane Schwartz <dowobeha@gmail.com>
# Explicitly list the source files for this subdirectory
#
# If you add any source files to this subdirectory
# that should be included in the kenlm library,
# (this excludes any unit test files)
# you should add them to the following list:
#
# In order to set correct paths to these files
# in case this variable is referenced by CMake files in the parent directory,
# we prefix all files with ${CMAKE_CURRENT_SOURCE_DIR}.
#
set(KENLM_LM_COMMON_SOURCE
${CMAKE_CURRENT_SOURCE_DIR}/model_buffer.cc
${CMAKE_CURRENT_SOURCE_DIR}/print.cc
${CMAKE_CURRENT_SOURCE_DIR}/renumber.cc
${CMAKE_CURRENT_SOURCE_DIR}/size_option.cc
PARENT_SCOPE)
if(BUILD_TESTING)
KenLMAddTest(TEST model_buffer_test
LIBRARIES kenlm
TEST_ARGS ${CMAKE_CURRENT_SOURCE_DIR}/test_data)
endif()

View File

@ -0,0 +1,185 @@
#ifndef LM_COMMON_COMPARE_H
#define LM_COMMON_COMPARE_H
#include "lm/common/ngram.hh"
#include "lm/word_index.hh"
#include <functional>
#include <string>
namespace lm {
/**
* Abstract parent class for defining custom n-gram comparators.
*/
template <class Child> class Comparator : public std::binary_function<const void *, const void *, bool> {
public:
/**
* Constructs a comparator capable of comparing two n-grams.
*
* @param order Number of words in each n-gram
*/
explicit Comparator(std::size_t order) : order_(order) {}
/**
* Applies the comparator using the Compare method that must be defined in any class that inherits from this class.
*
* @param lhs A pointer to the n-gram on the left-hand side of the comparison
* @param rhs A pointer to the n-gram on the right-hand side of the comparison
*
* @see ContextOrder::Compare
* @see PrefixOrder::Compare
* @see SuffixOrder::Compare
*/
inline bool operator()(const void *lhs, const void *rhs) const {
return static_cast<const Child*>(this)->Compare(static_cast<const WordIndex*>(lhs), static_cast<const WordIndex*>(rhs));
}
/** Gets the n-gram order defined for this comparator. */
std::size_t Order() const { return order_; }
protected:
std::size_t order_;
};
/**
* N-gram comparator that compares n-grams according to their reverse (suffix) order.
*
* This comparator compares n-grams lexicographically, one word at a time,
* beginning with the last word of each n-gram and ending with the first word of each n-gram.
*
* Some examples of n-gram comparisons as defined by this comparator:
* - a b c == a b c
* - a b c < a b d
* - a b c > a d b
* - a b c > a b b
* - a b c > x a c
* - a b c < x y z
*/
class SuffixOrder : public Comparator<SuffixOrder> {
public:
/**
* Constructs a comparator capable of comparing two n-grams.
*
* @param order Number of words in each n-gram
*/
explicit SuffixOrder(std::size_t order) : Comparator<SuffixOrder>(order) {}
/**
* Compares two n-grams lexicographically, one word at a time,
* beginning with the last word of each n-gram and ending with the first word of each n-gram.
*
* @param lhs A pointer to the n-gram on the left-hand side of the comparison
* @param rhs A pointer to the n-gram on the right-hand side of the comparison
*/
inline bool Compare(const WordIndex *lhs, const WordIndex *rhs) const {
for (std::size_t i = order_ - 1; i != 0; --i) {
if (lhs[i] != rhs[i])
return lhs[i] < rhs[i];
}
return lhs[0] < rhs[0];
}
static const unsigned kMatchOffset = 1;
};
/**
* N-gram comparator that compares n-grams according to the reverse (suffix) order of the n-gram context.
*
* This comparator compares n-grams lexicographically, one word at a time,
* beginning with the penultimate word of each n-gram and ending with the first word of each n-gram;
* finally, this comparator compares the last word of each n-gram.
*
* Some examples of n-gram comparisons as defined by this comparator:
* - a b c == a b c
* - a b c < a b d
* - a b c < a d b
* - a b c > a b b
* - a b c > x a c
* - a b c < x y z
*/
class ContextOrder : public Comparator<ContextOrder> {
public:
/**
* Constructs a comparator capable of comparing two n-grams.
*
* @param order Number of words in each n-gram
*/
explicit ContextOrder(std::size_t order) : Comparator<ContextOrder>(order) {}
/**
* Compares two n-grams lexicographically, one word at a time,
* beginning with the penultimate word of each n-gram and ending with the first word of each n-gram;
* finally, this comparator compares the last word of each n-gram.
*
* @param lhs A pointer to the n-gram on the left-hand side of the comparison
* @param rhs A pointer to the n-gram on the right-hand side of the comparison
*/
inline bool Compare(const WordIndex *lhs, const WordIndex *rhs) const {
for (int i = order_ - 2; i >= 0; --i) {
if (lhs[i] != rhs[i])
return lhs[i] < rhs[i];
}
return lhs[order_ - 1] < rhs[order_ - 1];
}
};
/**
* N-gram comparator that compares n-grams according to their natural (prefix) order.
*
* This comparator compares n-grams lexicographically, one word at a time,
* beginning with the first word of each n-gram and ending with the last word of each n-gram.
*
* Some examples of n-gram comparisons as defined by this comparator:
* - a b c == a b c
* - a b c < a b d
* - a b c < a d b
* - a b c > a b b
* - a b c < x a c
* - a b c < x y z
*/
class PrefixOrder : public Comparator<PrefixOrder> {
public:
/**
* Constructs a comparator capable of comparing two n-grams.
*
* @param order Number of words in each n-gram
*/
explicit PrefixOrder(std::size_t order) : Comparator<PrefixOrder>(order) {}
/**
* Compares two n-grams lexicographically, one word at a time,
* beginning with the first word of each n-gram and ending with the last word of each n-gram.
*
* @param lhs A pointer to the n-gram on the left-hand side of the comparison
* @param rhs A pointer to the n-gram on the right-hand side of the comparison
*/
inline bool Compare(const WordIndex *lhs, const WordIndex *rhs) const {
for (std::size_t i = 0; i < order_; ++i) {
if (lhs[i] != rhs[i])
return lhs[i] < rhs[i];
}
return false;
}
static const unsigned kMatchOffset = 0;
};
template <class Range> struct SuffixLexicographicLess : public std::binary_function<const Range, const Range, bool> {
bool operator()(const Range first, const Range second) const {
for (const WordIndex *f = first.end() - 1, *s = second.end() - 1; f >= first.begin() && s >= second.begin(); --f, --s) {
if (*f < *s) return true;
if (*f > *s) return false;
}
return first.size() < second.size();
}
};
} // namespace lm
#endif // LM_COMMON_COMPARE_H

View File

@ -0,0 +1,71 @@
#ifndef LM_COMMON_JOINT_ORDER_H
#define LM_COMMON_JOINT_ORDER_H
#include "lm/common/ngram_stream.hh"
#include "lm/lm_exception.hh"
#ifdef DEBUG
#include "util/fixed_array.hh"
#include <iostream>
#endif
#include <cstring>
namespace lm {
template <class Callback, class Compare> void JointOrder(const util::stream::ChainPositions &positions, Callback &callback) {
// Allow matching to reference streams[-1].
util::FixedArray<ProxyStream<NGramHeader> > streams_with_dummy(positions.size() + 1);
// A bogus stream for [-1].
streams_with_dummy.push_back();
for (std::size_t i = 0; i < positions.size(); ++i) {
streams_with_dummy.push_back(positions[i], NGramHeader(NULL, i + 1));
}
ProxyStream<NGramHeader> *streams = streams_with_dummy.begin() + 1;
std::size_t order;
for (order = 0; order < positions.size() && streams[order]; ++order) {}
assert(order); // should always have <unk>.
// Debugging only: call comparison function to sanity check order.
#ifdef DEBUG
util::FixedArray<Compare> less_compare(order);
for (unsigned i = 0; i < order; ++i)
less_compare.push_back(i + 1);
#endif // DEBUG
std::size_t current = 0;
while (true) {
// Does the context match the lower one?
if (!memcmp(streams[static_cast<int>(current) - 1]->begin(), streams[current]->begin() + Compare::kMatchOffset, sizeof(WordIndex) * current)) {
callback.Enter(current, streams[current].Get());
// Transition to looking for extensions.
if (++current < order) continue;
}
#ifdef DEBUG
// match_check[current - 1] matches current-grams
// The lower-order stream (which skips fewer current-grams) should always be <= the higher order-stream (which can skip current-grams).
else if (!less_compare[current - 1](streams[static_cast<int>(current) - 1]->begin(), streams[current]->begin() + Compare::kMatchOffset)) {
std::cerr << "Stream out of order detected" << std::endl;
abort();
}
#endif // DEBUG
// No extension left.
while(true) {
assert(current > 0);
--current;
callback.Exit(current, streams[current].Get());
if (++streams[current]) break;
UTIL_THROW_IF(order != current + 1, FormatLoadException, "Detected n-gram without matching suffix");
order = current;
if (!order) return;
}
}
}
} // namespaces
#endif // LM_COMMON_JOINT_ORDER_H

View File

@ -0,0 +1,144 @@
#include "lm/common/model_buffer.hh"
#include "lm/common/compare.hh"
#include "lm/state.hh"
#include "lm/weights.hh"
#include "util/exception.hh"
#include "util/file_stream.hh"
#include "util/file.hh"
#include "util/file_piece.hh"
#include "util/stream/io.hh"
#include "util/stream/multi_stream.hh"
#include <boost/lexical_cast.hpp>
#include <numeric>
namespace lm {
namespace {
const char kMetadataHeader[] = "KenLM intermediate binary file";
} // namespace
ModelBuffer::ModelBuffer(StringPiece file_base, bool keep_buffer, bool output_q)
: file_base_(file_base.data(), file_base.size()), keep_buffer_(keep_buffer), output_q_(output_q),
vocab_file_(keep_buffer ? util::CreateOrThrow((file_base_ + ".vocab").c_str()) : util::MakeTemp(file_base_)) {}
ModelBuffer::ModelBuffer(StringPiece file_base)
: file_base_(file_base.data(), file_base.size()), keep_buffer_(false) {
const std::string full_name = file_base_ + ".kenlm_intermediate";
util::FilePiece in(full_name.c_str());
StringPiece token = in.ReadLine();
UTIL_THROW_IF2(token != kMetadataHeader, "File " << full_name << " begins with \"" << token << "\" not " << kMetadataHeader);
token = in.ReadDelimited();
UTIL_THROW_IF2(token != "Counts", "Expected Counts, got \"" << token << "\" in " << full_name);
char got;
while ((got = in.get()) == ' ') {
counts_.push_back(in.ReadULong());
}
UTIL_THROW_IF2(got != '\n', "Expected newline at end of counts.");
token = in.ReadDelimited();
UTIL_THROW_IF2(token != "Payload", "Expected Payload, got \"" << token << "\" in " << full_name);
token = in.ReadDelimited();
if (token == "q") {
output_q_ = true;
} else if (token == "pb") {
output_q_ = false;
} else {
UTIL_THROW(util::Exception, "Unknown payload " << token);
}
vocab_file_.reset(util::OpenReadOrThrow((file_base_ + ".vocab").c_str()));
files_.Init(counts_.size());
for (unsigned long i = 0; i < counts_.size(); ++i) {
files_.push_back(util::OpenReadOrThrow((file_base_ + '.' + boost::lexical_cast<std::string>(i + 1)).c_str()));
}
}
void ModelBuffer::Sink(util::stream::Chains &chains, const std::vector<uint64_t> &counts) {
counts_ = counts;
// Open files.
files_.Init(chains.size());
for (std::size_t i = 0; i < chains.size(); ++i) {
if (keep_buffer_) {
files_.push_back(util::CreateOrThrow(
(file_base_ + '.' + boost::lexical_cast<std::string>(i + 1)).c_str()
));
} else {
files_.push_back(util::MakeTemp(file_base_));
}
chains[i] >> util::stream::Write(files_.back().get());
}
if (keep_buffer_) {
util::scoped_fd metadata(util::CreateOrThrow((file_base_ + ".kenlm_intermediate").c_str()));
util::FileStream meta(metadata.get(), 200);
meta << kMetadataHeader << "\nCounts";
for (std::vector<uint64_t>::const_iterator i = counts_.begin(); i != counts_.end(); ++i) {
meta << ' ' << *i;
}
meta << "\nPayload " << (output_q_ ? "q" : "pb") << '\n';
}
}
void ModelBuffer::Source(util::stream::Chains &chains) {
assert(chains.size() <= files_.size());
for (unsigned int i = 0; i < chains.size(); ++i) {
chains[i].SetProgressTarget(util::SizeOrThrow(files_[i].get()));
chains[i] >> util::stream::PRead(files_[i].get());
}
}
void ModelBuffer::Source(std::size_t order_minus_1, util::stream::Chain &chain) {
chain >> util::stream::PRead(files_[order_minus_1].get());
}
float ModelBuffer::SlowQuery(const ngram::State &context, WordIndex word, ngram::State &out) const {
// Lookup unigram.
ProbBackoff value;
util::ErsatzPRead(RawFile(0), &value, sizeof(value), word * (sizeof(WordIndex) + sizeof(value)) + sizeof(WordIndex));
out.backoff[0] = value.backoff;
out.words[0] = word;
out.length = 1;
std::vector<WordIndex> buffer(context.length + 1), query(context.length + 1);
std::reverse_copy(context.words, context.words + context.length, query.begin());
query[context.length] = word;
for (std::size_t order = 2; order <= query.size() && order <= context.length + 1; ++order) {
SuffixOrder less(order);
const WordIndex *key = &*query.end() - order;
int file = RawFile(order - 1);
std::size_t length = order * sizeof(WordIndex) + sizeof(ProbBackoff);
// TODO: cache file size?
uint64_t begin = 0, end = util::SizeOrThrow(file) / length;
while (true) {
if (end <= begin) {
// Did not find for order.
return std::accumulate(context.backoff + out.length - 1, context.backoff + context.length, value.prob);
}
uint64_t test = begin + (end - begin) / 2;
util::ErsatzPRead(file, &*buffer.begin(), sizeof(WordIndex) * order, test * length);
if (less(&*buffer.begin(), key)) {
begin = test + 1;
} else if (less(key, &*buffer.begin())) {
end = test;
} else {
// Found it.
util::ErsatzPRead(file, &value, sizeof(value), test * length + sizeof(WordIndex) * order);
if (order != Order()) {
out.length = order;
out.backoff[order - 1] = value.backoff;
out.words[order - 1] = *key;
}
break;
}
}
}
return value.prob;
}
} // namespace

View File

@ -0,0 +1,74 @@
#ifndef LM_COMMON_MODEL_BUFFER_H
#define LM_COMMON_MODEL_BUFFER_H
/* Format with separate files in suffix order. Each file contains
* n-grams of the same order.
*/
#include "lm/word_index.hh"
#include "util/file.hh"
#include "util/fixed_array.hh"
#include "util/string_piece.hh"
#include <string>
#include <vector>
namespace util { namespace stream {
class Chains;
class Chain;
}} // namespaces
namespace lm {
namespace ngram { class State; }
class ModelBuffer {
public:
// Construct for writing. Must call VocabFile() and fill it with null-delimited vocab words.
ModelBuffer(StringPiece file_base, bool keep_buffer, bool output_q);
// Load from file.
explicit ModelBuffer(StringPiece file_base);
// Must call VocabFile and populate before calling this function.
void Sink(util::stream::Chains &chains, const std::vector<uint64_t> &counts);
// Read files and write to the given chains. If fewer chains are provided,
// only do the lower orders.
void Source(util::stream::Chains &chains);
void Source(std::size_t order_minus_1, util::stream::Chain &chain);
// The order of the n-gram model that is associated with the model buffer.
std::size_t Order() const { return counts_.size(); }
// Requires Sink or load from file.
const std::vector<uint64_t> &Counts() const {
assert(!counts_.empty());
return counts_;
}
int VocabFile() const { return vocab_file_.get(); }
int RawFile(std::size_t order_minus_1) const {
return files_[order_minus_1].get();
}
bool Keep() const { return keep_buffer_; }
// Slowly execute a language model query with binary search.
// This is used by interpolation to gather tuning probabilities rather than
// scanning the files.
float SlowQuery(const ngram::State &context, WordIndex word, ngram::State &out) const;
private:
const std::string file_base_;
const bool keep_buffer_;
bool output_q_;
std::vector<uint64_t> counts_;
util::scoped_fd vocab_file_;
util::FixedArray<util::scoped_fd> files_;
};
} // namespace lm
#endif // LM_COMMON_MODEL_BUFFER_H

View File

@ -0,0 +1,44 @@
#include "lm/common/model_buffer.hh"
#include "lm/model.hh"
#include "lm/state.hh"
#define BOOST_TEST_MODULE ModelBufferTest
#include <boost/test/unit_test.hpp>
namespace lm { namespace {
BOOST_AUTO_TEST_CASE(Query) {
std::string dir("test_data/");
if (boost::unit_test::framework::master_test_suite().argc == 2) {
dir = boost::unit_test::framework::master_test_suite().argv[1];
}
ngram::Model ref((dir + "/toy0.arpa").c_str());
ModelBuffer test(dir + "/toy0");
ngram::State ref_state, test_state;
WordIndex a = ref.GetVocabulary().Index("a");
BOOST_CHECK_CLOSE(
ref.FullScore(ref.BeginSentenceState(), a, ref_state).prob,
test.SlowQuery(ref.BeginSentenceState(), a, test_state),
0.001);
BOOST_CHECK_EQUAL((unsigned)ref_state.length, (unsigned)test_state.length);
BOOST_CHECK_EQUAL(ref_state.words[0], test_state.words[0]);
BOOST_CHECK_EQUAL(ref_state.backoff[0], test_state.backoff[0]);
BOOST_CHECK(ref_state == test_state);
ngram::State ref_state2, test_state2;
WordIndex b = ref.GetVocabulary().Index("b");
BOOST_CHECK_CLOSE(
ref.FullScore(ref_state, b, ref_state2).prob,
test.SlowQuery(test_state, b, test_state2),
0.001);
BOOST_CHECK(ref_state2 == test_state2);
BOOST_CHECK_EQUAL(ref_state2.backoff[0], test_state2.backoff[0]);
BOOST_CHECK_CLOSE(
ref.FullScore(ref_state2, 0, ref_state).prob,
test.SlowQuery(test_state2, 0, test_state),
0.001);
// The reference does state minimization but this doesn't.
}
}} // namespaces

View File

@ -0,0 +1,77 @@
#ifndef LM_COMMON_NGRAM_H
#define LM_COMMON_NGRAM_H
#include "lm/weights.hh"
#include "lm/word_index.hh"
#include <cstddef>
#include <cassert>
#include <stdint.h>
#include <cstring>
namespace lm {
class NGramHeader {
public:
NGramHeader(void *begin, std::size_t order)
: begin_(static_cast<WordIndex*>(begin)), end_(begin_ + order) {}
NGramHeader() : begin_(NULL), end_(NULL) {}
const uint8_t *Base() const { return reinterpret_cast<const uint8_t*>(begin_); }
uint8_t *Base() { return reinterpret_cast<uint8_t*>(begin_); }
void ReBase(void *to) {
std::size_t difference = end_ - begin_;
begin_ = reinterpret_cast<WordIndex*>(to);
end_ = begin_ + difference;
}
// These are for the vocab index.
// Lower-case in deference to STL.
const WordIndex *begin() const { return begin_; }
WordIndex *begin() { return begin_; }
const WordIndex *end() const { return end_; }
WordIndex *end() { return end_; }
std::size_t size() const { return end_ - begin_; }
std::size_t Order() const { return end_ - begin_; }
private:
WordIndex *begin_, *end_;
};
template <class PayloadT> class NGram : public NGramHeader {
public:
typedef PayloadT Payload;
NGram() : NGramHeader(NULL, 0) {}
NGram(void *begin, std::size_t order) : NGramHeader(begin, order) {}
// Would do operator++ but that can get confusing for a stream.
void NextInMemory() {
ReBase(&Value() + 1);
}
static std::size_t TotalSize(std::size_t order) {
return order * sizeof(WordIndex) + sizeof(Payload);
}
std::size_t TotalSize() const {
// Compiler should optimize this.
return TotalSize(Order());
}
static std::size_t OrderFromSize(std::size_t size) {
std::size_t ret = (size - sizeof(Payload)) / sizeof(WordIndex);
assert(size == TotalSize(ret));
return ret;
}
const Payload &Value() const { return *reinterpret_cast<const Payload *>(end()); }
Payload &Value() { return *reinterpret_cast<Payload *>(end()); }
};
} // namespace lm
#endif // LM_COMMON_NGRAM_H

View File

@ -0,0 +1,65 @@
#ifndef LM_BUILDER_NGRAM_STREAM_H
#define LM_BUILDER_NGRAM_STREAM_H
#include "lm/common/ngram.hh"
#include "util/stream/chain.hh"
#include "util/stream/multi_stream.hh"
#include "util/stream/stream.hh"
#include <cstddef>
namespace lm {
template <class Proxy> class ProxyStream {
public:
// Make an invalid stream.
ProxyStream() {}
explicit ProxyStream(const util::stream::ChainPosition &position, const Proxy &proxy = Proxy())
: proxy_(proxy), stream_(position) {
proxy_.ReBase(stream_.Get());
}
Proxy &operator*() { return proxy_; }
const Proxy &operator*() const { return proxy_; }
Proxy *operator->() { return &proxy_; }
const Proxy *operator->() const { return &proxy_; }
void *Get() { return stream_.Get(); }
const void *Get() const { return stream_.Get(); }
operator bool() const { return stream_; }
bool operator!() const { return !stream_; }
void Poison() { stream_.Poison(); }
ProxyStream<Proxy> &operator++() {
++stream_;
proxy_.ReBase(stream_.Get());
return *this;
}
private:
Proxy proxy_;
util::stream::Stream stream_;
};
template <class Payload> class NGramStream : public ProxyStream<NGram<Payload> > {
public:
// Make an invalid stream.
NGramStream() {}
explicit NGramStream(const util::stream::ChainPosition &position) :
ProxyStream<NGram<Payload> >(position, NGram<Payload>(NULL, NGram<Payload>::OrderFromSize(position.GetChain().EntrySize()))) {}
};
template <class Payload> class NGramStreams : public util::stream::GenericStreams<NGramStream<Payload> > {
private:
typedef util::stream::GenericStreams<NGramStream<Payload> > P;
public:
NGramStreams() : P() {}
NGramStreams(const util::stream::ChainPositions &positions) : P(positions) {}
};
} // namespace
#endif // LM_BUILDER_NGRAM_STREAM_H

View File

@ -0,0 +1,62 @@
#include "lm/common/print.hh"
#include "lm/common/ngram_stream.hh"
#include "util/file_stream.hh"
#include "util/file.hh"
#include "util/mmap.hh"
#include "util/scoped.hh"
#include <sstream>
#include <cstring>
namespace lm {
VocabReconstitute::VocabReconstitute(int fd) {
uint64_t size = util::SizeOrThrow(fd);
util::MapRead(util::POPULATE_OR_READ, fd, 0, size, memory_);
const char *const start = static_cast<const char*>(memory_.get());
const char *i;
for (i = start; i != start + size; i += strlen(i) + 1) {
map_.push_back(i);
}
// Last one for LookupPiece.
map_.push_back(i);
}
namespace {
template <class Payload> void PrintLead(const VocabReconstitute &vocab, ProxyStream<Payload> &stream, util::FileStream &out) {
out << stream->Value().prob << '\t' << vocab.Lookup(*stream->begin());
for (const WordIndex *i = stream->begin() + 1; i != stream->end(); ++i) {
out << ' ' << vocab.Lookup(*i);
}
}
} // namespace
void PrintARPA::Run(const util::stream::ChainPositions &positions) {
VocabReconstitute vocab(vocab_fd_);
util::FileStream out(out_fd_);
out << "\\data\\\n";
for (size_t i = 0; i < positions.size(); ++i) {
out << "ngram " << (i+1) << '=' << counts_[i] << '\n';
}
out << '\n';
for (unsigned order = 1; order < positions.size(); ++order) {
out << "\\" << order << "-grams:" << '\n';
for (ProxyStream<NGram<ProbBackoff> > stream(positions[order - 1], NGram<ProbBackoff>(NULL, order)); stream; ++stream) {
PrintLead(vocab, stream, out);
out << '\t' << stream->Value().backoff << '\n';
}
out << '\n';
}
out << "\\" << positions.size() << "-grams:" << '\n';
for (ProxyStream<NGram<Prob> > stream(positions.back(), NGram<Prob>(NULL, positions.size())); stream; ++stream) {
PrintLead(vocab, stream, out);
out << '\n';
}
out << '\n';
out << "\\end\\\n";
}
} // namespace lm

View File

@ -0,0 +1,58 @@
#ifndef LM_COMMON_PRINT_H
#define LM_COMMON_PRINT_H
#include "lm/word_index.hh"
#include "util/mmap.hh"
#include "util/string_piece.hh"
#include <cassert>
#include <vector>
namespace util { namespace stream { class ChainPositions; }}
// Warning: PrintARPA routines read all unigrams before all bigrams before all
// trigrams etc. So if other parts of the chain move jointly, you'll have to
// buffer.
namespace lm {
class VocabReconstitute {
public:
// fd must be alive for life of this object; does not take ownership.
explicit VocabReconstitute(int fd);
const char *Lookup(WordIndex index) const {
assert(index < map_.size() - 1);
return map_[index];
}
StringPiece LookupPiece(WordIndex index) const {
return StringPiece(map_[index], map_[index + 1] - 1 - map_[index]);
}
std::size_t Size() const {
// There's an extra entry to support StringPiece lengths.
return map_.size() - 1;
}
private:
util::scoped_memory memory_;
std::vector<const char*> map_;
};
class PrintARPA {
public:
// Does not take ownership of vocab_fd or out_fd.
explicit PrintARPA(int vocab_fd, int out_fd, const std::vector<uint64_t> &counts)
: vocab_fd_(vocab_fd), out_fd_(out_fd), counts_(counts) {}
void Run(const util::stream::ChainPositions &positions);
private:
int vocab_fd_;
int out_fd_;
std::vector<uint64_t> counts_;
};
} // namespace lm
#endif // LM_COMMON_PRINT_H

View File

@ -0,0 +1,17 @@
#include "lm/common/renumber.hh"
#include "lm/common/ngram.hh"
#include "util/stream/stream.hh"
namespace lm {
void Renumber::Run(const util::stream::ChainPosition &position) {
for (util::stream::Stream stream(position); stream; ++stream) {
NGramHeader gram(stream.Get(), order_);
for (WordIndex *w = gram.begin(); w != gram.end(); ++w) {
*w = new_numbers_[*w];
}
}
}
} // namespace lm

View File

@ -0,0 +1,30 @@
/* Map vocab ids. This is useful to merge independently collected counts or
* change the vocab ids to the order used by the trie.
*/
#ifndef LM_COMMON_RENUMBER_H
#define LM_COMMON_RENUMBER_H
#include "lm/word_index.hh"
#include <cstddef>
namespace util { namespace stream { class ChainPosition; }}
namespace lm {
class Renumber {
public:
// Assumes the array is large enough to map all words and stays alive while
// the thread is active.
Renumber(const WordIndex *new_numbers, std::size_t order)
: new_numbers_(new_numbers), order_(order) {}
void Run(const util::stream::ChainPosition &position);
private:
const WordIndex *new_numbers_;
std::size_t order_;
};
} // namespace lm
#endif // LM_COMMON_RENUMBER_H

View File

@ -0,0 +1,24 @@
#include <boost/program_options.hpp>
#include "util/usage.hh"
namespace lm {
namespace {
class SizeNotify {
public:
explicit SizeNotify(std::size_t &out) : behind_(out) {}
void operator()(const std::string &from) {
behind_ = util::ParseSize(from);
}
private:
std::size_t &behind_;
};
}
boost::program_options::typed_value<std::string> *SizeOption(std::size_t &to, const char *default_value) {
return boost::program_options::value<std::string>()->notifier(SizeNotify(to))->default_value(default_value);
}
} // namespace lm

View File

@ -0,0 +1,11 @@
#include <boost/program_options.hpp>
#include <cstddef>
#include <string>
namespace lm {
// Create a boost program option for data sizes. This parses sizes like 1T and 10k.
boost::program_options::typed_value<std::string> *SizeOption(std::size_t &to, const char *default_value);
} // namespace lm

View File

@ -0,0 +1,27 @@
#ifndef LM_COMMON_SPECIAL_H
#define LM_COMMON_SPECIAL_H
#include "lm/word_index.hh"
namespace lm {
class SpecialVocab {
public:
SpecialVocab(WordIndex bos, WordIndex eos) : bos_(bos), eos_(eos) {}
bool IsSpecial(WordIndex word) const {
return word == kUNK || word == bos_ || word == eos_;
}
WordIndex UNK() const { return kUNK; }
WordIndex BOS() const { return bos_; }
WordIndex EOS() const { return eos_; }
private:
WordIndex bos_;
WordIndex eos_;
};
} // namespace lm
#endif // LM_COMMON_SPECIAL_H

View File

@ -0,0 +1,9 @@
#!/bin/bash
../../../bin/lmplz --discount_fallback -o 3 -S 100M --intermediate toy0 --arpa toy0.arpa <<EOF
a a b a
b a a b
EOF
../../../bin/lmplz --discount_fallback -o 3 -S 100M --intermediate toy1 --arpa toy1.arpa <<EOF
a a b b b b b b b
c
EOF

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,31 @@
\data\
ngram 1=5
ngram 2=7
ngram 3=7
\1-grams:
-0.90309 <unk> 0
0 <s> -0.30103
-0.46943438 a -0.30103
-0.5720968 </s> 0
-0.5720968 b -0.30103
\2-grams:
-0.37712017 <s> a -0.30103
-0.37712017 a a -0.30103
-0.2984526 b a -0.30103
-0.58682007 a </s> 0
-0.52201796 b </s> 0
-0.41574955 <s> b -0.30103
-0.58682007 a b -0.30103
\3-grams:
-0.14885087 <s> a a
-0.33741078 b a a
-0.124077894 <s> b a
-0.2997394 a b a
-0.42082912 b a </s>
-0.397617 a b </s>
-0.20102891 a a b
\end\

View File

@ -0,0 +1,3 @@
KenLM intermediate binary file
Counts 5 7 7
Payload pb

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,31 @@
\data\
ngram 1=6
ngram 2=7
ngram 3=6
\1-grams:
-1 <unk> 0
0 <s> -0.30103
-0.6146491 a -0.30103
-0.6146491 </s> 0
-0.7659168 c -0.30103
-0.6146491 b -0.30103
\2-grams:
-0.4301247 <s> a -0.30103
-0.4301247 a a -0.30103
-0.20660876 c </s> 0
-0.5404639 b </s> 0
-0.4740302 <s> c -0.30103
-0.4301247 a b -0.30103
-0.3422159 b b -0.47712123
\3-grams:
-0.1638568 <s> a a
-0.09113217 <s> c </s>
-0.7462621 b b </s>
-0.1638568 a a b
-0.13823806 a b b
-0.13375957 b b b
\end\

View File

@ -0,0 +1,3 @@
KenLM intermediate binary file
Counts 6 7 6
Payload pb

Binary file not shown.

View File

@ -0,0 +1,30 @@
#include "lm/config.hh"
#include <iostream>
namespace lm {
namespace ngram {
Config::Config() :
show_progress(true),
messages(&std::cerr),
enumerate_vocab(NULL),
unknown_missing(COMPLAIN),
sentence_marker_missing(THROW_UP),
positive_log_probability(THROW_UP),
unknown_missing_logprob(-100.0),
probing_multiplier(1.5),
building_memory(1073741824ULL), // 1 GB
temporary_directory_prefix(""),
arpa_complain(ALL),
write_mmap(NULL),
write_method(WRITE_AFTER),
include_vocab(true),
rest_function(REST_MAX),
prob_bits(8),
backoff_bits(8),
pointer_bhiksha_bits(22),
load_method(util::POPULATE_OR_READ) {}
} // namespace ngram
} // namespace lm

View File

@ -0,0 +1,124 @@
#ifndef LM_CONFIG_H
#define LM_CONFIG_H
#include "lm/lm_exception.hh"
#include "util/mmap.hh"
#include <iosfwd>
#include <string>
#include <vector>
/* Configuration for ngram model. Separate header to reduce pollution. */
namespace lm {
class EnumerateVocab;
namespace ngram {
struct Config {
// EFFECTIVE FOR BOTH ARPA AND BINARY READS
// (default true) print progress bar to messages
bool show_progress;
// Where to log messages including the progress bar. Set to NULL for
// silence.
std::ostream *messages;
std::ostream *ProgressMessages() const {
return show_progress ? messages : 0;
}
// This will be called with every string in the vocabulary by the
// constructor; it need only exist for the lifetime of the constructor.
// See enumerate_vocab.hh for more detail. Config does not take ownership;
// just delete/let it go out of scope after the constructor exits.
EnumerateVocab *enumerate_vocab;
// ONLY EFFECTIVE WHEN READING ARPA
// What to do when <unk> isn't in the provided model.
WarningAction unknown_missing;
// What to do when <s> or </s> is missing from the model.
// If THROW_UP, the exception will be of type util::SpecialWordMissingException.
WarningAction sentence_marker_missing;
// What to do with a positive log probability. For COMPLAIN and SILENT, map
// to 0.
WarningAction positive_log_probability;
// The probability to substitute for <unk> if it's missing from the model.
// No effect if the model has <unk> or unknown_missing == THROW_UP.
float unknown_missing_logprob;
// Size multiplier for probing hash table. Must be > 1. Space is linear in
// this. Time is probing_multiplier / (probing_multiplier - 1). No effect
// for sorted variant.
// If you find yourself setting this to a low number, consider using the
// TrieModel which has lower memory consumption.
float probing_multiplier;
// Amount of memory to use for building. The actual memory usage will be
// higher since this just sets sort buffer size. Only applies to trie
// models.
std::size_t building_memory;
// Template for temporary directory appropriate for passing to mkdtemp.
// The characters XXXXXX are appended before passing to mkdtemp. Only
// applies to trie. If empty, defaults to write_mmap. If that's NULL,
// defaults to input file name.
std::string temporary_directory_prefix;
// Level of complaining to do when loading from ARPA instead of binary format.
enum ARPALoadComplain {ALL, EXPENSIVE, NONE};
ARPALoadComplain arpa_complain;
// While loading an ARPA file, also write out this binary format file. Set
// to NULL to disable.
const char *write_mmap;
enum WriteMethod {
WRITE_MMAP, // Map the file directly.
WRITE_AFTER // Write after we're done.
};
WriteMethod write_method;
// Include the vocab in the binary file? Only effective if write_mmap != NULL.
bool include_vocab;
// Left rest options. Only used when the model includes rest costs.
enum RestFunction {
REST_MAX, // Maximum of any score to the left
REST_LOWER, // Use lower-order files given below.
};
RestFunction rest_function;
// Only used for REST_LOWER.
std::vector<std::string> rest_lower_files;
// Quantization options. Only effective for QuantTrieModel. One value is
// reserved for each of prob and backoff, so 2^bits - 1 buckets will be used
// to quantize (and one of the remaining backoffs will be 0).
uint8_t prob_bits, backoff_bits;
// Bhiksha compression (simple form). Only works with trie.
uint8_t pointer_bhiksha_bits;
// ONLY EFFECTIVE WHEN READING BINARY
// How to get the giant array into memory: lazy mmap, populate, read etc.
// See util/mmap.hh for details of MapMethod.
util::LoadMethod load_method;
// Set defaults.
Config();
};
} /* namespace ngram */ } /* namespace lm */
#endif // LM_CONFIG_H

View File

@ -0,0 +1,28 @@
#ifndef LM_ENUMERATE_VOCAB_H
#define LM_ENUMERATE_VOCAB_H
#include "lm/word_index.hh"
#include "util/string_piece.hh"
namespace lm {
/* If you need the actual strings in the vocabulary, inherit from this class
* and implement Add. Then put a pointer in Config.enumerate_vocab; it does
* not take ownership. Add is called once per vocab word. index starts at 0
* and increases by 1 each time. This is only used by the Model constructor;
* the pointer is not retained by the class.
*/
class EnumerateVocab {
public:
virtual ~EnumerateVocab() {}
virtual void Add(WordIndex index, const StringPiece &str) = 0;
protected:
EnumerateVocab() {}
};
} // namespace lm
#endif // LM_ENUMERATE_VOCAB_H

View File

@ -0,0 +1,73 @@
#ifndef LM_FACADE_H
#define LM_FACADE_H
#include "lm/virtual_interface.hh"
#include "util/string_piece.hh"
#include <string>
namespace lm {
namespace base {
// Common model interface that depends on knowing the specific classes.
// Curiously recurring template pattern.
template <class Child, class StateT, class VocabularyT> class ModelFacade : public Model {
public:
typedef StateT State;
typedef VocabularyT Vocabulary;
/* Translate from void* to State */
FullScoreReturn BaseFullScore(const void *in_state, const WordIndex new_word, void *out_state) const {
return static_cast<const Child*>(this)->FullScore(
*reinterpret_cast<const State*>(in_state),
new_word,
*reinterpret_cast<State*>(out_state));
}
FullScoreReturn BaseFullScoreForgotState(const WordIndex *context_rbegin, const WordIndex *context_rend, const WordIndex new_word, void *out_state) const {
return static_cast<const Child*>(this)->FullScoreForgotState(
context_rbegin,
context_rend,
new_word,
*reinterpret_cast<State*>(out_state));
}
// Default Score function calls FullScore. Model can override this.
float Score(const State &in_state, const WordIndex new_word, State &out_state) const {
return static_cast<const Child*>(this)->FullScore(in_state, new_word, out_state).prob;
}
float BaseScore(const void *in_state, const WordIndex new_word, void *out_state) const {
return static_cast<const Child*>(this)->Score(
*reinterpret_cast<const State*>(in_state),
new_word,
*reinterpret_cast<State*>(out_state));
}
const State &BeginSentenceState() const { return begin_sentence_; }
const State &NullContextState() const { return null_context_; }
const Vocabulary &GetVocabulary() const { return *static_cast<const Vocabulary*>(&BaseVocabulary()); }
protected:
ModelFacade() : Model(sizeof(State)) {}
virtual ~ModelFacade() {}
// begin_sentence and null_context can disappear after. vocab should stay.
void Init(const State &begin_sentence, const State &null_context, const Vocabulary &vocab, unsigned char order) {
begin_sentence_ = begin_sentence;
null_context_ = null_context;
begin_sentence_memory_ = &begin_sentence_;
null_context_memory_ = &null_context_;
base_vocab_ = &vocab;
order_ = order;
}
private:
State begin_sentence_, null_context_;
};
} // mamespace base
} // namespace lm
#endif // LM_FACADE_H

View File

@ -0,0 +1,37 @@
#include "lm/binary_format.hh"
#include "lm/model.hh"
#include "lm/left.hh"
#include "util/tokenize_piece.hh"
template <class Model> void Query(const char *name) {
Model model(name);
std::string line;
lm::ngram::ChartState ignored;
while (getline(std::cin, line)) {
lm::ngram::RuleScore<Model> scorer(model, ignored);
for (util::TokenIter<util::SingleCharacter, true> i(line, ' '); i; ++i) {
scorer.Terminal(model.GetVocabulary().Index(*i));
}
std::cout << scorer.Finish() << '\n';
}
}
int main(int argc, char *argv[]) {
if (argc != 2) {
std::cerr << "Expected model file name." << std::endl;
return 1;
}
const char *name = argv[1];
lm::ngram::ModelType model_type = lm::ngram::PROBING;
lm::ngram::RecognizeBinary(name, model_type);
switch (model_type) {
case lm::ngram::PROBING:
Query<lm::ngram::ProbingModel>(name);
break;
case lm::ngram::REST_PROBING:
Query<lm::ngram::RestProbingModel>(name);
break;
default:
std::cerr << "Model type not supported yet." << std::endl;
}
}

View File

@ -0,0 +1,70 @@
find_package(Eigen3)
if(EIGEN3_FOUND)
if (3.1.0 VERSION_LESS ${EIGEN3_VERSION})
include_directories(${EIGEN3_INCLUDE_DIR})
set(KENLM_INTERPOLATE_SOURCE
backoff_reunification.cc
bounded_sequence_encoding.cc
merge_probabilities.cc
merge_vocab.cc
normalize.cc
pipeline.cc
split_worker.cc
tune_derivatives.cc
tune_instances.cc
tune_weights.cc
universal_vocab.cc)
find_package(OpenMP)
if (OPENMP_FOUND)
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
else()
message(STATUS "OpenMP support would be nice for parallelizing matrix operations.")
endif()
add_library(kenlm_interpolate ${KENLM_INTERPOLATE_SOURCE})
set(KENLM_INTERPOLATE_EXES
interpolate
streaming_example)
if (NOT MSVC)
set(THREADS pthread)
endif()
set(KENLM_INTERPOLATE_LIBS
kenlm_interpolate kenlm kenlm_util ${Boost_LIBRARIES} ${THREADS})
AddExes(EXES ${KENLM_INTERPOLATE_EXES}
LIBRARIES ${KENLM_INTERPOLATE_LIBS})
if(BUILD_TESTING)
AddTests(TESTS backoff_reunification_test bounded_sequence_encoding_test normalize_test tune_derivatives_test
LIBRARIES ${KENLM_INTERPOLATE_LIBS} pthread)
# tune_instances_test needs an extra command line parameter
KenLMAddTest(TEST tune_instances_test
LIBRARIES ${KENLM_INTERPOLATE_LIBS}
TEST_ARGS -- ${CMAKE_CURRENT_SOURCE_DIR}/../common/test_data/toy0.1)
foreach(test_file test1 test2 test3 test_bad_order test_no_unk)
set(KENLM_MERGE_TESTS_PATH ${KENLM_MERGE_TESTS_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/merge_test/${test_file})
endforeach(test_file)
KenLMAddTest(TEST merge_vocab_test
LIBRARIES ${KENLM_INTERPOLATE_LIBS}
TEST_ARGS ${KENLM_MERGE_TESTS_PATH})
endif()
else()
message(WARNING "Not building interpolation. You have an old version of Eigen3, ${EIGEN3_VERSION}, which has a race condition: http://eigen.tuxfamily.org/bz/show_bug.cgi?id=466. Please install Eigen 3.1.0 or above.")
endif()
else()
message(WARNING "Not building interpolation. Eigen3 was not found.")
message(STATUS "To install Eigen3 in your home directory, copy paste this:\n"
"export EIGEN3_ROOT=$HOME/eigen-eigen-07105f7124f9\n"
"(cd $HOME; wget -O - https://bitbucket.org/eigen/eigen/get/3.2.8.tar.bz2 |tar xj)\n"
"rm CMakeCache.txt\n")
endif()

View File

@ -0,0 +1,29 @@
#ifndef LM_INTERPOLATE_BACKOFF_MATRIX_H
#define LM_INTERPOLATE_BACKOFF_MATRIX_H
#include <cstddef>
#include <vector>
namespace lm { namespace interpolate {
class BackoffMatrix {
public:
BackoffMatrix(std::size_t num_models, std::size_t max_order)
: max_order_(max_order), backing_(num_models * max_order) {}
float &Backoff(std::size_t model, std::size_t order_minus_1) {
return backing_[model * max_order_ + order_minus_1];
}
float Backoff(std::size_t model, std::size_t order_minus_1) const {
return backing_[model * max_order_ + order_minus_1];
}
private:
const std::size_t max_order_;
std::vector<float> backing_;
};
}} // namespaces
#endif // LM_INTERPOLATE_BACKOFF_MATRIX_H

View File

@ -0,0 +1,58 @@
#include "lm/interpolate/backoff_reunification.hh"
#include "lm/common/model_buffer.hh"
#include "lm/common/ngram_stream.hh"
#include "lm/common/ngram.hh"
#include "lm/common/compare.hh"
#include <algorithm>
#include <cassert>
namespace lm {
namespace interpolate {
namespace {
class MergeWorker {
public:
MergeWorker(std::size_t order, const util::stream::ChainPosition &prob_pos,
const util::stream::ChainPosition &boff_pos)
: order_(order), prob_pos_(prob_pos), boff_pos_(boff_pos) {
// nothing
}
void Run(const util::stream::ChainPosition &position) {
lm::NGramStream<ProbBackoff> stream(position);
lm::NGramStream<float> prob_input(prob_pos_);
util::stream::Stream boff_input(boff_pos_);
for (; prob_input && boff_input; ++prob_input, ++boff_input, ++stream) {
std::copy(prob_input->begin(), prob_input->end(), stream->begin());
stream->Value().prob = std::min(0.0f, prob_input->Value());
stream->Value().backoff = *reinterpret_cast<float *>(boff_input.Get());
}
UTIL_THROW_IF2(prob_input || boff_input,
"Streams were not the same size during merging");
stream.Poison();
}
private:
std::size_t order_;
util::stream::ChainPosition prob_pos_;
util::stream::ChainPosition boff_pos_;
};
}
// Since we are *adding* something to the output chain here, we pass in the
// chain itself so that we can safely add a new step to the chain without
// creating a deadlock situation (since creating a new ChainPosition will
// make a new input/output pair---we want that position to be created
// *here*, not before).
void ReunifyBackoff(util::stream::ChainPositions &prob_pos,
util::stream::ChainPositions &boff_pos,
util::stream::Chains &output_chains) {
assert(prob_pos.size() == boff_pos.size());
for (size_t i = 0; i < prob_pos.size(); ++i)
output_chains[i] >> MergeWorker(i + 1, prob_pos[i], boff_pos[i]);
}
}
}

View File

@ -0,0 +1,27 @@
#ifndef KENLM_INTERPOLATE_BACKOFF_REUNIFICATION_
#define KENLM_INTERPOLATE_BACKOFF_REUNIFICATION_
#include "util/stream/stream.hh"
#include "util/stream/multi_stream.hh"
namespace lm {
namespace interpolate {
/**
* The third pass for the offline log-linear interpolation algorithm. This
* reads **suffix-ordered** probability values (ngram-id, float) and
* **suffix-ordered** backoff values (float) and writes the merged contents
* to the output.
*
* @param prob_pos The chain position for each order from which to read
* the probability values
* @param boff_pos The chain position for each order from which to read
* the backoff values
* @param output_chains The output chains for each order
*/
void ReunifyBackoff(util::stream::ChainPositions &prob_pos,
util::stream::ChainPositions &boff_pos,
util::stream::Chains &output_chains);
}
}
#endif

View File

@ -0,0 +1,158 @@
#include "lm/interpolate/backoff_reunification.hh"
#include "lm/common/ngram_stream.hh"
#define BOOST_TEST_MODULE InterpolateBackoffReunificationTest
#include <boost/test/unit_test.hpp>
namespace lm {
namespace interpolate {
namespace {
// none of this input actually makes sense, all we care about is making
// sure the merging works
template <uint8_t N>
struct Gram {
WordIndex ids[N];
float prob;
float boff;
};
template <uint8_t N>
struct Grams {
const static Gram<N> grams[];
};
template <>
const Gram<1> Grams<1>::grams[]
= {{{0}, -0.1f, -0.1f}, {{1}, -0.4f, -0.2f}, {{2}, -0.5f, -0.1f}};
template <>
const Gram<2> Grams<2>::grams[] = {{{0, 0}, -0.05f, -0.05f},
{{1, 0}, -0.05f, -0.02f},
{{1, 1}, -0.2f, -0.04f},
{{2, 2}, -0.2f, -0.01f}};
template <>
const Gram<3> Grams<3>::grams[] = {{{0, 0, 0}, -0.001f, -0.005f},
{{1, 0, 0}, -0.001f, -0.002f},
{{2, 0, 0}, -0.001f, -0.003f},
{{0, 1, 0}, -0.1f, -0.008f},
{{1, 1, 0}, -0.1f, -0.09f},
{{1, 1, 1}, -0.2f, -0.08f}};
template <uint8_t N>
class WriteInput {
public:
void Run(const util::stream::ChainPosition &position) {
lm::NGramStream<float> output(position);
for (std::size_t i = 0; i < sizeof(Grams<N>::grams) / sizeof(Gram<N>);
++i, ++output) {
std::copy(Grams<N>::grams[i].ids, Grams<N>::grams[i].ids + N,
output->begin());
output->Value() = Grams<N>::grams[i].prob;
}
output.Poison();
}
};
template <uint8_t N>
class WriteBackoffs {
public:
void Run(const util::stream::ChainPosition &position) {
util::stream::Stream output(position);
for (std::size_t i = 0; i < sizeof(Grams<N>::grams) / sizeof(Gram<N>);
++i, ++output) {
*reinterpret_cast<float *>(output.Get()) = Grams<N>::grams[i].boff;
}
output.Poison();
}
};
template <uint8_t N>
class CheckOutput {
public:
void Run(const util::stream::ChainPosition &position) {
lm::NGramStream<ProbBackoff> stream(position);
std::size_t i = 0;
for (; stream; ++stream, ++i) {
std::stringstream ss;
for (WordIndex *idx = stream->begin(); idx != stream->end(); ++idx)
ss << "(" << *idx << ")";
BOOST_CHECK(std::equal(stream->begin(), stream->end(), Grams<N>::grams[i].ids));
//"Mismatched id in CheckOutput<" << (int)N << ">: " << ss.str();
BOOST_CHECK_EQUAL(stream->Value().prob, Grams<N>::grams[i].prob);
/* "Mismatched probability in CheckOutput<"
<< (int)N << ">, got " << stream->Value().prob
<< ", expected " << Grams<N>::grams[i].prob;*/
BOOST_CHECK_EQUAL(stream->Value().backoff, Grams<N>::grams[i].boff);
/* "Mismatched backoff in CheckOutput<"
<< (int)N << ">, got " << stream->Value().backoff
<< ", expected " << Grams<N>::grams[i].boff);*/
}
BOOST_CHECK_EQUAL(i , sizeof(Grams<N>::grams) / sizeof(Gram<N>));
/* "Did not get correct number of "
<< (int)N << "-grams: expected "
<< sizeof(Grams<N>::grams) / sizeof(Gram<N>)
<< ", got " << i;*/
}
};
}
BOOST_AUTO_TEST_CASE(BackoffReunificationTest) {
util::stream::ChainConfig config;
config.total_memory = 100;
config.block_count = 1;
util::stream::Chains prob_chains(3);
config.entry_size = NGram<float>::TotalSize(1);
prob_chains.push_back(config);
prob_chains.back() >> WriteInput<1>();
config.entry_size = NGram<float>::TotalSize(2);
prob_chains.push_back(config);
prob_chains.back() >> WriteInput<2>();
config.entry_size = NGram<float>::TotalSize(3);
prob_chains.push_back(config);
prob_chains.back() >> WriteInput<3>();
util::stream::Chains boff_chains(3);
config.entry_size = sizeof(float);
boff_chains.push_back(config);
boff_chains.back() >> WriteBackoffs<1>();
boff_chains.push_back(config);
boff_chains.back() >> WriteBackoffs<2>();
boff_chains.push_back(config);
boff_chains.back() >> WriteBackoffs<3>();
util::stream::ChainPositions prob_pos(prob_chains);
util::stream::ChainPositions boff_pos(boff_chains);
util::stream::Chains output_chains(3);
for (std::size_t i = 0; i < 3; ++i) {
config.entry_size = NGram<ProbBackoff>::TotalSize(i + 1);
output_chains.push_back(config);
}
ReunifyBackoff(prob_pos, boff_pos, output_chains);
output_chains[0] >> CheckOutput<1>();
output_chains[1] >> CheckOutput<2>();
output_chains[2] >> CheckOutput<3>();
prob_chains >> util::stream::kRecycle;
boff_chains >> util::stream::kRecycle;
output_chains.Wait();
}
}
}

View File

@ -0,0 +1,36 @@
#include "lm/interpolate/bounded_sequence_encoding.hh"
#include <algorithm>
namespace lm { namespace interpolate {
BoundedSequenceEncoding::BoundedSequenceEncoding(const unsigned char *bound_begin, const unsigned char *bound_end)
: entries_(bound_end - bound_begin) {
std::size_t full = 0;
Entry entry;
entry.shift = 0;
for (const unsigned char *i = bound_begin; i != bound_end; ++i) {
uint8_t length;
if (*i <= 1) {
length = 0;
} else {
length = sizeof(unsigned int) * 8 - __builtin_clz((unsigned int)*i);
}
entry.mask = (1ULL << length) - 1ULL;
if (entry.shift + length > 64) {
entry.shift = 0;
entry.next = true;
++full;
} else {
entry.next = false;
}
entries_.push_back(entry);
entry.shift += length;
}
byte_length_ = full * sizeof(uint64_t) + (entry.shift + 7) / 8;
first_copy_ = std::min<std::size_t>(byte_length_, sizeof(uint64_t));
// Size of last uint64_t. Zero if empty, otherwise [1,8] depending on mod.
overhang_ = byte_length_ == 0 ? 0 : ((byte_length_ - 1) % 8 + 1);
}
}} // namespaces

View File

@ -0,0 +1,76 @@
#ifndef LM_INTERPOLATE_BOUNDED_SEQUENCE_ENCODING_H
#define LM_INTERPOLATE_BOUNDED_SEQUENCE_ENCODING_H
/* Encodes fixed-length sequences of integers with known bounds on each entry.
* This is used to encode how far each model has backed off.
* TODO: make this class efficient. Bit-level packing or multiply by bound and
* add.
*/
#include "util/exception.hh"
#include "util/fixed_array.hh"
#if BYTE_ORDER != LITTLE_ENDIAN
#warning The interpolation code assumes little endian for now.
#endif
#include <algorithm>
#include <cstring>
namespace lm {
namespace interpolate {
class BoundedSequenceEncoding {
public:
// Encode [0, bound_begin[0]) x [0, bound_begin[1]) x [0, bound_begin[2]) x ... x [0, *(bound_end - 1)) for entries in the sequence
BoundedSequenceEncoding(const unsigned char *bound_begin, const unsigned char *bound_end);
std::size_t Entries() const { return entries_.size(); }
std::size_t EncodedLength() const { return byte_length_; }
void Encode(const unsigned char *from, void *to_void) const {
uint8_t *to = static_cast<uint8_t*>(to_void);
uint64_t cur = 0;
for (const Entry *i = entries_.begin(); i != entries_.end(); ++i, ++from) {
if (UTIL_UNLIKELY(i->next)) {
std::memcpy(to, &cur, sizeof(uint64_t));
to += sizeof(uint64_t);
cur = 0;
}
cur |= static_cast<uint64_t>(*from) << i->shift;
}
memcpy(to, &cur, overhang_);
}
void Decode(const void *from_void, unsigned char *to) const {
const uint8_t *from = static_cast<const uint8_t*>(from_void);
uint64_t cur = 0;
memcpy(&cur, from, first_copy_);
for (const Entry *i = entries_.begin(); i != entries_.end(); ++i, ++to) {
if (UTIL_UNLIKELY(i->next)) {
from += sizeof(uint64_t);
cur = 0;
std::memcpy(&cur, from,
std::min<std::size_t>(sizeof(uint64_t), static_cast<const uint8_t*>(from_void) + byte_length_ - from));
}
*to = (cur >> i->shift) & i->mask;
}
}
private:
struct Entry {
bool next;
uint8_t shift;
uint64_t mask;
};
util::FixedArray<Entry> entries_;
std::size_t byte_length_;
std::size_t first_copy_;
std::size_t overhang_;
};
}} // namespaces
#endif // LM_INTERPOLATE_BOUNDED_SEQUENCE_ENCODING_H

View File

@ -0,0 +1,86 @@
#include "lm/interpolate/bounded_sequence_encoding.hh"
#include "util/scoped.hh"
#define BOOST_TEST_MODULE BoundedSequenceEncodingTest
#include <boost/test/unit_test.hpp>
namespace lm {
namespace interpolate {
namespace {
void ExhaustiveTest(unsigned char *bound_begin, unsigned char *bound_end) {
BoundedSequenceEncoding enc(bound_begin, bound_end);
util::scoped_malloc backing(util::MallocOrThrow(enc.EncodedLength()));
std::vector<unsigned char> values(bound_end - bound_begin),
out(bound_end - bound_begin);
while (true) {
enc.Encode(&values[0], backing.get());
enc.Decode(backing.get(), &out[0]);
for (std::size_t i = 0; i != values.size(); ++i) {
BOOST_CHECK_EQUAL(values[i], out[i]);
}
for (std::size_t i = 0;; ++i) {
if (i == values.size()) return;
++values[i];
if (values[i] < bound_begin[i]) break;
values[i] = 0;
}
}
}
void CheckEncodeDecode(unsigned char *bounds, unsigned char *input,
unsigned char *output, std::size_t len) {
BoundedSequenceEncoding encoder(bounds, bounds + len);
util::scoped_malloc backing(util::MallocOrThrow(encoder.EncodedLength()));
encoder.Encode(input, backing.get());
encoder.Decode(backing.get(), output);
for (std::size_t i = 0; i < len; ++i) {
BOOST_CHECK_EQUAL(input[i], output[i]);
}
}
BOOST_AUTO_TEST_CASE(Exhaustive) {
unsigned char bounds[] = {5, 2, 3, 9, 7, 20, 8};
ExhaustiveTest(bounds, bounds + sizeof(bounds) / sizeof(unsigned char));
}
BOOST_AUTO_TEST_CASE(LessThan64) {
unsigned char bounds[] = {255, 255, 255, 255, 255, 255, 255, 3};
unsigned char input[] = {172, 183, 254, 187, 96, 87, 65, 2};
unsigned char output[] = {0, 0, 0, 0, 0, 0, 0, 0};
std::size_t len = sizeof(bounds) / sizeof(unsigned char);
assert(sizeof(input) / sizeof(unsigned char) == len);
assert(sizeof(output) / sizeof(unsigned char) == len);
CheckEncodeDecode(bounds, input, output, len);
}
BOOST_AUTO_TEST_CASE(Exactly64) {
unsigned char bounds[] = {255, 255, 255, 255, 255, 255, 255, 255};
unsigned char input[] = {172, 183, 254, 187, 96, 87, 65, 16};
unsigned char output[] = {0, 0, 0, 0, 0, 0, 0, 0};
std::size_t len = sizeof(bounds) / sizeof(unsigned char);
assert(sizeof(input) / sizeof(unsigned char) == len);
assert(sizeof(output) / sizeof(unsigned char) == len);
CheckEncodeDecode(bounds, input, output, len);
}
BOOST_AUTO_TEST_CASE(MoreThan64) {
unsigned char bounds[] = {255, 255, 255, 255, 255, 255, 255, 255, 255};
unsigned char input[] = {172, 183, 254, 187, 96, 87, 65, 16, 137};
unsigned char output[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
std::size_t len = sizeof(bounds) / sizeof(unsigned char);
assert(sizeof(input) / sizeof(unsigned char) == len);
assert(sizeof(output) / sizeof(unsigned char) == len);
CheckEncodeDecode(bounds, input, output, len);
}
}}} // namespaces

View File

@ -0,0 +1,35 @@
#ifndef KENLM_INTERPOLATE_INTERPOLATE_INFO_H
#define KENLM_INTERPOLATE_INTERPOLATE_INFO_H
#include <cstddef>
#include <vector>
#include <stdint.h>
namespace lm {
namespace interpolate {
/**
* Stores relevant info for interpolating several language models, for use
* during the three-pass offline log-linear interpolation algorithm.
*/
struct InterpolateInfo {
/**
* @return the number of models being interpolated
*/
std::size_t Models() const {
return orders.size();
}
/**
* The lambda (interpolation weight) for each model.
*/
std::vector<float> lambdas;
/**
* The maximum ngram order for each model.
*/
std::vector<uint8_t> orders;
};
}
}
#endif

View File

@ -0,0 +1,124 @@
#include "lm/common/model_buffer.hh"
#include "lm/common/size_option.hh"
#include "lm/interpolate/pipeline.hh"
#include "lm/interpolate/tune_instances.hh"
#include "lm/interpolate/tune_weights.hh"
#include "util/fixed_array.hh"
#include "util/usage.hh"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpragmas" // Older gcc doesn't have "-Wunused-local-typedefs" and complains.
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#include <Eigen/Core>
#pragma GCC diagnostic pop
#include <boost/program_options.hpp>
#include <iostream>
#include <vector>
namespace {
void MungeWeightArgs(int argc, char *argv[], std::vector<const char *> &munged_args) {
// Boost program options doesn't -w 0.2 -0.1 because it thinks -0.1 is an
// option. There appears to be no standard way to fix this without breaking
// single-dash arguments. So here's a hack: put a -w before every number
// if it's within the scope of a weight argument.
munged_args.push_back(argv[0]);
char **inside_weights = NULL;
for (char **i = argv + 1; i < argv + argc; ++i) {
StringPiece arg(*i);
if (starts_with(arg, "-w") || starts_with(arg, "--w")) {
inside_weights = i;
} else if (inside_weights && arg.size() >= 2 && arg[0] == '-' && ((arg[1] >= '0' && arg[1] <= '9') || arg[1] == '.')) {
// If a negative number appears right after -w, don't add another -w.
// And do stay inside weights.
if (inside_weights + 1 != i) {
munged_args.push_back("-w");
}
} else if (starts_with(arg, "-")) {
inside_weights = NULL;
}
munged_args.push_back(*i);
}
}
} // namespace
int main(int argc, char *argv[]) {
try {
Eigen::initParallel();
lm::interpolate::Config pipe_config;
lm::interpolate::InstancesConfig instances_config;
std::vector<std::string> input_models;
std::string tuning_file;
namespace po = boost::program_options;
po::options_description options("Log-linear interpolation options");
options.add_options()
("help,h", po::bool_switch(), "Show this help message")
("model,m", po::value<std::vector<std::string> >(&input_models)->multitoken()->required(), "Models to interpolate, which must be in KenLM intermediate format. The intermediate format can be generated using the --intermediate argument to lmplz.")
("weight,w", po::value<std::vector<float> >(&pipe_config.lambdas)->multitoken(), "Interpolation weights")
("tuning,t", po::value<std::string>(&tuning_file), "File to tune on: a text file with one sentence per line")
("just_tune", po::bool_switch(), "Tune and print weights then quit")
("temp_prefix,T", po::value<std::string>(&pipe_config.sort.temp_prefix)->default_value("/tmp/lm"), "Temporary file prefix")
("memory,S", lm::SizeOption(pipe_config.sort.total_memory, util::GuessPhysicalMemory() ? "50%" : "1G"), "Sorting memory: this is a very rough guide")
("sort_block", lm::SizeOption(pipe_config.sort.buffer_size, "64M"), "Block size");
po::variables_map vm;
std::vector<const char *> munged_args;
MungeWeightArgs(argc, argv, munged_args);
po::store(po::parse_command_line((int)munged_args.size(), &*munged_args.begin(), options), vm);
if (argc == 1 || vm["help"].as<bool>()) {
std::cerr << "Interpolate multiple models\n" << options << std::endl;
return 1;
}
po::notify(vm);
instances_config.sort = pipe_config.sort;
instances_config.model_read_chain_mem = instances_config.sort.buffer_size;
instances_config.extension_write_chain_mem = instances_config.sort.total_memory;
instances_config.lazy_memory = instances_config.sort.total_memory;
if (pipe_config.lambdas.empty() && tuning_file.empty()) {
std::cerr << "Provide a tuning file with -t xor weights with -w." << std::endl;
return 1;
}
if (!pipe_config.lambdas.empty() && !tuning_file.empty()) {
std::cerr << "Provide weights xor a tuning file, not both." << std::endl;
return 1;
}
if (!tuning_file.empty()) {
// Tune weights
std::vector<StringPiece> model_names;
for (std::vector<std::string>::const_iterator i = input_models.begin(); i != input_models.end(); ++i) {
model_names.push_back(*i);
}
lm::interpolate::TuneWeights(util::OpenReadOrThrow(tuning_file.c_str()), model_names, instances_config, pipe_config.lambdas);
std::cerr << "Final weights:";
std::ostream &to = vm["just_tune"].as<bool>() ? std::cout : std::cerr;
for (std::vector<float>::const_iterator i = pipe_config.lambdas.begin(); i != pipe_config.lambdas.end(); ++i) {
to << ' ' << *i;
}
to << std::endl;
}
if (vm["just_tune"].as<bool>()) {
return 0;
}
if (pipe_config.lambdas.size() != input_models.size()) {
std::cerr << "Number of models (" << input_models.size() << ") should match the number of weights (" << pipe_config.lambdas.size() << ")." << std::endl;
return 1;
}
util::FixedArray<lm::ModelBuffer> models(input_models.size());
for (std::size_t i = 0; i < input_models.size(); ++i) {
models.push_back(input_models[i]);
}
lm::interpolate::Pipeline(models, pipe_config, 1);
} catch (const std::exception &e) {
std::cerr << e.what() <<std::endl;
return 1;
}
return 0;
}

View File

@ -0,0 +1,280 @@
#include "lm/interpolate/merge_probabilities.hh"
#include "lm/common/ngram_stream.hh"
#include "lm/interpolate/bounded_sequence_encoding.hh"
#include "lm/interpolate/interpolate_info.hh"
#include <algorithm>
#include <limits>
#include <numeric>
namespace lm {
namespace interpolate {
/**
* Helper to generate the BoundedSequenceEncoding used for writing the
* from values.
*/
BoundedSequenceEncoding MakeEncoder(const InterpolateInfo &info, uint8_t order) {
util::FixedArray<uint8_t> max_orders(info.orders.size());
for (std::size_t i = 0; i < info.orders.size(); ++i) {
max_orders.push_back(std::min(order, info.orders[i]));
}
return BoundedSequenceEncoding(max_orders.begin(), max_orders.end());
}
namespace {
/**
* A simple wrapper class that holds information needed to read and write
* the ngrams of a particular order. This class has the memory needed to
* buffer the data needed for the recursive process of computing the
* probabilities and "from" values for each component model.
*
* "From" values indicate, for each model, what order (as an index, so -1)
* was backed off to in order to arrive at a probability. For example, if a
* 5-gram model (order index 4) backed off twice, we would write a 2.
*/
class NGramHandler {
public:
NGramHandler(uint8_t order, const InterpolateInfo &ifo,
util::FixedArray<util::stream::ChainPositions> &models_by_order)
: info(ifo),
encoder(MakeEncoder(info, order)),
out_record(order, encoder.EncodedLength()) {
std::size_t count_has_order = 0;
for (std::size_t i = 0; i < models_by_order.size(); ++i) {
count_has_order += (models_by_order[i].size() >= order);
}
inputs_.Init(count_has_order);
for (std::size_t i = 0; i < models_by_order.size(); ++i) {
if (models_by_order[i].size() < order)
continue;
inputs_.push_back(models_by_order[i][order - 1]);
if (inputs_.back()) {
active_.resize(active_.size() + 1);
active_.back().model = i;
active_.back().stream = &inputs_.back();
}
}
// have to init outside since NGramStreams doesn't forward to
// GenericStreams ctor given a ChainPositions
probs.Init(info.Models());
from.Init(info.Models());
for (std::size_t i = 0; i < info.Models(); ++i) {
probs.push_back(0.0);
from.push_back(0);
}
}
struct StreamIndex {
NGramStream<ProbBackoff> *stream;
NGramStream<ProbBackoff> &Stream() { return *stream; }
std::size_t model;
};
std::size_t ActiveSize() const {
return active_.size();
}
/**
* @return the input stream for a particular model that corresponds to
* this ngram order
*/
StreamIndex &operator[](std::size_t idx) {
return active_[idx];
}
void erase(std::size_t idx) {
active_.erase(active_.begin() + idx);
}
const InterpolateInfo &info;
BoundedSequenceEncoding encoder;
PartialProbGamma out_record;
util::FixedArray<float> probs;
util::FixedArray<uint8_t> from;
private:
std::vector<StreamIndex> active_;
NGramStreams<ProbBackoff> inputs_;
};
/**
* A collection of NGramHandlers.
*/
class NGramHandlers : public util::FixedArray<NGramHandler> {
public:
explicit NGramHandlers(std::size_t num)
: util::FixedArray<NGramHandler>(num) {
}
void push_back(
std::size_t order, const InterpolateInfo &info,
util::FixedArray<util::stream::ChainPositions> &models_by_order) {
new (end()) NGramHandler(order, info, models_by_order);
Constructed();
}
};
/**
* The recursive helper function that computes probability and "from"
* values for all ngrams matching a particular suffix.
*
* The current order can be computed as the suffix length + 1. Note that
* the suffix could be empty (suffix_begin == suffix_end == NULL), in which
* case we are handling unigrams with the UNK token as the fallback
* probability.
*
* @param handlers The full collection of handlers
* @param suffix_begin A start iterator for the suffix
* @param suffix_end An end iterator for the suffix
* @param fallback_probs The probabilities of this ngram if we need to
* back off (that is, the probability of the suffix)
* @param fallback_from The order that the corresponding fallback
* probability in the fallback_probs is from
* @param combined_fallback interpolated fallback_probs
* @param outputs The output streams, one for each order
*/
void HandleSuffix(NGramHandlers &handlers, WordIndex *suffix_begin,
WordIndex *suffix_end,
const util::FixedArray<float> &fallback_probs,
const util::FixedArray<uint8_t> &fallback_from,
float combined_fallback,
util::stream::Streams &outputs) {
uint8_t order = std::distance(suffix_begin, suffix_end) + 1;
if (order > outputs.size()) return;
util::stream::Stream &output = outputs[order - 1];
NGramHandler &handler = handlers[order - 1];
while (true) {
// find the next smallest ngram which matches our suffix
// TODO: priority queue driven.
WordIndex *minimum = NULL;
for (std::size_t i = 0; i < handler.ActiveSize(); ++i) {
if (!std::equal(suffix_begin, suffix_end, handler[i].Stream()->begin() + 1))
continue;
// if we either haven't set a minimum yet or this one is smaller than
// the minimum we found before, replace it
WordIndex *last = handler[i].Stream()->begin();
if (!minimum || *last < *minimum) { minimum = handler[i].Stream()->begin(); }
}
// no more ngrams of this order match our suffix, so we're done
if (!minimum) return;
handler.out_record.ReBase(output.Get());
std::copy(minimum, minimum + order, handler.out_record.begin());
// Default case is having backed off.
std::copy(fallback_probs.begin(), fallback_probs.end(), handler.probs.begin());
std::copy(fallback_from.begin(), fallback_from.end(), handler.from.begin());
for (std::size_t i = 0; i < handler.ActiveSize();) {
if (std::equal(handler.out_record.begin(), handler.out_record.end(),
handler[i].Stream()->begin())) {
handler.probs[handler[i].model] = handler.info.lambdas[handler[i].model] * handler[i].Stream()->Value().prob;
handler.from[handler[i].model] = order - 1;
if (++handler[i].Stream()) {
++i;
} else {
handler.erase(i);
}
} else {
++i;
}
}
handler.out_record.Prob() = std::accumulate(handler.probs.begin(), handler.probs.end(), 0.0);
handler.out_record.LowerProb() = combined_fallback;
handler.encoder.Encode(handler.from.begin(),
handler.out_record.FromBegin());
// we've handled this particular ngram, so now recurse to the higher
// order using the current ngram as the suffix
HandleSuffix(handlers, handler.out_record.begin(), handler.out_record.end(),
handler.probs, handler.from, handler.out_record.Prob(), outputs);
// consume the output
++output;
}
}
/**
* Kicks off the recursion for computing the probabilities and "from"
* values for each ngram order. We begin by handling the UNK token that
* should be at the front of each of the unigram input streams. This is
* then output to the stream and it is used as the fallback for handling
* our unigram case, the unigram used as the fallback for the bigram case,
* etc.
*/
void HandleNGrams(NGramHandlers &handlers, util::stream::Streams &outputs) {
PartialProbGamma unk_record(1, 0);
// First: populate the unk probabilities by reading the first unigram
// from each stream
util::FixedArray<float> unk_probs(handlers[0].info.Models());
// start by populating the ngram id from the first stream
lm::NGram<ProbBackoff> ngram = *handlers[0][0].Stream();
unk_record.ReBase(outputs[0].Get());
std::copy(ngram.begin(), ngram.end(), unk_record.begin());
unk_record.Prob() = 0;
// then populate the probabilities into unk_probs while "multiply" the
// model probabilities together into the unk record
//
// note that from doesn't need to be set for unigrams
assert(handlers[0].ActiveSize() == handlers[0].info.Models());
for (std::size_t i = 0; i < handlers[0].info.Models();) {
ngram = *handlers[0][i].Stream();
unk_probs.push_back(handlers[0].info.lambdas[i] * ngram.Value().prob);
unk_record.Prob() += unk_probs[i];
assert(*ngram.begin() == kUNK);
if (++handlers[0][i].Stream()) {
++i;
} else {
handlers[0].erase(i);
}
}
float unk_combined = unk_record.Prob();
unk_record.LowerProb() = unk_combined;
// flush the unk output record
++outputs[0];
// Then, begin outputting everything in lexicographic order: first we'll
// get the unigram then the first bigram with that context, then the
// first trigram with that bigram context, etc., until we exhaust all of
// the ngrams, then all of the (n-1)grams, etc.
//
// This function is the "root" of this recursive process.
util::FixedArray<uint8_t> unk_from(handlers[0].info.Models());
for (std::size_t i = 0; i < handlers[0].info.Models(); ++i) {
unk_from.push_back(0);
}
// the two nulls are to encode that our "fallback" word is the "0-gram"
// case, e.g. we "backed off" to UNK
// TODO: stop generating vocab ids and LowerProb for unigrams.
HandleSuffix(handlers, NULL, NULL, unk_probs, unk_from, unk_combined, outputs);
// Verify we reached the end. And poison!
for (std::size_t i = 0; i < handlers.size(); ++i) {
UTIL_THROW_IF2(handlers[i].ActiveSize(),
"MergeProbabilities did not exhaust all ngram streams");
outputs[i].Poison();
}
}
} // namespace
void MergeProbabilities::Run(const util::stream::ChainPositions &output_pos) {
NGramHandlers handlers(output_pos.size());
for (std::size_t i = 0; i < output_pos.size(); ++i) {
handlers.push_back(i + 1, info_, models_by_order_);
}
util::stream::Streams outputs(output_pos);
HandleNGrams(handlers, outputs);
}
}} // namespaces

View File

@ -0,0 +1,96 @@
#ifndef LM_INTERPOLATE_MERGE_PROBABILITIES_H
#define LM_INTERPOLATE_MERGE_PROBABILITIES_H
#include "lm/common/ngram.hh"
#include "lm/interpolate/bounded_sequence_encoding.hh"
#include "util/fixed_array.hh"
#include "util/stream/multi_stream.hh"
#include <stdint.h>
namespace lm {
namespace interpolate {
struct InterpolateInfo;
/**
* Make the encoding of backoff values for a given order. This stores values
* in [PartialProbGamma::FromBegin(), PartialProbGamma::FromEnd())
*/
BoundedSequenceEncoding MakeEncoder(const InterpolateInfo &info, uint8_t order);
/**
* The first pass for the offline log-linear interpolation algorithm. This
* reads K **suffix-ordered** streams for each model, for each order, of
* ngram records (ngram-id, prob, backoff). It further assumes that the
* ngram-ids have been unified over all of the stream inputs.
*
* Its output is records of (ngram-id, prob-prod, backoff-level,
* backoff-level, ...) where the backoff-levels (of which there are K) are
* the context length (0 for unigrams) that the corresponding model had to
* back off to in order to obtain a probability for that ngram-id. Each of
* these streams is terminated with a record whose ngram-id is all
* maximum-integers for simplicity in implementation here.
*
* @param model_by_order An array of length N (max_i N_i) containing at
* the ChainPositions for the streams for order (i + 1).
* The Rus attached to output chains for each order (of length K)
*/
class MergeProbabilities {
public:
MergeProbabilities(const InterpolateInfo &info, util::FixedArray<util::stream::ChainPositions> &models_by_order)
: info_(info), models_by_order_(models_by_order) {}
void Run(const util::stream::ChainPositions &outputs);
private:
const InterpolateInfo &info_;
util::FixedArray<util::stream::ChainPositions> &models_by_order_;
};
/**
* This class represents the output payload for this pass, which consists
* of an ngram-id, a probability, and then a vector of orders from which
* each of the component models backed off to for this ngram, encoded
* using the BoundedSequenceEncoding class.
*/
class PartialProbGamma : public lm::NGramHeader {
public:
PartialProbGamma(std::size_t order, std::size_t backoff_bytes)
: lm::NGramHeader(NULL, order), backoff_bytes_(backoff_bytes) {
// nothing
}
std::size_t TotalSize() const {
return sizeof(WordIndex) * Order() + sizeof(After) + backoff_bytes_;
}
// TODO: cache bounded sequence encoding in the pipeline?
static std::size_t TotalSize(const InterpolateInfo &info, uint8_t order) {
return sizeof(WordIndex) * order + sizeof(After) + MakeEncoder(info, order).EncodedLength();
}
float &Prob() { return Pay().prob; }
float Prob() const { return Pay().prob; }
float &LowerProb() { return Pay().lower_prob; }
float LowerProb() const { return Pay().lower_prob; }
const uint8_t *FromBegin() const { return Pay().from; }
uint8_t *FromBegin() { return Pay().from; }
private:
struct After {
// Note that backoff_and_normalize assumes this comes first.
float prob;
float lower_prob;
uint8_t from[];
};
const After &Pay() const { return *reinterpret_cast<const After *>(end()); }
After &Pay() { return *reinterpret_cast<After*>(end()); }
std::size_t backoff_bytes_;
};
}} // namespaces
#endif // LM_INTERPOLATE_MERGE_PROBABILITIES_H

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1 @@
toto

View File

@ -0,0 +1,131 @@
#include "lm/interpolate/merge_vocab.hh"
#include "lm/enumerate_vocab.hh"
#include "lm/interpolate/universal_vocab.hh"
#include "lm/lm_exception.hh"
#include "lm/vocab.hh"
#include "util/file_piece.hh"
#include <queue>
#include <string>
#include <iostream>
#include <vector>
namespace lm {
namespace interpolate {
namespace {
class VocabFileReader {
public:
explicit VocabFileReader(const int fd, size_t model_num, uint64_t offset = 0);
VocabFileReader &operator++();
operator bool() const { return !eof_; }
uint64_t operator*() const { return Value(); }
uint64_t Value() const { return hash_value_; }
size_t ModelNum() const { return model_num_; }
WordIndex CurrentIndex() const { return current_index_; }
StringPiece Word() const { return word_; }
private:
uint64_t hash_value_;
WordIndex current_index_;
bool eof_;
size_t model_num_;
StringPiece word_;
util::FilePiece file_piece_;
};
VocabFileReader::VocabFileReader(const int fd, const size_t model_num, uint64_t offset) :
hash_value_(0),
current_index_(0),
eof_(false),
model_num_(model_num),
file_piece_(util::DupOrThrow(fd)) {
word_ = file_piece_.ReadLine('\0');
UTIL_THROW_IF(word_ != "<unk>",
FormatLoadException,
"Vocabulary words are in the wrong place.");
// setup to initial value
++*this;
}
VocabFileReader &VocabFileReader::operator++() {
try {
word_ = file_piece_.ReadLine('\0');
} catch(util::EndOfFileException &e) {
eof_ = true;
return *this;
}
uint64_t prev_hash_value = hash_value_;
hash_value_ = ngram::detail::HashForVocab(word_.data(), word_.size());
// hash values should be monotonically increasing
UTIL_THROW_IF(hash_value_ < prev_hash_value, FormatLoadException,
": word index not monotonically increasing."
<< " model_num: " << model_num_
<< " prev hash: " << prev_hash_value
<< " new hash: " << hash_value_);
++current_index_;
return *this;
}
class CompareFiles {
public:
bool operator()(const VocabFileReader* x,
const VocabFileReader* y)
{ return x->Value() > y->Value(); }
};
class Readers : public util::FixedArray<VocabFileReader> {
public:
Readers(std::size_t number) : util::FixedArray<VocabFileReader>(number) {}
void push_back(int fd, std::size_t i) {
new(end()) VocabFileReader(fd, i);
Constructed();
}
};
} // namespace
WordIndex MergeVocab(util::FixedArray<int> &files, UniversalVocab &vocab, EnumerateVocab &enumerate) {
typedef std::priority_queue<VocabFileReader*, std::vector<VocabFileReader*>, CompareFiles> HeapType;
HeapType heap;
Readers readers(files.size());
for (size_t i = 0; i < files.size(); ++i) {
readers.push_back(files[i], i);
heap.push(&readers.back());
// initialize first index to 0 for <unk>
vocab.InsertUniversalIdx(i, 0, 0);
}
uint64_t prev_hash_value = 0;
// global_index starts with <unk> which is 0
WordIndex global_index = 0;
enumerate.Add(0, "<unk>");
while (!heap.empty()) {
VocabFileReader* top_vocab_file = heap.top();
if (top_vocab_file->Value() != prev_hash_value) {
enumerate.Add(++global_index, top_vocab_file->Word());
}
vocab.InsertUniversalIdx(top_vocab_file->ModelNum(),
top_vocab_file->CurrentIndex(),
global_index);
prev_hash_value = top_vocab_file->Value();
heap.pop();
if (++(*top_vocab_file)) {
heap.push(top_vocab_file);
}
}
return global_index + 1;
}
} // namespace interpolate
} // namespace lm

View File

@ -0,0 +1,23 @@
#ifndef LM_INTERPOLATE_MERGE_VOCAB_H
#define LM_INTERPOLATE_MERGE_VOCAB_H
#include "lm/word_index.hh"
#include "util/file.hh"
#include "util/fixed_array.hh"
namespace lm {
class EnumerateVocab;
namespace interpolate {
class UniversalVocab;
// The combined vocabulary is enumerated with enumerate.
// Returns the size of the combined vocabulary.
// Does not take ownership of vocab_files.
WordIndex MergeVocab(util::FixedArray<int> &vocab_files, UniversalVocab &vocab, EnumerateVocab &enumerate);
}} // namespaces
#endif // LM_INTERPOLATE_MERGE_VOCAB_H

View File

@ -0,0 +1,127 @@
#define BOOST_TEST_MODULE InterpolateMergeVocabTest
#include <boost/test/unit_test.hpp>
#include "lm/enumerate_vocab.hh"
#include "lm/interpolate/merge_vocab.hh"
#include "lm/interpolate/universal_vocab.hh"
#include "lm/lm_exception.hh"
#include "lm/vocab.hh"
#include "lm/word_index.hh"
#include "util/file.hh"
#include "util/file_piece.hh"
#include <cstring>
namespace lm {
namespace interpolate {
namespace {
// Stupid bjam permutes the command line arguments randomly.
class TestFiles {
public:
TestFiles() {
char **argv = boost::unit_test::framework::master_test_suite().argv;
int argc = boost::unit_test::framework::master_test_suite().argc;
BOOST_REQUIRE_EQUAL(6, argc);
for (int i = 1; i < argc; ++i) {
EndsWithAssign(argv[i], "test1", test[0]);
EndsWithAssign(argv[i], "test2", test[1]);
EndsWithAssign(argv[i], "test3", test[2]);
EndsWithAssign(argv[i], "no_unk", no_unk);
EndsWithAssign(argv[i], "bad_order", bad_order);
}
}
void EndsWithAssign(char *arg, StringPiece value, util::scoped_fd &to) {
StringPiece str(arg);
if (str.size() < value.size()) return;
if (std::memcmp(str.data() + str.size() - value.size(), value.data(), value.size())) return;
to.reset(util::OpenReadOrThrow(arg));
}
util::scoped_fd test[3], no_unk, bad_order;
};
class DoNothingEnumerate : public EnumerateVocab {
public:
void Add(WordIndex, const StringPiece &) {}
};
BOOST_AUTO_TEST_CASE(MergeVocabTest) {
TestFiles files;
util::FixedArray<int> used_files(3);
used_files.push_back(files.test[0].get());
used_files.push_back(files.test[1].get());
used_files.push_back(files.test[2].get());
std::vector<lm::WordIndex> model_max_idx;
model_max_idx.push_back(10);
model_max_idx.push_back(10);
model_max_idx.push_back(10);
util::scoped_fd combined(util::MakeTemp("temporary"));
UniversalVocab universal_vocab(model_max_idx);
{
ngram::ImmediateWriteWordsWrapper writer(NULL, combined.get(), 0);
MergeVocab(used_files, universal_vocab, writer);
}
BOOST_CHECK_EQUAL(universal_vocab.GetUniversalIdx(0, 0), 0);
BOOST_CHECK_EQUAL(universal_vocab.GetUniversalIdx(1, 0), 0);
BOOST_CHECK_EQUAL(universal_vocab.GetUniversalIdx(2, 0), 0);
BOOST_CHECK_EQUAL(universal_vocab.GetUniversalIdx(0, 1), 1);
BOOST_CHECK_EQUAL(universal_vocab.GetUniversalIdx(1, 1), 2);
BOOST_CHECK_EQUAL(universal_vocab.GetUniversalIdx(2, 1), 8);
BOOST_CHECK_EQUAL(universal_vocab.GetUniversalIdx(0, 5), 11);
BOOST_CHECK_EQUAL(universal_vocab.GetUniversalIdx(1, 3), 4);
BOOST_CHECK_EQUAL(universal_vocab.GetUniversalIdx(2, 3), 10);
util::SeekOrThrow(combined.get(), 0);
util::FilePiece f(combined.release());
BOOST_CHECK_EQUAL("<unk>", f.ReadLine('\0'));
BOOST_CHECK_EQUAL("a", f.ReadLine('\0'));
BOOST_CHECK_EQUAL("is this", f.ReadLine('\0'));
BOOST_CHECK_EQUAL("this a", f.ReadLine('\0'));
BOOST_CHECK_EQUAL("first cut", f.ReadLine('\0'));
BOOST_CHECK_EQUAL("this", f.ReadLine('\0'));
BOOST_CHECK_EQUAL("a first", f.ReadLine('\0'));
BOOST_CHECK_EQUAL("cut", f.ReadLine('\0'));
BOOST_CHECK_EQUAL("is", f.ReadLine('\0'));
BOOST_CHECK_EQUAL("i", f.ReadLine('\0'));
BOOST_CHECK_EQUAL("secd", f.ReadLine('\0'));
BOOST_CHECK_EQUAL("first", f.ReadLine('\0'));
BOOST_CHECK_THROW(f.ReadLine('\0'), util::EndOfFileException);
}
BOOST_AUTO_TEST_CASE(MergeVocabNoUnkTest) {
TestFiles files;
util::FixedArray<int> used_files(1);
used_files.push_back(files.no_unk.get());
std::vector<lm::WordIndex> model_max_idx;
model_max_idx.push_back(10);
UniversalVocab universal_vocab(model_max_idx);
DoNothingEnumerate nothing;
BOOST_CHECK_THROW(MergeVocab(used_files, universal_vocab, nothing), FormatLoadException);
}
BOOST_AUTO_TEST_CASE(MergeVocabWrongOrderTest) {
TestFiles files;
util::FixedArray<int> used_files(2);
used_files.push_back(files.test[0].get());
used_files.push_back(files.bad_order.get());
std::vector<lm::WordIndex> model_max_idx;
model_max_idx.push_back(10);
model_max_idx.push_back(10);
lm::interpolate::UniversalVocab universal_vocab(model_max_idx);
DoNothingEnumerate nothing;
BOOST_CHECK_THROW(MergeVocab(used_files, universal_vocab, nothing), FormatLoadException);
}
}}} // namespaces

View File

@ -0,0 +1,373 @@
#include "lm/interpolate/normalize.hh"
#include "lm/common/compare.hh"
#include "lm/common/ngram_stream.hh"
#include "lm/interpolate/backoff_matrix.hh"
#include "lm/interpolate/bounded_sequence_encoding.hh"
#include "lm/interpolate/interpolate_info.hh"
#include "lm/interpolate/merge_probabilities.hh"
#include "lm/weights.hh"
#include "lm/word_index.hh"
#include "util/fixed_array.hh"
#include "util/scoped.hh"
#include "util/stream/stream.hh"
#include "util/stream/rewindable_stream.hh"
#include <functional>
#include <queue>
#include <vector>
namespace lm { namespace interpolate {
namespace {
class BackoffQueueEntry {
public:
BackoffQueueEntry(float &entry, const util::stream::ChainPosition &position)
: entry_(entry), stream_(position) {
entry_ = 0.0;
}
operator bool() const { return stream_; }
NGramHeader operator*() const { return *stream_; }
const NGramHeader *operator->() const { return &*stream_; }
void Enter() {
entry_ = stream_->Value().backoff;
}
BackoffQueueEntry &Next() {
entry_ = 0.0;
++stream_;
return *this;
}
private:
float &entry_;
NGramStream<ProbBackoff> stream_;
};
struct PtrGreater : public std::binary_function<const BackoffQueueEntry *, const BackoffQueueEntry *, bool> {
bool operator()(const BackoffQueueEntry *first, const BackoffQueueEntry *second) const {
return SuffixLexicographicLess<NGramHeader>()(**second, **first);
}
};
class EntryOwner : public util::FixedArray<BackoffQueueEntry> {
public:
void push_back(float &entry, const util::stream::ChainPosition &position) {
new (end()) BackoffQueueEntry(entry, position);
Constructed();
}
};
std::size_t MaxOrder(const util::FixedArray<util::stream::ChainPositions> &model) {
std::size_t ret = 0;
for (const util::stream::ChainPositions *m = model.begin(); m != model.end(); ++m) {
ret = std::max(ret, m->size());
}
return ret;
}
class BackoffManager {
public:
explicit BackoffManager(const util::FixedArray<util::stream::ChainPositions> &models)
: entered_(MaxOrder(models)), matrix_(models.size(), MaxOrder(models)), skip_write_(MaxOrder(models)) {
std::size_t total = 0;
for (const util::stream::ChainPositions *m = models.begin(); m != models.end(); ++m) {
total += m->size();
}
for (std::size_t i = 0; i < MaxOrder(models); ++i) {
entered_.push_back(models.size());
}
owner_.Init(total);
for (const util::stream::ChainPositions *m = models.begin(); m != models.end(); ++m) {
for (const util::stream::ChainPosition *j = m->begin(); j != m->end(); ++j) {
owner_.push_back(matrix_.Backoff(m - models.begin(), j - m->begin()), *j);
if (owner_.back()) {
queue_.push(&owner_.back());
}
}
}
}
void SetupSkip(std::size_t order, util::stream::Stream &stream) {
skip_write_[order - 2] = &stream;
}
// Move up the backoffs for the given n-gram. The n-grams must be provided
// in suffix lexicographic order.
void Enter(const NGramHeader &to) {
// Check that we exited properly.
for (std::size_t i = to.Order() - 1; i < entered_.size(); ++i) {
assert(entered_[i].empty());
}
SuffixLexicographicLess<NGramHeader> less;
while (!queue_.empty() && less(**queue_.top(), to))
SkipRecord();
while (TopMatches(to)) {
BackoffQueueEntry *matches = queue_.top();
entered_[to.Order() - 1].push_back(matches);
matches->Enter();
queue_.pop();
}
}
void Exit(std::size_t order_minus_1) {
for (BackoffQueueEntry **i = entered_[order_minus_1].begin(); i != entered_[order_minus_1].end(); ++i) {
if ((*i)->Next())
queue_.push(*i);
}
entered_[order_minus_1].clear();
}
float Get(std::size_t model, std::size_t order_minus_1) const {
return matrix_.Backoff(model, order_minus_1);
}
void Finish() {
while (!queue_.empty())
SkipRecord();
}
private:
void SkipRecord() {
BackoffQueueEntry *top = queue_.top();
queue_.pop();
// Is this the last instance of the n-gram?
if (!TopMatches(**top)) {
// An n-gram is being skipped. Called once per skipped n-gram,
// regardless of how many models it comes from.
*reinterpret_cast<float*>(skip_write_[(*top)->Order() - 1]->Get()) = 0.0;
++*skip_write_[(*top)->Order() - 1];
}
if (top->Next())
queue_.push(top);
}
bool TopMatches(const NGramHeader &header) const {
return !queue_.empty() && (*queue_.top())->Order() == header.Order() && std::equal(header.begin(), header.end(), (*queue_.top())->begin());
}
EntryOwner owner_;
std::priority_queue<BackoffQueueEntry*, std::vector<BackoffQueueEntry*>, PtrGreater> queue_;
// Indexed by order then just all the matching models.
util::FixedArray<util::FixedArray<BackoffQueueEntry*> > entered_;
BackoffMatrix matrix_;
std::vector<util::stream::Stream*> skip_write_;
};
typedef long double Accum;
// Handles n-grams of the same order, using recursion to call another instance
// for higher orders.
class Recurse {
public:
Recurse(
const InterpolateInfo &info, // Must stay alive the entire time.
std::size_t order,
const util::stream::ChainPosition &merged_probs,
const util::stream::ChainPosition &prob_out,
const util::stream::ChainPosition &backoff_out,
BackoffManager &backoffs,
Recurse *higher) // higher is null for the highest order.
: order_(order),
encoding_(MakeEncoder(info, order)),
input_(merged_probs, PartialProbGamma(order, encoding_.EncodedLength())),
prob_out_(prob_out),
backoff_out_(backoff_out),
backoffs_(backoffs),
lambdas_(&*info.lambdas.begin()),
higher_(higher),
decoded_backoffs_(info.Models()),
extended_context_(order - 1) {
// This is only for bigrams and above. Summing unigrams is a much easier case.
assert(order >= 2);
}
// context = w_1^{n-1}
// z_lower = Z(w_2^{n-1})
// Input:
// Merged probabilities without backoff applied in input_.
// Backoffs via backoffs_.
// Calculates:
// Z(w_1^{n-1}): intermediate only.
// p_I(x | w_1^{n-1}) for all x: w_1^{n-1}x exists: Written to prob_out_.
// b_I(w_1^{n-1}): Written to backoff_out_.
void SameContext(const NGramHeader &context, Accum z_lower) {
assert(context.size() == order_ - 1);
backoffs_.Enter(context);
prob_out_.Mark();
// This is the backoff term that applies when one assumes everything backs off:
// \prod_i b_i(w_1^{n-1})^{\lambda_i}.
Accum backoff_once = 0.0;
for (std::size_t m = 0; m < decoded_backoffs_.size(); ++m) {
backoff_once += lambdas_[m] * backoffs_.Get(m, order_ - 2);
}
Accum z_delta = 0.0;
std::size_t count = 0;
for (; input_ && std::equal(context.begin(), context.end(), input_->begin()); ++input_, ++prob_out_, ++count) {
// Apply backoffs to probabilities.
// TODO: change bounded sequence encoding to have an iterator for decoding instead of doing a copy here.
encoding_.Decode(input_->FromBegin(), &*decoded_backoffs_.begin());
for (std::size_t m = 0; m < NumModels(); ++m) {
// Apply the backoffs as instructed for model m.
float accumulated = 0.0;
// Change backoffs for [order it backed off to, order - 1) except
// with 0-indexing. There is still the potential to charge backoff
// for order - 1, which is done later. The backoffs charged here
// are b_m(w_{n-1}^{n-1}) ... b_m(w_2^{n-1})
for (unsigned char backed_to = decoded_backoffs_[m]; backed_to < order_ - 2; ++backed_to) {
accumulated += backoffs_.Get(m, backed_to);
}
float lambda = lambdas_[m];
// Lower p(x | w_2^{n-1}) gets all the backoffs except the highest.
input_->LowerProb() += accumulated * lambda;
// Charge the backoff b(w_1^{n-1}) if applicable, but only to attain p(x | w_1^{n-1})
if (decoded_backoffs_[m] < order_ - 1) {
accumulated += backoffs_.Get(m, order_ - 2);
}
input_->Prob() += accumulated * lambda;
}
// TODO: better precision/less operations here.
z_delta += pow(10.0, input_->Prob()) - pow(10.0, input_->LowerProb() + backoff_once);
// Write unnormalized probability record.
std::copy(input_->begin(), input_->end(), reinterpret_cast<WordIndex*>(prob_out_.Get()));
ProbWrite() = input_->Prob();
}
// TODO numerical precision.
Accum z = log10(pow(10.0, z_lower + backoff_once) + z_delta);
// Normalize.
prob_out_.Rewind();
for (std::size_t i = 0; i < count; ++i, ++prob_out_) {
ProbWrite() -= z;
}
// This allows the stream to release data.
prob_out_.Mark();
// Output backoff.
*reinterpret_cast<float*>(backoff_out_.Get()) = z_lower + backoff_once - z;
++backoff_out_;
if (higher_.get())
higher_->ExtendContext(context, z);
backoffs_.Exit(order_ - 2);
}
// Call is given a context and z(context).
// Evaluates y context x for all y,x.
void ExtendContext(const NGramHeader &middle, Accum z_lower) {
assert(middle.size() == order_ - 2);
// Copy because the input will advance. TODO avoid this copy by sharing amongst classes.
std::copy(middle.begin(), middle.end(), extended_context_.begin() + 1);
while (input_ && std::equal(middle.begin(), middle.end(), input_->begin() + 1)) {
*extended_context_.begin() = *input_->begin();
SameContext(NGramHeader(&*extended_context_.begin(), order_ - 1), z_lower);
}
}
void Finish() {
assert(!input_);
prob_out_.Poison();
backoff_out_.Poison();
if (higher_.get())
higher_->Finish();
}
// The BackoffManager class also injects backoffs when it skips ahead e.g. b(</s>) = 1
util::stream::Stream &BackoffStream() { return backoff_out_; }
private:
// Write the probability to the correct place in prob_out_. Should use a proxy but currently incompatible with RewindableStream.
float &ProbWrite() {
return *reinterpret_cast<float*>(reinterpret_cast<uint8_t*>(prob_out_.Get()) + order_ * sizeof(WordIndex));
}
std::size_t NumModels() const { return decoded_backoffs_.size(); }
const std::size_t order_;
const BoundedSequenceEncoding encoding_;
ProxyStream<PartialProbGamma> input_;
util::stream::RewindableStream prob_out_;
util::stream::Stream backoff_out_;
BackoffManager &backoffs_;
const float *const lambdas_;
// Higher order instance of this same class.
util::scoped_ptr<Recurse> higher_;
// Temporary in SameContext.
std::vector<unsigned char> decoded_backoffs_;
// Temporary in ExtendContext.
std::vector<WordIndex> extended_context_;
};
class Thread {
public:
Thread(const InterpolateInfo &info, util::FixedArray<util::stream::ChainPositions> &models_by_order, util::stream::Chains &prob_out, util::stream::Chains &backoff_out)
: info_(info), models_by_order_(models_by_order), prob_out_(prob_out), backoff_out_(backoff_out) {}
void Run(const util::stream::ChainPositions &merged_probabilities) {
// Unigrams do not have enocded backoff info.
ProxyStream<PartialProbGamma> in(merged_probabilities[0], PartialProbGamma(1, 0));
util::stream::RewindableStream prob_write(prob_out_[0]);
Accum z = 0.0;
prob_write.Mark();
WordIndex count = 0;
for (; in; ++in, ++prob_write, ++count) {
// Note assumption that probabilitity comes first
memcpy(prob_write.Get(), in.Get(), sizeof(WordIndex) + sizeof(float));
z += pow(10.0, in->Prob());
}
// TODO HACK TODO: lmplz outputs p(<s>) = 1 to get q to compute nicely. That will always result in 1.0 more than it should be.
z -= 1.0;
float log_z = log10(z);
prob_write.Rewind();
// Normalize unigram probabilities.
for (WordIndex i = 0; i < count; ++i, ++prob_write) {
*reinterpret_cast<float*>(reinterpret_cast<uint8_t*>(prob_write.Get()) + sizeof(WordIndex)) -= log_z;
}
prob_write.Poison();
// Now setup the higher orders.
util::scoped_ptr<Recurse> higher_order;
BackoffManager backoffs(models_by_order_);
std::size_t max_order = merged_probabilities.size();
for (std::size_t order = max_order; order >= 2; --order) {
higher_order.reset(new Recurse(info_, order, merged_probabilities[order - 1], prob_out_[order - 1], backoff_out_[order - 2], backoffs, higher_order.release()));
backoffs.SetupSkip(order, higher_order->BackoffStream());
}
if (max_order > 1) {
higher_order->ExtendContext(NGramHeader(NULL, 0), log_z);
backoffs.Finish();
higher_order->Finish();
}
}
private:
const InterpolateInfo info_;
util::FixedArray<util::stream::ChainPositions> &models_by_order_;
util::stream::ChainPositions prob_out_;
util::stream::ChainPositions backoff_out_;
};
} // namespace
void Normalize(const InterpolateInfo &info, util::FixedArray<util::stream::ChainPositions> &models_by_order, util::stream::Chains &merged_probabilities, util::stream::Chains &prob_out, util::stream::Chains &backoff_out) {
assert(prob_out.size() == backoff_out.size() + 1);
// Arbitrarily put the thread on the merged_probabilities Chains.
merged_probabilities >> Thread(info, models_by_order, prob_out, backoff_out);
}
}} // namespaces

View File

@ -0,0 +1,35 @@
#ifndef LM_INTERPOLATE_NORMALIZE_H
#define LM_INTERPOLATE_NORMALIZE_H
#include "util/fixed_array.hh"
/* Pass 2:
* - Multiply backoff weights by the backed off probabilities from pass 1.
* - Compute the normalization factor Z.
* - Send Z to the next highest order.
* - Rewind and divide by Z.
*/
namespace util { namespace stream {
class ChainPositions;
class Chains;
}} // namespaces
namespace lm { namespace interpolate {
struct InterpolateInfo;
void Normalize(
const InterpolateInfo &info,
// Input full models for backoffs. Assumes that renumbering has been done. Suffix order.
util::FixedArray<util::stream::ChainPositions> &models_by_order,
// Input PartialProbGamma from MergeProbabilities. Context order.
util::stream::Chains &merged_probabilities,
// Output NGram<float> with normalized probabilities. Context order.
util::stream::Chains &probabilities_out,
// Output bare floats with backoffs. Note backoffs.size() == order - 1. Suffix order.
util::stream::Chains &backoffs_out);
}} // namespaces
#endif // LM_INTERPOLATE_NORMALIZE_H

View File

@ -0,0 +1,86 @@
#include "lm/interpolate/normalize.hh"
#include "lm/interpolate/interpolate_info.hh"
#include "lm/interpolate/merge_probabilities.hh"
#include "lm/common/ngram_stream.hh"
#include "util/stream/chain.hh"
#include "util/stream/multi_stream.hh"
#define BOOST_TEST_MODULE NormalizeTest
#include <boost/test/unit_test.hpp>
namespace lm { namespace interpolate { namespace {
// log without backoff
const float kInputs[] = {-0.3, 1.2, -9.8, 4.0, -7.0, 0.0};
class WriteInput {
public:
WriteInput() {}
void Run(const util::stream::ChainPosition &to) {
util::stream::Stream out(to);
for (WordIndex i = 0; i < sizeof(kInputs) / sizeof(float); ++i, ++out) {
memcpy(out.Get(), &i, sizeof(WordIndex));
memcpy((uint8_t*)out.Get() + sizeof(WordIndex), &kInputs[i], sizeof(float));
}
out.Poison();
}
};
void CheckOutput(const util::stream::ChainPosition &from) {
NGramStream<float> in(from);
float sum = 0.0;
for (WordIndex i = 0; i < sizeof(kInputs) / sizeof(float) - 1 /* <s> at the end */; ++i) {
sum += pow(10.0, kInputs[i]);
}
sum = log10(sum);
BOOST_REQUIRE(in);
BOOST_CHECK_CLOSE(kInputs[0] - sum, in->Value(), 0.0001);
BOOST_REQUIRE(++in);
BOOST_CHECK_CLOSE(kInputs[1] - sum, in->Value(), 0.0001);
BOOST_REQUIRE(++in);
BOOST_CHECK_CLOSE(kInputs[2] - sum, in->Value(), 0.0001);
BOOST_REQUIRE(++in);
BOOST_CHECK_CLOSE(kInputs[3] - sum, in->Value(), 0.0001);
BOOST_REQUIRE(++in);
BOOST_CHECK_CLOSE(kInputs[4] - sum, in->Value(), 0.0001);
BOOST_REQUIRE(++in);
BOOST_CHECK_CLOSE(kInputs[5] - sum, in->Value(), 0.0001);
BOOST_CHECK(!++in);
}
BOOST_AUTO_TEST_CASE(Unigrams) {
InterpolateInfo info;
info.lambdas.push_back(2.0);
info.lambdas.push_back(-0.1);
info.orders.push_back(1);
info.orders.push_back(1);
BOOST_CHECK_EQUAL(0, MakeEncoder(info, 1).EncodedLength());
// No backoffs.
util::stream::Chains blank(0);
util::FixedArray<util::stream::ChainPositions> models_by_order(2);
models_by_order.push_back(blank);
models_by_order.push_back(blank);
util::stream::Chains merged_probabilities(1);
util::stream::Chains probabilities_out(1);
util::stream::Chains backoffs_out(0);
merged_probabilities.push_back(util::stream::ChainConfig(sizeof(WordIndex) + sizeof(float) + sizeof(float), 2, 24));
probabilities_out.push_back(util::stream::ChainConfig(sizeof(WordIndex) + sizeof(float), 2, 100));
merged_probabilities[0] >> WriteInput();
Normalize(info, models_by_order, merged_probabilities, probabilities_out, backoffs_out);
util::stream::ChainPosition checker(probabilities_out[0].Add());
merged_probabilities >> util::stream::kRecycle;
probabilities_out >> util::stream::kRecycle;
CheckOutput(checker);
probabilities_out.Wait();
}
}}} // namespaces

View File

@ -0,0 +1,187 @@
#include "lm/interpolate/pipeline.hh"
#include "lm/common/compare.hh"
#include "lm/common/print.hh"
#include "lm/common/renumber.hh"
#include "lm/vocab.hh"
#include "lm/interpolate/backoff_reunification.hh"
#include "lm/interpolate/interpolate_info.hh"
#include "lm/interpolate/merge_probabilities.hh"
#include "lm/interpolate/merge_vocab.hh"
#include "lm/interpolate/normalize.hh"
#include "lm/interpolate/universal_vocab.hh"
#include "util/stream/chain.hh"
#include "util/stream/count_records.hh"
#include "util/stream/io.hh"
#include "util/stream/multi_stream.hh"
#include "util/stream/sort.hh"
#include "util/fixed_array.hh"
namespace lm { namespace interpolate { namespace {
/* Put the original input files on chains and renumber them */
void SetupInputs(std::size_t buffer_size, const UniversalVocab &vocab, util::FixedArray<ModelBuffer> &models, bool exclude_highest, util::FixedArray<util::stream::Chains> &chains, util::FixedArray<util::stream::ChainPositions> &positions) {
chains.clear();
positions.clear();
// TODO: much better memory sizing heuristics e.g. not making the chain larger than it will use.
util::stream::ChainConfig config(0, 2, buffer_size);
for (std::size_t i = 0; i < models.size(); ++i) {
chains.push_back(models[i].Order() - exclude_highest);
for (std::size_t j = 0; j < models[i].Order() - exclude_highest; ++j) {
config.entry_size = sizeof(WordIndex) * (j + 1) + sizeof(float) * 2; // TODO do not include wasteful backoff for highest.
chains.back().push_back(config);
}
if (i == models.size() - 1)
chains.back().back().ActivateProgress();
models[i].Source(chains.back());
for (std::size_t j = 0; j < models[i].Order() - exclude_highest; ++j) {
chains[i][j] >> Renumber(vocab.Mapping(i), j + 1);
}
}
for (std::size_t i = 0; i < chains.size(); ++i) {
positions.push_back(chains[i]);
}
}
template <class Compare> void SinkSort(const util::stream::SortConfig &config, util::stream::Chains &chains, util::stream::Sorts<Compare> &sorts) {
for (std::size_t i = 0; i < chains.size(); ++i) {
sorts.push_back(chains[i], config, Compare(i + 1));
}
}
template <class Compare> void SourceSort(util::stream::Chains &chains, util::stream::Sorts<Compare> &sorts) {
// TODO memory management
for (std::size_t i = 0; i < sorts.size(); ++i) {
sorts[i].Merge(sorts[i].DefaultLazy());
}
for (std::size_t i = 0; i < sorts.size(); ++i) {
sorts[i].Output(chains[i], sorts[i].DefaultLazy());
}
}
} // namespace
void Pipeline(util::FixedArray<ModelBuffer> &models, const Config &config, int write_file) {
// Setup InterpolateInfo and UniversalVocab.
InterpolateInfo info;
info.lambdas = config.lambdas;
std::vector<WordIndex> vocab_sizes;
util::scoped_fd vocab_null(util::MakeTemp(config.sort.temp_prefix));
std::size_t max_order = 0;
util::FixedArray<int> vocab_files(models.size());
for (ModelBuffer *i = models.begin(); i != models.end(); ++i) {
info.orders.push_back(i->Order());
vocab_sizes.push_back(i->Counts()[0]);
vocab_files.push_back(i->VocabFile());
max_order = std::max(max_order, i->Order());
}
util::scoped_ptr<UniversalVocab> vocab(new UniversalVocab(vocab_sizes));
{
ngram::ImmediateWriteWordsWrapper writer(NULL, vocab_null.get(), 0);
MergeVocab(vocab_files, *vocab, writer);
}
std::cerr << "Merging probabilities." << std::endl;
// Pass 1: merge probabilities
util::FixedArray<util::stream::Chains> input_chains(models.size());
util::FixedArray<util::stream::ChainPositions> models_by_order(models.size());
SetupInputs(config.BufferSize(), *vocab, models, false, input_chains, models_by_order);
util::stream::Chains merged_probs(max_order);
for (std::size_t i = 0; i < max_order; ++i) {
merged_probs.push_back(util::stream::ChainConfig(PartialProbGamma::TotalSize(info, i + 1), 2, config.BufferSize())); // TODO: not buffer_size
}
merged_probs >> MergeProbabilities(info, models_by_order);
std::vector<uint64_t> counts(max_order);
for (std::size_t i = 0; i < max_order; ++i) {
merged_probs[i] >> util::stream::CountRecords(&counts[i]);
}
for (util::stream::Chains *i = input_chains.begin(); i != input_chains.end(); ++i) {
*i >> util::stream::kRecycle;
}
// Pass 2: normalize.
{
util::stream::Sorts<ContextOrder> sorts(merged_probs.size());
SinkSort(config.sort, merged_probs, sorts);
merged_probs.Wait(true);
for (util::stream::Chains *i = input_chains.begin(); i != input_chains.end(); ++i) {
i->Wait(true);
}
SourceSort(merged_probs, sorts);
}
std::cerr << "Normalizing" << std::endl;
SetupInputs(config.BufferSize(), *vocab, models, true, input_chains, models_by_order);
util::stream::Chains probabilities(max_order), backoffs(max_order - 1);
std::size_t block_count = 2;
for (std::size_t i = 0; i < max_order; ++i) {
// Careful accounting to ensure RewindableStream can fit the entire vocabulary.
block_count = std::max<std::size_t>(block_count, 2);
// This much needs to fit in RewindableStream.
std::size_t fit = NGram<float>::TotalSize(i + 1) * counts[0];
// fit / (block_count - 1) rounded up
std::size_t min_block = (fit + block_count - 2) / (block_count - 1);
std::size_t specify = std::max(config.BufferSize(), min_block * block_count);
probabilities.push_back(util::stream::ChainConfig(NGram<float>::TotalSize(i + 1), block_count, specify));
}
for (std::size_t i = 0; i < max_order - 1; ++i) {
backoffs.push_back(util::stream::ChainConfig(sizeof(float), 2, config.BufferSize()));
}
Normalize(info, models_by_order, merged_probs, probabilities, backoffs);
util::FixedArray<util::stream::FileBuffer> backoff_buffers(backoffs.size());
for (std::size_t i = 0; i < max_order - 1; ++i) {
backoff_buffers.push_back(util::MakeTemp(config.sort.temp_prefix));
backoffs[i] >> backoff_buffers.back().Sink() >> util::stream::kRecycle;
}
for (util::stream::Chains *i = input_chains.begin(); i != input_chains.end(); ++i) {
*i >> util::stream::kRecycle;
}
merged_probs >> util::stream::kRecycle;
// Pass 3: backoffs in the right place.
{
util::stream::Sorts<SuffixOrder> sorts(probabilities.size());
SinkSort(config.sort, probabilities, sorts);
probabilities.Wait(true);
for (util::stream::Chains *i = input_chains.begin(); i != input_chains.end(); ++i) {
i->Wait(true);
}
backoffs.Wait(true);
merged_probs.Wait(true);
// destroy universal vocab to save RAM.
vocab.reset();
SourceSort(probabilities, sorts);
}
std::cerr << "Reunifying backoffs" << std::endl;
util::stream::ChainPositions prob_pos(max_order - 1);
util::stream::Chains combined(max_order - 1);
for (std::size_t i = 0; i < max_order - 1; ++i) {
if (i == max_order - 2)
backoffs[i].ActivateProgress();
backoffs[i].SetProgressTarget(backoff_buffers[i].Size());
backoffs[i] >> backoff_buffers[i].Source(true);
prob_pos.push_back(probabilities[i].Add());
combined.push_back(util::stream::ChainConfig(NGram<ProbBackoff>::TotalSize(i + 1), 2, config.BufferSize()));
}
util::stream::ChainPositions backoff_pos(backoffs);
ReunifyBackoff(prob_pos, backoff_pos, combined);
util::stream::ChainPositions output_pos(max_order);
for (std::size_t i = 0; i < max_order - 1; ++i) {
output_pos.push_back(combined[i].Add());
}
output_pos.push_back(probabilities.back().Add());
probabilities >> util::stream::kRecycle;
backoffs >> util::stream::kRecycle;
combined >> util::stream::kRecycle;
// TODO genericize to ModelBuffer etc.
PrintARPA(vocab_null.get(), write_file, counts).Run(output_pos);
}
}} // namespaces

View File

@ -0,0 +1,22 @@
#ifndef LM_INTERPOLATE_PIPELINE_H
#define LM_INTERPOLATE_PIPELINE_H
#include "lm/common/model_buffer.hh"
#include "util/fixed_array.hh"
#include "util/stream/config.hh"
#include <cstddef>
#include <string>
namespace lm { namespace interpolate {
struct Config {
std::vector<float> lambdas;
util::stream::SortConfig sort;
std::size_t BufferSize() const { return sort.buffer_size; }
};
void Pipeline(util::FixedArray<ModelBuffer> &models, const Config &config, int write_file);
}} // namespaces
#endif // LM_INTERPOLATE_PIPELINE_H

View File

@ -0,0 +1,40 @@
#include "lm/interpolate/split_worker.hh"
#include "lm/common/ngram.hh"
namespace lm {
namespace interpolate {
SplitWorker::SplitWorker(std::size_t order, util::stream::Chain &backoff_chain,
util::stream::Chain &sort_chain)
: order_(order) {
backoff_chain >> backoff_input_;
sort_chain >> sort_input_;
}
void SplitWorker::Run(const util::stream::ChainPosition &position) {
// input: ngram record (id, prob, and backoff)
// output: a float to the backoff_input stream
// an ngram id and a float to the sort_input stream
for (util::stream::Stream stream(position); stream; ++stream) {
NGram<ProbBackoff> ngram(stream.Get(), order_);
// write id and prob to the sort stream
float prob = ngram.Value().prob;
lm::WordIndex *out = reinterpret_cast<lm::WordIndex *>(sort_input_.Get());
for (const lm::WordIndex *it = ngram.begin(); it != ngram.end(); ++it) {
*out++ = *it;
}
*reinterpret_cast<float *>(out) = prob;
++sort_input_;
// write backoff to the backoff output stream
float boff = ngram.Value().backoff;
*reinterpret_cast<float *>(backoff_input_.Get()) = boff;
++backoff_input_;
}
sort_input_.Poison();
backoff_input_.Poison();
}
}
}

View File

@ -0,0 +1,44 @@
#ifndef KENLM_INTERPOLATE_SPLIT_WORKER_H_
#define KENLM_INTERPOLATE_SPLIT_WORKER_H_
#include "util/stream/chain.hh"
#include "util/stream/stream.hh"
namespace lm {
namespace interpolate {
class SplitWorker {
public:
/**
* Constructs a split worker for a particular order. It writes the
* split-off backoff values to the backoff chain and the ngram id and
* probability to the sort chain for each ngram in the input.
*/
SplitWorker(std::size_t order, util::stream::Chain &backoff_chain,
util::stream::Chain &sort_chain);
/**
* The callback invoked to handle the input from the ngram intermediate
* files.
*/
void Run(const util::stream::ChainPosition& position);
private:
/**
* The ngram order we are reading/writing for.
*/
std::size_t order_;
/**
* The stream to write to for the backoff values.
*/
util::stream::Stream backoff_input_;
/**
* The stream to write to for the ngram id + probability values.
*/
util::stream::Stream sort_input_;
};
}
}
#endif

View File

@ -0,0 +1,195 @@
#include "lm/common/compare.hh"
#include "lm/common/model_buffer.hh"
#include "lm/common/ngram.hh"
#include "util/stream/chain.hh"
#include "util/stream/multi_stream.hh"
#include "util/stream/sort.hh"
#include "lm/interpolate/split_worker.hh"
#include <boost/program_options.hpp>
#include <boost/version.hpp>
#if defined(_WIN32) || defined(_WIN64)
// Windows doesn't define <unistd.h>
//
// So we define what we need here instead:
//
#define STDIN_FILENO = 0
#define STDOUT_FILENO = 1
#else // Huzzah for POSIX!
#include <unistd.h>
#endif
/*
* This is a simple example program that takes in intermediate
* suffix-sorted ngram files and outputs two sets of files: one for backoff
* probability values (raw numbers, in suffix order) and one for
* probability values (ngram id and probability, in *context* order)
*/
int main(int argc, char *argv[]) {
using namespace lm::interpolate;
const std::size_t ONE_GB = 1 << 30;
const std::size_t SIXTY_FOUR_MB = 1 << 26;
const std::size_t NUMBER_OF_BLOCKS = 2;
std::string FILE_NAME = "ngrams";
std::string CONTEXT_SORTED_FILENAME = "csorted-ngrams";
std::string BACKOFF_FILENAME = "backoffs";
std::string TMP_DIR = "/tmp/";
try {
namespace po = boost::program_options;
po::options_description options("canhazinterp Pass-3 options");
options.add_options()
("help,h", po::bool_switch(), "Show this help message")
("ngrams,n", po::value<std::string>(&FILE_NAME), "ngrams file")
("csortngrams,c", po::value<std::string>(&CONTEXT_SORTED_FILENAME), "context sorted ngrams file")
("backoffs,b", po::value<std::string>(&BACKOFF_FILENAME), "backoffs file")
("tmpdir,t", po::value<std::string>(&TMP_DIR), "tmp dir");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, options), vm);
// Display help
if(vm["help"].as<bool>()) {
std::cerr << "Usage: " << options << std::endl;
return 1;
}
}
catch(const std::exception &e) {
std::cerr << e.what() << std::endl;
return 1;
}
// The basic strategy here is to have three chains:
// - The first reads the ngram order inputs using ModelBuffer. Those are
// then stripped of their backoff values and fed into the third chain;
// the backoff values *themselves* are written to the second chain.
//
// - The second chain takes the backoff values and writes them out to a
// file (one for each order).
//
// - The third chain takes just the probability values and ngrams and
// writes them out, sorted in context-order, to a file (one for each
// order).
// This will be used to read in the binary intermediate files. There is
// one file per order (e.g. ngrams.1, ngrams.2, ...)
lm::ModelBuffer buffer(FILE_NAME);
// Create a separate chains for each ngram order for:
// - Input from the intermediate files
// - Output to the backoff file
// - Output to the (context-sorted) probability file
util::stream::Chains ngram_inputs(buffer.Order());
util::stream::Chains backoff_chains(buffer.Order());
util::stream::Chains prob_chains(buffer.Order());
for (std::size_t i = 0; i < buffer.Order(); ++i) {
ngram_inputs.push_back(util::stream::ChainConfig(
lm::NGram<lm::ProbBackoff>::TotalSize(i + 1), NUMBER_OF_BLOCKS, ONE_GB));
backoff_chains.push_back(
util::stream::ChainConfig(sizeof(float), NUMBER_OF_BLOCKS, ONE_GB));
prob_chains.push_back(util::stream::ChainConfig(
sizeof(lm::WordIndex) * (i + 1) + sizeof(float), NUMBER_OF_BLOCKS,
ONE_GB));
}
// This sets the input for each of the ngram order chains to the
// appropriate file
buffer.Source(ngram_inputs);
util::FixedArray<util::scoped_ptr<SplitWorker> > workers(buffer.Order());
for (std::size_t i = 0; i < buffer.Order(); ++i) {
// Attach a SplitWorker to each of the ngram input chains, writing to the
// corresponding order's backoff and probability chains
workers.push_back(
new SplitWorker(i + 1, backoff_chains[i], prob_chains[i]));
ngram_inputs[i] >> boost::ref(*workers.back());
}
util::stream::SortConfig sort_cfg;
sort_cfg.temp_prefix = TMP_DIR;
sort_cfg.buffer_size = SIXTY_FOUR_MB;
sort_cfg.total_memory = ONE_GB;
// This will parallel merge sort the individual order files, putting
// them in context-order instead of suffix-order.
//
// Two new threads will be running, each owned by the chains[i] object.
// - The first executes BlockSorter.Run() to sort the n-gram entries
// - The second executes WriteAndRecycle.Run() to write each sorted
// block to disk as a temporary file
util::stream::Sorts<lm::ContextOrder> sorts(buffer.Order());
for (std::size_t i = 0; i < prob_chains.size(); ++i) {
sorts.push_back(prob_chains[i], sort_cfg, lm::ContextOrder(i + 1));
}
// Set the sort output to be on the same chain
for (std::size_t i = 0; i < prob_chains.size(); ++i) {
// The following call to Chain::Wait()
// joins the threads owned by chains[i].
//
// As such the following call won't return
// until all threads owned by chains[i] have completed.
//
// The following call also resets chain[i]
// so that it can be reused
// (including free'ing the memory previously used by the chain)
prob_chains[i].Wait();
// In an ideal world (without memory restrictions)
// we could merge all of the previously sorted blocks
// by reading them all completely into memory
// and then running merge sort over them.
//
// In the real world, we have memory restrictions;
// depending on how many blocks we have,
// and how much memory we can use to read from each block
// (sort_config.buffer_size)
// it may be the case that we have insufficient memory
// to read sort_config.buffer_size of data from each block from disk.
//
// If this occurs, then it will be necessary to perform one or more rounds
// of merge sort on disk;
// doing so will reduce the number of blocks that we will eventually
// need to read from
// when performing the final round of merge sort in memory.
//
// So, the following call determines whether it is necessary
// to perform one or more rounds of merge sort on disk;
// if such on-disk merge sorting is required, such sorting is performed.
//
// Finally, the following method launches a thread that calls
// OwningMergingReader.Run()
// to perform the final round of merge sort in memory.
//
// Merge sort could have be invoked directly
// so that merge sort memory doesn't coexist with Chain memory.
sorts[i].Output(prob_chains[i]);
}
// Create another model buffer for our output on e.g. csorted-ngrams.1,
// csorted-ngrams.2, ...
lm::ModelBuffer output_buf(CONTEXT_SORTED_FILENAME, true, false);
output_buf.Sink(prob_chains, buffer.Counts());
// Create a third model buffer for our backoff output on e.g. backoff.1,
// backoff.2, ...
lm::ModelBuffer boff_buf(BACKOFF_FILENAME, true, false);
boff_buf.Sink(backoff_chains, buffer.Counts());
// Joins all threads that chains owns,
// and does a for loop over each chain object in chains,
// calling chain.Wait() on each such chain object
ngram_inputs.Wait(true);
backoff_chains.Wait(true);
prob_chains.Wait(true);
return 0;
}

View File

@ -0,0 +1,127 @@
#include "lm/interpolate/tune_derivatives.hh"
#include "lm/interpolate/tune_instances.hh"
#include "lm/interpolate/tune_matrix.hh"
#include "util/stream/chain.hh"
#include "util/stream/typed_stream.hh"
#include <Eigen/Core>
namespace lm { namespace interpolate {
Accum Derivatives(Instances &in, const Vector &weights, Vector &gradient, Matrix &hessian) {
gradient = in.CorrectGradientTerm();
hessian = Matrix::Zero(weights.rows(), weights.rows());
// TODO: loop instead to force low-memory evaluation?
// Compute p_I(x)*Z_{\epsilon} i.e. the unnormalized probabilities
Vector weighted_uni((in.LNUnigrams() * weights).array().exp());
// Even -inf doesn't work for <s> because weights can be negative. Manually set it to zero.
weighted_uni(in.BOS()) = 0.0;
Accum Z_epsilon = weighted_uni.sum();
// unigram_cross(i) = \sum_{all x} p_I(x) ln p_i(x)
Vector unigram_cross(in.LNUnigrams().transpose() * weighted_uni / Z_epsilon);
Accum sum_B_I = 0.0;
Accum sum_ln_Z_context = 0.0;
// Temporaries used each cycle of the loop.
Matrix convolve;
Vector full_cross;
Matrix hessian_missing_Z_context;
// Backed off ln p_i(x)B_i(context)
Vector ln_p_i_backed;
// Full ln p_i(x | context)
Vector ln_p_i_full;
// TODO make configurable memory size.
util::stream::Chain chain(util::stream::ChainConfig(in.ReadExtensionsEntrySize(), 2, 64 << 20));
chain.ActivateProgress();
in.ReadExtensions(chain);
util::stream::TypedStream<Extension> extensions(chain.Add());
chain >> util::stream::kRecycle;
// Loop over instances (words in the tuning data).
for (InstanceIndex n = 0; n < in.NumInstances(); ++n) {
assert(extensions);
Accum weighted_backoffs = exp(in.LNBackoffs(n).dot(weights));
// Compute \sum_{x: model does not back off to unigram} p_I(x)Z(epsilon)
Accum unnormalized_sum_x_p_I = 0.0;
// Compute \sum_{x: model does not back off to unigram} p_I(x | context)Z(context)
Accum unnormalized_sum_x_p_I_full = 0.0;
// This should be divided by Z_context then added to the Hessian.
hessian_missing_Z_context = Matrix::Zero(weights.rows(), weights.rows());
full_cross = Vector::Zero(weights.rows());
// Loop over words within an instance for which extension exists. An extension happens when any model matches more than a unigram in the tuning instance.
while (extensions && extensions->instance == n) {
const WordIndex word = extensions->word;
unnormalized_sum_x_p_I += weighted_uni(word);
ln_p_i_backed = in.LNUnigrams().row(word) + in.LNBackoffs(n);
// Calculate ln_p_i_full(i) = ln p_i(word | context) by filling in unigrams then overwriting with extensions.
ln_p_i_full = ln_p_i_backed;
// Loop over all models that have an extension for the same word namely p_i(word | context) matches at least a bigram.
for (; extensions && extensions->word == word && extensions->instance == n; ++extensions) {
ln_p_i_full(extensions->model) = extensions->ln_prob;
}
// This is the weighted product of probabilities. In other words, p_I(word | context) * Z(context) = exp(\sum_i w_i * p_i(word | context)).
Accum weighted = exp(ln_p_i_full.dot(weights));
unnormalized_sum_x_p_I_full += weighted;
// These aren't normalized by Z_context (happens later)
full_cross.noalias() +=
weighted * ln_p_i_full
- weighted_uni(word) * weighted_backoffs /* we'll divide by Z_context later to form B_I */ * in.LNUnigrams().row(word).transpose();
// This will get multiplied by Z_context then added to the Hessian.
hessian_missing_Z_context.noalias() +=
// Replacement terms.
weighted * ln_p_i_full * ln_p_i_full.transpose()
// Presumed unigrams. Z_epsilon * weighted_backoffs will turn into B_I once all of this is divided by Z_context.
- weighted_uni(word) * weighted_backoffs * ln_p_i_backed * ln_p_i_backed.transpose();
}
Accum Z_context =
weighted_backoffs * (Z_epsilon - unnormalized_sum_x_p_I) // Back off and unnormalize the unigrams for which there is no extension.
+ unnormalized_sum_x_p_I_full; // Add the extensions.
sum_ln_Z_context += log(Z_context);
Accum B_I = Z_epsilon / Z_context * weighted_backoffs;
sum_B_I += B_I;
// This is the gradient term for this instance except for -log p_i(w_n | w_1^{n-1}) which was accounted for as part of neg_correct_sum_.
// full_cross(i) is \sum_{all x} p_I(x | context) log p_i(x | context)
// Prior terms excluded dividing by Z_context because it wasn't known at the time.
full_cross /= Z_context;
full_cross +=
// Uncorrected term
B_I * (in.LNBackoffs(n).transpose() + unigram_cross)
// Subtract values that should not have been charged.
- unnormalized_sum_x_p_I / Z_epsilon * B_I * in.LNBackoffs(n).transpose();
gradient += full_cross;
convolve = unigram_cross * in.LNBackoffs(n);
// There's one missing term here, which is independent of context and done at the end.
hessian.noalias() +=
// First term of Hessian, assuming all models back off to unigram.
B_I * (convolve + convolve.transpose() + in.LNBackoffs(n).transpose() * in.LNBackoffs(n))
// Error in the first term, correcting from unigram to full probabilities.
+ hessian_missing_Z_context / Z_context
// Second term of Hessian, with correct full probabilities.
- full_cross * full_cross.transpose();
}
for (Matrix::Index x = 0; x < weighted_uni.rows(); ++x) {
// \sum_{contexts} B_I(context) \sum_x p_I(x) log p_i(x) log p_j(x)
// TODO can this be optimized? It's summing over the entire vocab which should be a matrix operation.
hessian.noalias() += sum_B_I * weighted_uni(x) / Z_epsilon * in.LNUnigrams().row(x).transpose() * in.LNUnigrams().row(x);
}
return exp((in.CorrectGradientTerm().dot(weights) + sum_ln_Z_context) / static_cast<double>(in.NumInstances()));
}
}} // namespaces

View File

@ -0,0 +1,20 @@
#ifndef LM_INTERPOLATE_TUNE_DERIVATIVES_H
#define LM_INTERPOLATE_TUNE_DERIVATIVES_H
#include "lm/interpolate/tune_matrix.hh"
#include <Eigen/Core>
#include <cmath>
namespace lm { namespace interpolate {
class Instances;
// Given tuning instances and model weights, computes the objective function (log probability), gradient, and Hessian.
// Returns log probability / number of instances.
Accum Derivatives(Instances &instances /* Doesn't modify but ReadExtensions is lazy */, const Vector &weights, Vector &gradient, Matrix &hessian);
}} // namespaces
#endif // LM_INTERPOLATE_TUNE_DERIVATIVES_H

View File

@ -0,0 +1,138 @@
#include "lm/interpolate/tune_derivatives.hh"
#include "lm/interpolate/tune_instances.hh"
#include "util/stream/config.hh"
#include "util/stream/chain.hh"
#include "util/stream/io.hh"
#include "util/stream/typed_stream.hh"
#define BOOST_TEST_MODULE DerivativeTest
#include <boost/test/unit_test.hpp>
namespace lm { namespace interpolate {
class MockInstances : public Instances {
public:
MockInstances() : chain_(util::stream::ChainConfig(ReadExtensionsEntrySize(), 2, 100)), write_(chain_.Add()) {
extensions_subsequent_.reset(new util::stream::FileBuffer(util::MakeTemp("/tmp/")));
chain_ >> extensions_subsequent_->Sink() >> util::stream::kRecycle;
}
Matrix &LNUnigrams() { return ln_unigrams_; }
BackoffMatrix &LNBackoffs() { return ln_backoffs_; }
WordIndex &BOS() { return bos_; }
Vector &NegLNCorrectSum() { return neg_ln_correct_sum_; }
// Extensions must be provided sorted!
void AddExtension(const Extension &extension) {
*write_ = extension;
++write_;
}
void DoneExtending() {
write_.Poison();
chain_.Wait(true);
}
private:
util::stream::Chain chain_;
util::stream::TypedStream<Extension> write_;
};
namespace {
BOOST_AUTO_TEST_CASE(Small) {
MockInstances mock;
{
// Three vocabulary words plus <s>, two models.
Matrix unigrams(4, 2);
unigrams <<
0.1, 0.6,
0.4, 0.3,
0.5, 0.1,
// <s>
1.0, 1.0;
mock.LNUnigrams() = unigrams.array().log();
}
mock.BOS() = 3;
// One instance
mock.LNBackoffs().resize(1, 2);
mock.LNBackoffs() << 0.2, 0.4;
mock.LNBackoffs() = mock.LNBackoffs().array().log();
// Sparse extensions: model 0 word 2 and model 1 word 1.
// Assuming that model 1 only matches word 1, this is p_1(1 | context)
Accum model_1_word_1 = 1.0 - .6 * .4 - .1 * .4;
mock.NegLNCorrectSum().resize(2);
// We'll suppose correct has WordIndex 1, which backs off in model 0, and matches in model 1
mock.NegLNCorrectSum() << (0.4 * 0.2), model_1_word_1;
mock.NegLNCorrectSum() = -mock.NegLNCorrectSum().array().log();
Accum model_0_word_2 = 1.0 - .1 * .2 - .4 * .2;
Extension ext;
ext.instance = 0;
ext.word = 1;
ext.model = 1;
ext.ln_prob = log(model_1_word_1);
mock.AddExtension(ext);
ext.instance = 0;
ext.word = 2;
ext.model = 0;
ext.ln_prob = log(model_0_word_2);
mock.AddExtension(ext);
mock.DoneExtending();
Vector weights(2);
weights << 0.9, 1.2;
Vector gradient(2);
Matrix hessian(2,2);
Derivatives(mock, weights, gradient, hessian);
// TODO: check perplexity value coming out.
// p_I(x | context)
Vector p_I(3);
p_I <<
pow(0.1 * 0.2, 0.9) * pow(0.6 * 0.4, 1.2),
pow(0.4 * 0.2, 0.9) * pow(model_1_word_1, 1.2),
pow(model_0_word_2, 0.9) * pow(0.1 * 0.4, 1.2);
p_I /= p_I.sum();
Vector expected_gradient = mock.NegLNCorrectSum();
expected_gradient(0) += p_I(0) * log(0.1 * 0.2);
expected_gradient(0) += p_I(1) * log(0.4 * 0.2);
expected_gradient(0) += p_I(2) * log(model_0_word_2);
BOOST_CHECK_CLOSE(expected_gradient(0), gradient(0), 0.01);
expected_gradient(1) += p_I(0) * log(0.6 * 0.4);
expected_gradient(1) += p_I(1) * log(model_1_word_1);
expected_gradient(1) += p_I(2) * log(0.1 * 0.4);
BOOST_CHECK_CLOSE(expected_gradient(1), gradient(1), 0.01);
Matrix expected_hessian(2, 2);
expected_hessian(1, 0) =
// First term
p_I(0) * log(0.1 * 0.2) * log(0.6 * 0.4) +
p_I(1) * log(0.4 * 0.2) * log(model_1_word_1) +
p_I(2) * log(model_0_word_2) * log(0.1 * 0.4);
expected_hessian(1, 0) -=
(p_I(0) * log(0.1 * 0.2) + p_I(1) * log(0.4 * 0.2) + p_I(2) * log(model_0_word_2)) *
(p_I(0) * log(0.6 * 0.4) + p_I(1) * log(model_1_word_1) + p_I(2) * log(0.1 * 0.4));
expected_hessian(0, 1) = expected_hessian(1, 0);
BOOST_CHECK_CLOSE(expected_hessian(1, 0), hessian(1, 0), 0.01);
BOOST_CHECK_CLOSE(expected_hessian(0, 1), hessian(0, 1), 0.01);
}
}}} // namespaces

View File

@ -0,0 +1,501 @@
/* Load tuning instances and filter underlying models to them. A tuning
* instance is an n-gram in the tuning file. To tune towards these, we want
* the correct probability p_i(w_n | w_1^{n-1}) from each model as well as
* all the denominators p_i(v | w_1^{n-1}) that appear in normalization.
*
* In other words, we filter the models to only those n-grams whose context
* appears in the tuning data. This can be divided into two categories:
* - All unigrams. This goes into Instances::ln_unigrams_
* - Bigrams and above whose context appears in the tuning data. These are
* known as extensions. We only care about the longest extension for each
* w_1^{n-1}v since that is what will be used for the probability.
* Because there is a large number of extensions (we tried keeping them in RAM
* and ran out), the streaming framework is used to keep track of extensions
* and sort them so they can be streamed in. Downstream code
* (tune_derivatives.hh) takes a stream of extensions ordered by tuning
* instance, the word v, and the model the extension came from.
*/
#include "lm/interpolate/tune_instances.hh"
#include "lm/common/compare.hh"
#include "lm/common/joint_order.hh"
#include "lm/common/model_buffer.hh"
#include "lm/common/ngram_stream.hh"
#include "lm/common/renumber.hh"
#include "lm/enumerate_vocab.hh"
#include "lm/interpolate/merge_vocab.hh"
#include "lm/interpolate/universal_vocab.hh"
#include "lm/lm_exception.hh"
#include "util/file_piece.hh"
#include "util/murmur_hash.hh"
#include "util/stream/chain.hh"
#include "util/stream/io.hh"
#include "util/stream/sort.hh"
#include "util/tokenize_piece.hh"
#include <boost/shared_ptr.hpp>
#include <boost/unordered_map.hpp>
#include <cmath>
#include <limits>
#include <vector>
namespace lm { namespace interpolate {
// gcc 4.6 complains about uninitialized when sort code is generated for a 4-byte POD. But that sort code is never used.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuninitialized"
bool Extension::operator<(const Extension &other) const {
if (instance != other.instance)
return instance < other.instance;
if (word != other.word)
return word < other.word;
if (model != other.model)
return model < other.model;
return false;
}
#pragma GCC diagnostic pop
namespace {
// An extension without backoff weights applied yet.
#pragma pack(push)
#pragma pack(1)
struct InitialExtension {
Extension ext;
// Order from which it came.
uint8_t order;
};
#pragma pack(pop)
struct InitialExtensionCompare {
bool operator()(const void *first, const void *second) const {
return reinterpret_cast<const InitialExtension *>(first)->ext < reinterpret_cast<const InitialExtension *>(second)->ext;
}
};
// Intended use
// For each model:
// stream through orders jointly in suffix order:
// Call MatchedBackoff for full matches.
// Call Exit when the context matches.
// Call FinishModel with the unigram probability of the correct word, get full
// probability in return.
// Use backoffs_out to adjust records that were written to the stream.
// backoffs_out(model, order - 1) is the penalty for matching order.
class InstanceMatch {
public:
InstanceMatch(Matrix &backoffs_out, const WordIndex correct)
: seen_(std::numeric_limits<WordIndex>::max()),
backoffs_(backoffs_out),
correct_(correct), correct_from_(1), correct_ln_prob_(std::numeric_limits<float>::quiet_NaN()) {}
void MatchedBackoff(ModelIndex model, uint8_t order, float ln_backoff) {
backoffs_(model, order - 1) = ln_backoff;
}
// We only want the highest-order matches, which are the first to be exited for a given word.
void Exit(const InitialExtension &from, util::stream::Stream &out) {
if (from.ext.word == seen_) return;
seen_ = from.ext.word;
*static_cast<InitialExtension*>(out.Get()) = from;
++out;
if (UTIL_UNLIKELY(correct_ == from.ext.word)) {
correct_from_ = from.order;
correct_ln_prob_ = from.ext.ln_prob;
}
}
WordIndex Correct() const { return correct_; }
// Call this after each model has been passed through. Provide the unigram
// probability of the correct word (which follows the given context).
// This function will return the fully-backed-off probability of the correct
// word.
float FinishModel(ModelIndex model, float correct_ln_unigram) {
seen_ = std::numeric_limits<WordIndex>::max();
// Turn backoffs into multiplied values (added in log space).
// So backoffs_(model, order - 1) is the penalty for matching order.
float accum = 0.0;
for (int order = backoffs_.cols() - 1; order >= 0; --order) {
accum += backoffs_(model, order);
backoffs_(model, order) = accum;
}
if (correct_from_ == 1) {
correct_ln_prob_ = correct_ln_unigram;
}
if (correct_from_ - 1 < backoffs_.cols()) {
correct_ln_prob_ += backoffs_(model, correct_from_ - 1);
}
correct_from_ = 1;
return correct_ln_prob_;
}
private:
// What's the last word we've seen? Used to act only on exiting the longest match.
WordIndex seen_;
Matrix &backoffs_;
const WordIndex correct_;
// These only apply to the most recent model.
uint8_t correct_from_;
float correct_ln_prob_;
};
// Forward information to multiple instances of a context. So if the tuning
// set contains
// a b c d e
// a b c d e
// there's one DispatchContext for a b c d which calls two InstanceMatch, one
// for each tuning instance. This might be to inform them about a b c d g in
// one of the models.
class DispatchContext {
public:
void Register(InstanceMatch &context) {
registered_.push_back(&context);
}
void MatchedBackoff(ModelIndex model, uint8_t order, float ln_backoff) {
for (std::vector<InstanceMatch*>::iterator i = registered_.begin(); i != registered_.end(); ++i)
(*i)->MatchedBackoff(model, order, ln_backoff);
}
void Exit(InitialExtension &from, util::stream::Stream &out, const InstanceMatch *base_instance) {
for (std::vector<InstanceMatch*>::iterator i = registered_.begin(); i != registered_.end(); ++i) {
from.ext.instance = *i - base_instance;
(*i)->Exit(from, out);
}
}
private:
// TODO make these offsets in a big array rather than separately allocated.
std::vector<InstanceMatch*> registered_;
};
// Map from n-gram hash to contexts in the tuning data. TODO: probing hash table?
typedef boost::unordered_map<uint64_t, DispatchContext> ContextMap;
// Handle all the orders of a single model at once.
class JointOrderCallback {
public:
JointOrderCallback(
std::size_t model,
std::size_t full_order_minus_1,
ContextMap &contexts,
util::stream::Stream &out,
const InstanceMatch *base_instance)
: full_order_minus_1_(full_order_minus_1),
contexts_(contexts),
out_(out),
base_instance_(base_instance) {
ext_.ext.model = model;
}
void Enter(std::size_t order_minus_1, const void *data) {}
void Exit(std::size_t order_minus_1, void *data) {
// Match the full n-gram for backoffs.
if (order_minus_1 != full_order_minus_1_) {
NGram<ProbBackoff> gram(data, order_minus_1 + 1);
ContextMap::iterator i = contexts_.find(util::MurmurHashNative(gram.begin(), gram.Order() * sizeof(WordIndex)));
if (UTIL_UNLIKELY(i != contexts_.end())) {
i->second.MatchedBackoff(ext_.ext.model, gram.Order(), gram.Value().backoff * M_LN10);
}
}
// Match the context of the n-gram to indicate it's an extension.
ContextMap::iterator i = contexts_.find(util::MurmurHashNative(data, order_minus_1 * sizeof(WordIndex)));
if (UTIL_UNLIKELY(i != contexts_.end())) {
NGram<Prob> gram(data, order_minus_1 + 1);
// model is already set.
// instance is set by DispatchContext.
// That leaves word, ln_prob, and order.
ext_.ext.word = *(gram.end() - 1);
ext_.ext.ln_prob = gram.Value().prob * M_LN10;
ext_.order = order_minus_1 + 1;
// model was already set in the constructor.
// ext_.ext.instance is set by the Exit call.
i->second.Exit(ext_, out_, base_instance_);
}
}
void Run(const util::stream::ChainPositions &positions) {
JointOrder<JointOrderCallback, SuffixOrder>(positions, *this);
}
private:
const std::size_t full_order_minus_1_;
// Mapping is constant but values are being manipulated to tell them about
// n-grams.
ContextMap &contexts_;
// Reused variable. model is set correctly.
InitialExtension ext_;
util::stream::Stream &out_;
const InstanceMatch *const base_instance_;
};
// This populates the ln_unigrams_ matrix. It can (and should for efficiency)
// be run in the same scan as JointOrderCallback.
class ReadUnigrams {
public:
explicit ReadUnigrams(Matrix::ColXpr out) : out_(out) {}
// Read renumbered unigrams, fill with <unk> otherwise.
void Run(const util::stream::ChainPosition &position) {
NGramStream<ProbBackoff> stream(position);
assert(stream);
Accum unk = stream->Value().prob * M_LN10;
WordIndex previous = 0;
for (; stream; ++stream) {
WordIndex word = *stream->begin();
out_.segment(previous, word - previous) = Vector::Constant(word - previous, unk);
out_(word) = stream->Value().prob * M_LN10;
//backoffs are used by JointOrderCallback.
previous = word + 1;
}
out_.segment(previous, out_.rows() - previous) = Vector::Constant(out_.rows() - previous, unk);
}
private:
Matrix::ColXpr out_;
};
// Read tuning data into an array of vocab ids. The vocab ids are agreed with MergeVocab.
class IdentifyTuning : public EnumerateVocab {
public:
IdentifyTuning(int tuning_file, std::vector<WordIndex> &out) : indices_(out) {
indices_.clear();
StringPiece line;
std::size_t counter = 0;
std::vector<std::size_t> &eos = words_[util::MurmurHashNative("</s>", 4)];
for (util::FilePiece f(tuning_file); f.ReadLineOrEOF(line);) {
for (util::TokenIter<util::BoolCharacter, true> word(line, util::kSpaces); word; ++word) {
UTIL_THROW_IF(*word == "<s>" || *word == "</s>", FormatLoadException, "Illegal word in tuning data: " << *word);
words_[util::MurmurHashNative(word->data(), word->size())].push_back(counter++);
}
eos.push_back(counter++);
}
// Also get <s>
indices_.resize(counter + 1);
words_[util::MurmurHashNative("<s>", 3)].push_back(indices_.size() - 1);
}
// Apply ids as they come out of MergeVocab if they match.
void Add(WordIndex id, const StringPiece &str) {
boost::unordered_map<uint64_t, std::vector<std::size_t> >::iterator i = words_.find(util::MurmurHashNative(str.data(), str.size()));
if (i != words_.end()) {
for (std::vector<std::size_t>::iterator j = i->second.begin(); j != i->second.end(); ++j) {
indices_[*j] = id;
}
}
}
WordIndex FinishGetBOS() {
WordIndex ret = indices_.back();
indices_.pop_back();
return ret;
}
private:
// array of words in tuning data.
std::vector<WordIndex> &indices_;
// map from hash(string) to offsets in indices_.
boost::unordered_map<uint64_t, std::vector<std::size_t> > words_;
};
} // namespace
// Store information about the first iteration.
class ExtensionsFirstIteration {
public:
explicit ExtensionsFirstIteration(std::size_t instances, std::size_t models, std::size_t max_order, util::stream::Chain &extension_input, const util::stream::SortConfig &config)
: backoffs_by_instance_(new std::vector<Matrix>(instances)), sort_(extension_input, config) {
// Initialize all the backoff matrices to zeros.
for (std::vector<Matrix>::iterator i = backoffs_by_instance_->begin(); i != backoffs_by_instance_->end(); ++i) {
*i = Matrix::Zero(models, max_order);
}
}
Matrix &WriteBackoffs(std::size_t instance) {
return (*backoffs_by_instance_)[instance];
}
// Get the backoff all the way to unigram for a particular tuning instance and model.
Accum FullBackoff(std::size_t instance, std::size_t model) const {
return (*backoffs_by_instance_)[instance](model, 0);
}
void Merge(std::size_t lazy_memory) {
sort_.Merge(lazy_memory);
lazy_memory_ = lazy_memory;
}
void Output(util::stream::Chain &chain) {
sort_.Output(chain, lazy_memory_);
chain >> ApplyBackoffs(backoffs_by_instance_);
}
private:
class ApplyBackoffs {
public:
explicit ApplyBackoffs(boost::shared_ptr<std::vector<Matrix> > backoffs_by_instance)
: backoffs_by_instance_(backoffs_by_instance) {}
void Run(const util::stream::ChainPosition &position) {
// There should always be tuning instances.
const std::vector<Matrix> &backoffs = *backoffs_by_instance_;
assert(!backoffs.empty());
uint8_t max_order = backoffs.front().cols();
for (util::stream::Stream stream(position); stream; ++stream) {
InitialExtension &ini = *reinterpret_cast<InitialExtension*>(stream.Get());
assert(ini.order > 1); // If it's an extension, it should be higher than a unigram.
if (ini.order != max_order) {
ini.ext.ln_prob += backoffs[ini.ext.instance](ini.ext.model, ini.order - 1);
}
}
}
private:
boost::shared_ptr<std::vector<Matrix> > backoffs_by_instance_;
};
// Array of complete backoff matrices by instance.
// Each matrix is by model, then by order.
// Would have liked to use a tensor but it's not that well supported.
// This is a shared pointer so that ApplyBackoffs can run after this class is gone.
boost::shared_ptr<std::vector<Matrix> > backoffs_by_instance_;
// This sorts and stores all the InitialExtensions.
util::stream::Sort<InitialExtensionCompare> sort_;
std::size_t lazy_memory_;
};
Instances::Instances(int tune_file, const std::vector<StringPiece> &model_names, const InstancesConfig &config) : temp_prefix_(config.sort.temp_prefix) {
// All the memory from stack variables here should go away before merge sort of the instances.
{
util::FixedArray<ModelBuffer> models(model_names.size());
// Load tuning set and join vocabulary.
std::vector<WordIndex> vocab_sizes;
vocab_sizes.reserve(model_names.size());
util::FixedArray<int> vocab_files(model_names.size());
std::size_t max_order = 0;
for (std::vector<StringPiece>::const_iterator i = model_names.begin(); i != model_names.end(); ++i) {
models.push_back(*i);
vocab_sizes.push_back(models.back().Counts()[0]);
vocab_files.push_back(models.back().VocabFile());
max_order = std::max(max_order, models.back().Order());
}
UniversalVocab vocab(vocab_sizes);
std::vector<WordIndex> tuning_words;
WordIndex combined_vocab_size;
{
IdentifyTuning identify(tune_file, tuning_words);
combined_vocab_size = MergeVocab(vocab_files, vocab, identify);
bos_ = identify.FinishGetBOS();
}
// Setup the initial extensions storage: a chain going to a sort with a stream in the middle for writing.
util::stream::Chain extensions_chain(util::stream::ChainConfig(sizeof(InitialExtension), 2, config.extension_write_chain_mem));
util::stream::Stream extensions_write(extensions_chain.Add());
extensions_first_.reset(new ExtensionsFirstIteration(tuning_words.size(), model_names.size(), max_order, extensions_chain, config.sort));
// Populate the ContextMap from contexts to instances.
ContextMap cmap;
util::FixedArray<InstanceMatch> instances(tuning_words.size());
{
UTIL_THROW_IF2(tuning_words.empty(), "Empty tuning data");
const WordIndex eos = tuning_words.back();
std::vector<WordIndex> context;
context.push_back(bos_);
for (std::size_t i = 0; i < tuning_words.size(); ++i) {
instances.push_back(boost::ref(extensions_first_->WriteBackoffs(i)), tuning_words[i]);
for (std::size_t j = 0; j < context.size(); ++j) {
cmap[util::MurmurHashNative(&context[j], sizeof(WordIndex) * (context.size() - j))].Register(instances.back());
}
// Prepare for next word by starting a new sentence or shifting context.
if (tuning_words[i] == eos) {
context.clear();
context.push_back(bos_);
} else {
if (context.size() == max_order) {
context.erase(context.begin());
}
context.push_back(tuning_words[i]);
}
}
}
// Go through each model. Populate:
// ln_backoffs_
ln_backoffs_.resize(instances.size(), models.size());
// neg_ln_correct_sum_
neg_ln_correct_sum_.resize(models.size());
// ln_unigrams_
ln_unigrams_.resize(combined_vocab_size, models.size());
// The backoffs in extensions_first_
for (std::size_t m = 0; m < models.size(); ++m) {
std::cerr << "Processing model " << m << '/' << models.size() << ": " << model_names[m] << std::endl;
util::stream::Chains chains(models[m].Order());
for (std::size_t i = 0; i < models[m].Order(); ++i) {
// TODO: stop wasting space for backoffs of highest order.
chains.push_back(util::stream::ChainConfig(NGram<ProbBackoff>::TotalSize(i + 1), 2, config.model_read_chain_mem));
}
chains.back().ActivateProgress();
models[m].Source(chains);
for (std::size_t i = 0; i < models[m].Order(); ++i) {
chains[i] >> Renumber(vocab.Mapping(m), i + 1);
}
// Populate ln_unigrams_.
chains[0] >> ReadUnigrams(ln_unigrams_.col(m));
// Send extensions into extensions_first_ and give data to the instances about backoffs/extensions.
chains >> JointOrderCallback(m, models[m].Order() - 1, cmap, extensions_write, instances.begin());
chains >> util::stream::kRecycle;
chains.Wait(true);
neg_ln_correct_sum_(m) = 0.0;
for (InstanceMatch *i = instances.begin(); i != instances.end(); ++i) {
neg_ln_correct_sum_(m) -= i->FinishModel(m, ln_unigrams_(i->Correct(), m));
ln_backoffs_(i - instances.begin(), m) = extensions_first_->FullBackoff(i - instances.begin(), m);
}
ln_unigrams_(bos_, m) = 0; // Does not matter as long as it does not produce nans since tune_derivatives will overwrite the output.
}
extensions_write.Poison();
}
extensions_first_->Merge(config.lazy_memory);
}
Instances::~Instances() {}
// TODO: size reduction by excluding order for subsequent passes.
std::size_t Instances::ReadExtensionsEntrySize() const {
return sizeof(InitialExtension);
}
void Instances::ReadExtensions(util::stream::Chain &on) {
if (extensions_first_.get()) {
// Lazy sort and save a sorted copy to disk. TODO: cut down on record size by stripping out order information.
extensions_first_->Output(on);
extensions_first_.reset(); // Relevant data will continue to live in workers.
extensions_subsequent_.reset(new util::stream::FileBuffer(util::MakeTemp(temp_prefix_)));
on >> extensions_subsequent_->Sink();
} else {
on.SetProgressTarget(extensions_subsequent_->Size());
on >> extensions_subsequent_->Source();
}
}
// Back door.
Instances::Instances() {}
}} // namespaces

View File

@ -0,0 +1,102 @@
#ifndef LM_INTERPOLATE_TUNE_INSTANCE_H
#define LM_INTERPOLATE_TUNE_INSTANCE_H
#include "lm/interpolate/tune_matrix.hh"
#include "lm/word_index.hh"
#include "util/scoped.hh"
#include "util/stream/config.hh"
#include "util/string_piece.hh"
#include <boost/optional.hpp>
#include <vector>
namespace util { namespace stream {
class Chain;
class FileBuffer;
}} // namespaces
namespace lm { namespace interpolate {
typedef uint32_t InstanceIndex;
typedef uint32_t ModelIndex;
struct Extension {
// Which tuning instance does this belong to?
InstanceIndex instance;
WordIndex word;
ModelIndex model;
// ln p_{model} (word | context(instance))
float ln_prob;
bool operator<(const Extension &other) const;
};
class ExtensionsFirstIteration;
struct InstancesConfig {
// For batching the model reads. This is per order.
std::size_t model_read_chain_mem;
// This is being sorted, make it larger.
std::size_t extension_write_chain_mem;
std::size_t lazy_memory;
util::stream::SortConfig sort;
};
class Instances {
private:
typedef Eigen::Matrix<Accum, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> BackoffMatrix;
public:
Instances(int tune_file, const std::vector<StringPiece> &model_names, const InstancesConfig &config);
// For destruction of forward-declared classes.
~Instances();
// Full backoff from unigram for each model.
typedef BackoffMatrix::ConstRowXpr FullBackoffs;
FullBackoffs LNBackoffs(InstanceIndex instance) const {
return ln_backoffs_.row(instance);
}
InstanceIndex NumInstances() const { return ln_backoffs_.rows(); }
const Vector &CorrectGradientTerm() const { return neg_ln_correct_sum_; }
const Matrix &LNUnigrams() const { return ln_unigrams_; }
// Entry size to use to configure the chain (since in practice order is needed).
std::size_t ReadExtensionsEntrySize() const;
void ReadExtensions(util::stream::Chain &chain);
// Vocab id of the beginning of sentence. Used to ignore it for normalization.
WordIndex BOS() const { return bos_; }
private:
// Allow the derivatives test to get access.
friend class MockInstances;
Instances();
// backoffs_(instance, model) is the backoff all the way to unigrams.
BackoffMatrix ln_backoffs_;
// neg_correct_sum_(model) = -\sum_{instances} ln p_{model}(correct(instance) | context(instance)).
// This appears as a term in the gradient.
Vector neg_ln_correct_sum_;
// ln_unigrams_(word, model) = ln p_{model}(word).
Matrix ln_unigrams_;
// This is the source of data for the first iteration.
util::scoped_ptr<ExtensionsFirstIteration> extensions_first_;
// Source of data for subsequent iterations. This contains already-sorted data.
util::scoped_ptr<util::stream::FileBuffer> extensions_subsequent_;
WordIndex bos_;
std::string temp_prefix_;
};
}} // namespaces
#endif // LM_INTERPOLATE_TUNE_INSTANCE_H

View File

@ -0,0 +1,132 @@
#include "lm/interpolate/tune_instances.hh"
#include "util/file.hh"
#include "util/file_stream.hh"
#include "util/stream/chain.hh"
#include "util/stream/config.hh"
#include "util/stream/typed_stream.hh"
#include "util/string_piece.hh"
#define BOOST_TEST_MODULE InstanceTest
#include <boost/test/unit_test.hpp>
#include <vector>
#include <math.h>
namespace lm { namespace interpolate { namespace {
BOOST_AUTO_TEST_CASE(Toy) {
util::scoped_fd test_input(util::MakeTemp("temporary"));
util::FileStream(test_input.get()) << "c\n";
StringPiece dir("../common/test_data/");
if (boost::unit_test::framework::master_test_suite().argc == 2) {
StringPiece zero_file(boost::unit_test::framework::master_test_suite().argv[1]);
BOOST_REQUIRE(zero_file.size() > strlen("toy0.1"));
BOOST_REQUIRE_EQUAL("toy0.1", StringPiece(zero_file.data() + zero_file.size() - 6, 6));
dir = StringPiece(zero_file.data(), zero_file.size() - 6);
}
std::vector<StringPiece> model_names;
std::string full0 = std::string(dir.data(), dir.size()) + "toy0";
std::string full1 = std::string(dir.data(), dir.size()) + "toy1";
model_names.push_back(full0);
model_names.push_back(full1);
// Tiny buffer sizes.
InstancesConfig config;
config.model_read_chain_mem = 100;
config.extension_write_chain_mem = 100;
config.lazy_memory = 100;
config.sort.temp_prefix = "temporary";
config.sort.buffer_size = 100;
config.sort.total_memory = 1024;
util::SeekOrThrow(test_input.get(), 0);
Instances inst(test_input.release(), model_names, config);
BOOST_CHECK_EQUAL(1, inst.BOS());
const Matrix &ln_unigrams = inst.LNUnigrams();
// <unk>=0
BOOST_CHECK_CLOSE(-0.90309 * M_LN10, ln_unigrams(0, 0), 0.001);
BOOST_CHECK_CLOSE(-1 * M_LN10, ln_unigrams(0, 1), 0.001);
// <s>=1 doesn't matter as long as it doesn't cause NaNs.
BOOST_CHECK(!isnan(ln_unigrams(1, 0)));
BOOST_CHECK(!isnan(ln_unigrams(1, 1)));
// a = 2
BOOST_CHECK_CLOSE(-0.46943438 * M_LN10, ln_unigrams(2, 0), 0.001);
BOOST_CHECK_CLOSE(-0.6146491 * M_LN10, ln_unigrams(2, 1), 0.001);
// </s> = 3
BOOST_CHECK_CLOSE(-0.5720968 * M_LN10, ln_unigrams(3, 0), 0.001);
BOOST_CHECK_CLOSE(-0.6146491 * M_LN10, ln_unigrams(3, 1), 0.001);
// c = 4
BOOST_CHECK_CLOSE(-0.90309 * M_LN10, ln_unigrams(4, 0), 0.001); // <unk>
BOOST_CHECK_CLOSE(-0.7659168 * M_LN10, ln_unigrams(4, 1), 0.001);
// too lazy to do b = 5.
// Two instances:
// <s> predicts c
// <s> c predicts </s>
BOOST_REQUIRE_EQUAL(2, inst.NumInstances());
BOOST_CHECK_CLOSE(-0.30103 * M_LN10, inst.LNBackoffs(0)(0), 0.001);
BOOST_CHECK_CLOSE(-0.30103 * M_LN10, inst.LNBackoffs(0)(1), 0.001);
// Backoffs of <s> c
BOOST_CHECK_CLOSE(0.0, inst.LNBackoffs(1)(0), 0.001);
BOOST_CHECK_CLOSE((-0.30103 - 0.30103) * M_LN10, inst.LNBackoffs(1)(1), 0.001);
util::stream::Chain extensions(util::stream::ChainConfig(inst.ReadExtensionsEntrySize(), 2, 300));
inst.ReadExtensions(extensions);
util::stream::TypedStream<Extension> stream(extensions.Add());
extensions >> util::stream::kRecycle;
// The extensions are (in order of instance, vocab id, and model as they should be sorted):
// <s> a from both models 0 and 1 (so two instances)
// <s> c from model 1
// <s> b from model 0
// c </s> from model 1
// Magic probabilities come from querying the models directly.
// <s> a from model 0
BOOST_REQUIRE(stream);
BOOST_CHECK_EQUAL(0, stream->instance);
BOOST_CHECK_EQUAL(2 /* a */, stream->word);
BOOST_CHECK_EQUAL(0, stream->model);
BOOST_CHECK_CLOSE(-0.37712017 * M_LN10, stream->ln_prob, 0.001);
// <s> a from model 1
BOOST_REQUIRE(++stream);
BOOST_CHECK_EQUAL(0, stream->instance);
BOOST_CHECK_EQUAL(2 /* a */, stream->word);
BOOST_CHECK_EQUAL(1, stream->model);
BOOST_CHECK_CLOSE(-0.4301247 * M_LN10, stream->ln_prob, 0.001);
// <s> c from model 1
BOOST_REQUIRE(++stream);
BOOST_CHECK_EQUAL(0, stream->instance);
BOOST_CHECK_EQUAL(4 /* c */, stream->word);
BOOST_CHECK_EQUAL(1, stream->model);
BOOST_CHECK_CLOSE(-0.4740302 * M_LN10, stream->ln_prob, 0.001);
// <s> b from model 0
BOOST_REQUIRE(++stream);
BOOST_CHECK_EQUAL(0, stream->instance);
BOOST_CHECK_EQUAL(5 /* b */, stream->word);
BOOST_CHECK_EQUAL(0, stream->model);
BOOST_CHECK_CLOSE(-0.41574955 * M_LN10, stream->ln_prob, 0.001);
// c </s> from model 1
BOOST_REQUIRE(++stream);
BOOST_CHECK_EQUAL(1, stream->instance);
BOOST_CHECK_EQUAL(3 /* </s> */, stream->word);
BOOST_CHECK_EQUAL(1, stream->model);
BOOST_CHECK_CLOSE(-0.09113217 * M_LN10, stream->ln_prob, 0.001);
BOOST_CHECK(!++stream);
}
}}} // namespaces

View File

@ -0,0 +1,18 @@
#ifndef LM_INTERPOLATE_TUNE_MATRIX_H
#define LM_INTERPOLATE_TUNE_MATRIX_H
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpragmas" // Older gcc doesn't have "-Wunused-local-typedefs" and complains.
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#include <Eigen/Core>
#pragma GCC diagnostic pop
namespace lm { namespace interpolate {
typedef Eigen::MatrixXf Matrix;
typedef Eigen::VectorXf Vector;
typedef Matrix::Scalar Accum;
}} // namespaces
#endif // LM_INTERPOLATE_TUNE_MATRIX_H

View File

@ -0,0 +1,33 @@
#include "lm/interpolate/tune_weights.hh"
#include "lm/interpolate/tune_derivatives.hh"
#include "lm/interpolate/tune_instances.hh"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpragmas" // Older gcc doesn't have "-Wunused-local-typedefs" and complains.
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#include <Eigen/Dense>
#pragma GCC diagnostic pop
#include <boost/program_options.hpp>
#include <iostream>
namespace lm { namespace interpolate {
void TuneWeights(int tune_file, const std::vector<StringPiece> &model_names, const InstancesConfig &config, std::vector<float> &weights_out) {
Instances instances(tune_file, model_names, config);
Vector weights = Vector::Constant(model_names.size(), 1.0 / model_names.size());
Vector gradient;
Matrix hessian;
for (std::size_t iteration = 0; iteration < 10 /*TODO fancy stopping criteria */; ++iteration) {
std::cerr << "Iteration " << iteration << ": weights =";
for (Vector::Index i = 0; i < weights.rows(); ++i) {
std::cerr << ' ' << weights(i);
}
std::cerr << std::endl;
std::cerr << "Perplexity = " << Derivatives(instances, weights, gradient, hessian) << std::endl;
// TODO: 1.0 step size was too big and it kept getting unstable. More math.
weights -= 0.7 * hessian.inverse() * gradient;
}
weights_out.assign(weights.data(), weights.data() + weights.size());
}
}} // namespaces

View File

@ -0,0 +1,15 @@
#ifndef LM_INTERPOLATE_TUNE_WEIGHTS_H
#define LM_INTERPOLATE_TUNE_WEIGHTS_H
#include "util/string_piece.hh"
#include <vector>
namespace lm { namespace interpolate {
struct InstancesConfig;
// Run a tuning loop, producing weights as output.
void TuneWeights(int tune_file, const std::vector<StringPiece> &model_names, const InstancesConfig &config, std::vector<float> &weights);
}} // namespaces
#endif // LM_INTERPOLATE_TUNE_WEIGHTS_H

View File

@ -0,0 +1,13 @@
#include "lm/interpolate/universal_vocab.hh"
namespace lm {
namespace interpolate {
UniversalVocab::UniversalVocab(const std::vector<WordIndex>& model_vocab_sizes) {
model_index_map_.resize(model_vocab_sizes.size());
for (size_t i = 0; i < model_vocab_sizes.size(); ++i) {
model_index_map_[i].resize(model_vocab_sizes[i]);
}
}
}} // namespaces

View File

@ -0,0 +1,44 @@
#ifndef LM_INTERPOLATE_UNIVERSAL_VOCAB_H
#define LM_INTERPOLATE_UNIVERSAL_VOCAB_H
#include "lm/word_index.hh"
#include <vector>
#include <cstddef>
namespace lm {
namespace interpolate {
class UniversalVocab {
public:
explicit UniversalVocab(const std::vector<WordIndex>& model_vocab_sizes);
// GetUniversalIndex takes the model number and index for the specific
// model and returns the universal model number
WordIndex GetUniversalIdx(std::size_t model_num, WordIndex model_word_index) const {
return model_index_map_[model_num][model_word_index];
}
const WordIndex *Mapping(std::size_t model) const {
return &*model_index_map_[model].begin();
}
WordIndex SlowConvertToModel(std::size_t model, WordIndex index) const {
std::vector<WordIndex>::const_iterator i = lower_bound(model_index_map_[model].begin(), model_index_map_[model].end(), index);
if (i == model_index_map_[model].end() || *i != index) return 0;
return i - model_index_map_[model].begin();
}
void InsertUniversalIdx(std::size_t model_num, WordIndex word_index,
WordIndex universal_word_index) {
model_index_map_[model_num][word_index] = universal_word_index;
}
private:
std::vector<std::vector<WordIndex> > model_index_map_;
};
} // namespace interpolate
} // namespace lm
#endif // LM_INTERPOLATE_UNIVERSAL_VOCAB_H

View File

@ -0,0 +1,232 @@
#include "lm/model.hh"
#include "util/file_stream.hh"
#include "util/file.hh"
#include "util/file_piece.hh"
#include "util/usage.hh"
#include "util/thread_pool.hh"
#include <boost/range/iterator_range.hpp>
#include <boost/program_options.hpp>
#include <iostream>
#include <stdint.h>
namespace {
template <class Model, class Width> void ConvertToBytes(const Model &model, int fd_in) {
util::FilePiece in(fd_in);
util::FileStream out(1);
Width width;
StringPiece word;
const Width end_sentence = (Width)model.GetVocabulary().EndSentence();
while (true) {
while (in.ReadWordSameLine(word)) {
width = (Width)model.GetVocabulary().Index(word);
out.write(&width, sizeof(Width));
}
if (!in.ReadLineOrEOF(word)) break;
out.write(&end_sentence, sizeof(Width));
}
}
template <class Model, class Width> class Worker {
public:
explicit Worker(const Model &model, double &add_total) : model_(model), total_(0.0), add_total_(add_total) {}
// Destructors happen in the main thread, so there's no race for add_total_.
~Worker() { add_total_ += total_; }
typedef boost::iterator_range<Width *> Request;
void operator()(Request request) {
const lm::ngram::State *const begin_state = &model_.BeginSentenceState();
const lm::ngram::State *next_state = begin_state;
const Width kEOS = model_.GetVocabulary().EndSentence();
float sum = 0.0;
// Do even stuff first.
const Width *even_end = request.begin() + (request.size() & ~1);
// Alternating states
const Width *i;
for (i = request.begin(); i != even_end;) {
sum += model_.FullScore(*next_state, *i, state_[1]).prob;
next_state = (*i++ == kEOS) ? begin_state : &state_[1];
sum += model_.FullScore(*next_state, *i, state_[0]).prob;
next_state = (*i++ == kEOS) ? begin_state : &state_[0];
}
// Odd corner case.
if (request.size() & 1) {
sum += model_.FullScore(*next_state, *i, state_[2]).prob;
next_state = (*i++ == kEOS) ? begin_state : &state_[2];
}
total_ += sum;
}
private:
const Model &model_;
double total_;
double &add_total_;
lm::ngram::State state_[3];
};
struct Config {
int fd_in;
std::size_t threads;
std::size_t buf_per_thread;
bool query;
};
template <class Model, class Width> void QueryFromBytes(const Model &model, const Config &config) {
util::FileStream out(1);
out << "Threads: " << config.threads << '\n';
const Width kEOS = model.GetVocabulary().EndSentence();
double total = 0.0;
// Number of items to have in queue in addition to everything in flight.
const std::size_t kInQueue = 3;
std::size_t total_queue = config.threads + kInQueue;
std::vector<Width> backing(config.buf_per_thread * total_queue);
double loaded_cpu;
double loaded_wall;
uint64_t queries = 0;
{
util::RecyclingThreadPool<Worker<Model, Width> > pool(total_queue, config.threads, Worker<Model, Width>(model, total), boost::iterator_range<Width *>((Width*)0, (Width*)0));
for (std::size_t i = 0; i < total_queue; ++i) {
pool.PopulateRecycling(boost::iterator_range<Width *>(&backing[i * config.buf_per_thread], &backing[i * config.buf_per_thread]));
}
loaded_cpu = util::CPUTime();
loaded_wall = util::WallTime();
out << "To Load, CPU: " << loaded_cpu << " Wall: " << loaded_wall << '\n';
boost::iterator_range<Width *> overhang((Width*)0, (Width*)0);
while (true) {
boost::iterator_range<Width *> buf = pool.Consume();
std::memmove(buf.begin(), overhang.begin(), overhang.size() * sizeof(Width));
std::size_t got = util::ReadOrEOF(config.fd_in, buf.begin() + overhang.size(), (config.buf_per_thread - overhang.size()) * sizeof(Width));
if (!got && overhang.empty()) break;
UTIL_THROW_IF2(got % sizeof(Width), "File size not a multiple of vocab id size " << sizeof(Width));
Width *read_end = buf.begin() + overhang.size() + got / sizeof(Width);
Width *last_eos;
for (last_eos = read_end - 1; ; --last_eos) {
UTIL_THROW_IF2(last_eos <= buf.begin(), "Encountered a sentence longer than the buffer size of " << config.buf_per_thread << " words. Rerun with increased buffer size. TODO: adaptable buffer");
if (*last_eos == kEOS) break;
}
buf = boost::iterator_range<Width*>(buf.begin(), last_eos + 1);
overhang = boost::iterator_range<Width*>(last_eos + 1, read_end);
queries += buf.size();
pool.Produce(buf);
}
} // Drain pool.
double after_cpu = util::CPUTime();
double after_wall = util::WallTime();
util::FileStream(2, 70) << "Probability sum: " << total << '\n';
out << "Queries: " << queries << '\n';
out << "Excluding load, CPU: " << (after_cpu - loaded_cpu) << " Wall: " << (after_wall - loaded_wall) << '\n';
double cpu_per_entry = ((after_cpu - loaded_cpu) / static_cast<double>(queries));
double wall_per_entry = ((after_wall - loaded_wall) / static_cast<double>(queries));
out << "Seconds per query excluding load, CPU: " << cpu_per_entry << " Wall: " << wall_per_entry << '\n';
out << "Queries per second excluding load, CPU: " << (1.0/cpu_per_entry) << " Wall: " << (1.0/wall_per_entry) << '\n';
out << "RSSMax: " << util::RSSMax() << '\n';
}
template <class Model, class Width> void DispatchFunction(const Model &model, const Config &config) {
if (config.query) {
QueryFromBytes<Model, Width>(model, config);
} else {
ConvertToBytes<Model, Width>(model, config.fd_in);
}
}
template <class Model> void DispatchWidth(const char *file, const Config &config) {
lm::ngram::Config model_config;
model_config.load_method = util::READ;
Model model(file, model_config);
uint64_t bound = model.GetVocabulary().Bound();
if (bound <= 256) {
DispatchFunction<Model, uint8_t>(model, config);
} else if (bound <= 65536) {
DispatchFunction<Model, uint16_t>(model, config);
} else if (bound <= (1ULL << 32)) {
DispatchFunction<Model, uint32_t>(model, config);
} else {
DispatchFunction<Model, uint64_t>(model, config);
}
}
void Dispatch(const char *file, const Config &config) {
using namespace lm::ngram;
lm::ngram::ModelType model_type;
if (lm::ngram::RecognizeBinary(file, model_type)) {
switch(model_type) {
case PROBING:
DispatchWidth<lm::ngram::ProbingModel>(file, config);
break;
case REST_PROBING:
DispatchWidth<lm::ngram::RestProbingModel>(file, config);
break;
case TRIE:
DispatchWidth<lm::ngram::TrieModel>(file, config);
break;
case QUANT_TRIE:
DispatchWidth<lm::ngram::QuantTrieModel>(file, config);
break;
case ARRAY_TRIE:
DispatchWidth<lm::ngram::ArrayTrieModel>(file, config);
break;
case QUANT_ARRAY_TRIE:
DispatchWidth<lm::ngram::QuantArrayTrieModel>(file, config);
break;
default:
UTIL_THROW(util::Exception, "Unrecognized kenlm model type " << model_type);
}
} else {
UTIL_THROW(util::Exception, "Binarize before running benchmarks.");
}
}
} // namespace
int main(int argc, char *argv[]) {
try {
Config config;
config.fd_in = 0;
std::string model;
namespace po = boost::program_options;
po::options_description options("Benchmark options");
options.add_options()
("help,h", po::bool_switch(), "Show help message")
("model,m", po::value<std::string>(&model)->required(), "Model to query or convert vocab ids")
("threads,t", po::value<std::size_t>(&config.threads)->default_value(boost::thread::hardware_concurrency()), "Threads to use (querying only; TODO vocab conversion)")
("buffer,b", po::value<std::size_t>(&config.buf_per_thread)->default_value(4096), "Number of words to buffer per task.")
("vocab,v", po::bool_switch(), "Convert strings to vocab ids")
("query,q", po::bool_switch(), "Query from vocab ids");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, options), vm);
if (argc == 1 || vm["help"].as<bool>()) {
std::cerr << "Benchmark program for KenLM. Intended usage:\n"
<< "#Convert text to vocabulary ids offline. These ids are tied to a model.\n"
<< argv[0] << " -v -m $model <$text >$text.vocab\n"
<< "#Ensure files are in RAM.\n"
<< "cat $text.vocab $model >/dev/null\n"
<< "#Timed query against the model.\n"
<< argv[0] << " -q -m $model <$text.vocab\n";
return 0;
}
po::notify(vm);
if (!(vm["vocab"].as<bool>() ^ vm["query"].as<bool>())) {
std::cerr << "Specify exactly one of -v (vocab conversion) or -q (query)." << std::endl;
return 0;
}
config.query = vm["query"].as<bool>();
if (!config.threads) {
std::cerr << "Specify a non-zero number of threads with -t." << std::endl;
}
Dispatch(model.c_str(), config);
} catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}

View File

@ -0,0 +1,216 @@
/* Efficient left and right language model state for sentence fragments.
* Intended usage:
* Store ChartState with every chart entry.
* To do a rule application:
* 1. Make a ChartState object for your new entry.
* 2. Construct RuleScore.
* 3. Going from left to right, call Terminal or NonTerminal.
* For terminals, just pass the vocab id.
* For non-terminals, pass that non-terminal's ChartState.
* If your decoder expects scores inclusive of subtree scores (i.e. you
* label entries with the highest-scoring path), pass the non-terminal's
* score as prob.
* If your decoder expects relative scores and will walk the chart later,
* pass prob = 0.0.
* In other words, the only effect of prob is that it gets added to the
* returned log probability.
* 4. Call Finish. It returns the log probability.
*
* There's a couple more details:
* Do not pass <s> to Terminal as it is formally not a word in the sentence,
* only context. Instead, call BeginSentence. If called, it should be the
* first call after RuleScore is constructed (since <s> is always the
* leftmost).
*
* If the leftmost RHS is a non-terminal, it's faster to call BeginNonTerminal.
*
* Hashing and sorting comparison operators are provided. All state objects
* are POD. If you intend to use memcmp on raw state objects, you must call
* ZeroRemaining first, as the value of array entries beyond length is
* otherwise undefined.
*
* Usage is of course not limited to chart decoding. Anything that generates
* sentence fragments missing left context could benefit. For example, a
* phrase-based decoder could pre-score phrases, storing ChartState with each
* phrase, even if hypotheses are generated left-to-right.
*/
#ifndef LM_LEFT_H
#define LM_LEFT_H
#include "lm/max_order.hh"
#include "lm/state.hh"
#include "lm/return.hh"
#include "util/murmur_hash.hh"
#include <algorithm>
namespace lm {
namespace ngram {
template <class M> class RuleScore {
public:
explicit RuleScore(const M &model, ChartState &out) : model_(model), out_(&out), left_done_(false), prob_(0.0) {
out.left.length = 0;
out.right.length = 0;
}
void BeginSentence() {
out_->right = model_.BeginSentenceState();
// out_->left is empty.
left_done_ = true;
}
void Terminal(WordIndex word) {
State copy(out_->right);
FullScoreReturn ret(model_.FullScore(copy, word, out_->right));
if (left_done_) { prob_ += ret.prob; return; }
if (ret.independent_left) {
prob_ += ret.prob;
left_done_ = true;
return;
}
out_->left.pointers[out_->left.length++] = ret.extend_left;
prob_ += ret.rest;
if (out_->right.length != copy.length + 1)
left_done_ = true;
}
// Faster version of NonTerminal for the case where the rule begins with a non-terminal.
void BeginNonTerminal(const ChartState &in, float prob = 0.0) {
prob_ = prob;
*out_ = in;
left_done_ = in.left.full;
}
void NonTerminal(const ChartState &in, float prob = 0.0) {
prob_ += prob;
if (!in.left.length) {
if (in.left.full) {
for (const float *i = out_->right.backoff; i < out_->right.backoff + out_->right.length; ++i) prob_ += *i;
left_done_ = true;
out_->right = in.right;
}
return;
}
if (!out_->right.length) {
out_->right = in.right;
if (left_done_) {
prob_ += model_.UnRest(in.left.pointers, in.left.pointers + in.left.length, 1);
return;
}
if (out_->left.length) {
left_done_ = true;
} else {
out_->left = in.left;
left_done_ = in.left.full;
}
return;
}
float backoffs[KENLM_MAX_ORDER - 1], backoffs2[KENLM_MAX_ORDER - 1];
float *back = backoffs, *back2 = backoffs2;
unsigned char next_use = out_->right.length;
// First word
if (ExtendLeft(in, next_use, 1, out_->right.backoff, back)) return;
// Words after the first, so extending a bigram to begin with
for (unsigned char extend_length = 2; extend_length <= in.left.length; ++extend_length) {
if (ExtendLeft(in, next_use, extend_length, back, back2)) return;
std::swap(back, back2);
}
if (in.left.full) {
for (const float *i = back; i != back + next_use; ++i) prob_ += *i;
left_done_ = true;
out_->right = in.right;
return;
}
// Right state was minimized, so it's already independent of the new words to the left.
if (in.right.length < in.left.length) {
out_->right = in.right;
return;
}
// Shift exisiting words down.
for (WordIndex *i = out_->right.words + next_use - 1; i >= out_->right.words; --i) {
*(i + in.right.length) = *i;
}
// Add words from in.right.
std::copy(in.right.words, in.right.words + in.right.length, out_->right.words);
// Assemble backoff composed on the existing state's backoff followed by the new state's backoff.
std::copy(in.right.backoff, in.right.backoff + in.right.length, out_->right.backoff);
std::copy(back, back + next_use, out_->right.backoff + in.right.length);
out_->right.length = in.right.length + next_use;
}
float Finish() {
// A N-1-gram might extend left and right but we should still set full to true because it's an N-1-gram.
out_->left.full = left_done_ || (out_->left.length == model_.Order() - 1);
return prob_;
}
void Reset() {
prob_ = 0.0;
left_done_ = false;
out_->left.length = 0;
out_->right.length = 0;
}
void Reset(ChartState &replacement) {
out_ = &replacement;
Reset();
}
private:
bool ExtendLeft(const ChartState &in, unsigned char &next_use, unsigned char extend_length, const float *back_in, float *back_out) {
ProcessRet(model_.ExtendLeft(
out_->right.words, out_->right.words + next_use, // Words to extend into
back_in, // Backoffs to use
in.left.pointers[extend_length - 1], extend_length, // Words to be extended
back_out, // Backoffs for the next score
next_use)); // Length of n-gram to use in next scoring.
if (next_use != out_->right.length) {
left_done_ = true;
if (!next_use) {
// Early exit.
out_->right = in.right;
prob_ += model_.UnRest(in.left.pointers + extend_length, in.left.pointers + in.left.length, extend_length + 1);
return true;
}
}
// Continue scoring.
return false;
}
void ProcessRet(const FullScoreReturn &ret) {
if (left_done_) {
prob_ += ret.prob;
return;
}
if (ret.independent_left) {
prob_ += ret.prob;
left_done_ = true;
return;
}
out_->left.pointers[out_->left.length++] = ret.extend_left;
prob_ += ret.rest;
}
const M &model_;
ChartState *out_;
bool left_done_;
float prob_;
};
} // namespace ngram
} // namespace lm
#endif // LM_LEFT_H

View File

@ -0,0 +1,397 @@
#include "lm/left.hh"
#include "lm/model.hh"
#include "util/tokenize_piece.hh"
#include <vector>
#define BOOST_TEST_MODULE LeftTest
#include <boost/test/unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>
namespace lm {
namespace ngram {
namespace {
#define Term(word) score.Terminal(m.GetVocabulary().Index(word));
#define VCheck(word, value) BOOST_CHECK_EQUAL(m.GetVocabulary().Index(word), value);
// Apparently some Boost versions use templates and are pretty strict about types matching.
#define SLOPPY_CHECK_CLOSE(ref, value, tol) BOOST_CHECK_CLOSE(static_cast<double>(ref), static_cast<double>(value), static_cast<double>(tol));
template <class M> void Short(const M &m) {
ChartState base;
{
RuleScore<M> score(m, base);
Term("more");
Term("loin");
SLOPPY_CHECK_CLOSE(-1.206319 - 0.3561665, score.Finish(), 0.001);
}
BOOST_CHECK(base.left.full);
BOOST_CHECK_EQUAL(2, base.left.length);
BOOST_CHECK_EQUAL(1, base.right.length);
VCheck("loin", base.right.words[0]);
ChartState more_left;
{
RuleScore<M> score(m, more_left);
Term("little");
score.NonTerminal(base, -1.206319 - 0.3561665);
// p(little more loin | null context)
SLOPPY_CHECK_CLOSE(-1.56538, score.Finish(), 0.001);
}
BOOST_CHECK_EQUAL(3, more_left.left.length);
BOOST_CHECK_EQUAL(1, more_left.right.length);
VCheck("loin", more_left.right.words[0]);
BOOST_CHECK(more_left.left.full);
ChartState shorter;
{
RuleScore<M> score(m, shorter);
Term("to");
score.NonTerminal(base, -1.206319 - 0.3561665);
SLOPPY_CHECK_CLOSE(-0.30103 - 1.687872 - 1.206319 - 0.3561665, score.Finish(), 0.01);
}
BOOST_CHECK_EQUAL(1, shorter.left.length);
BOOST_CHECK_EQUAL(1, shorter.right.length);
VCheck("loin", shorter.right.words[0]);
BOOST_CHECK(shorter.left.full);
}
template <class M> void Charge(const M &m) {
ChartState base;
{
RuleScore<M> score(m, base);
Term("on");
Term("more");
SLOPPY_CHECK_CLOSE(-1.509559 -0.4771212 -1.206319, score.Finish(), 0.001);
}
BOOST_CHECK_EQUAL(1, base.left.length);
BOOST_CHECK_EQUAL(1, base.right.length);
VCheck("more", base.right.words[0]);
BOOST_CHECK(base.left.full);
ChartState extend;
{
RuleScore<M> score(m, extend);
Term("looking");
score.NonTerminal(base, -1.509559 -0.4771212 -1.206319);
SLOPPY_CHECK_CLOSE(-3.91039, score.Finish(), 0.001);
}
BOOST_CHECK_EQUAL(2, extend.left.length);
BOOST_CHECK_EQUAL(1, extend.right.length);
VCheck("more", extend.right.words[0]);
BOOST_CHECK(extend.left.full);
ChartState tobos;
{
RuleScore<M> score(m, tobos);
score.BeginSentence();
score.NonTerminal(extend, -3.91039);
SLOPPY_CHECK_CLOSE(-3.471169, score.Finish(), 0.001);
}
BOOST_CHECK_EQUAL(0, tobos.left.length);
BOOST_CHECK_EQUAL(1, tobos.right.length);
}
template <class M> float LeftToRight(const M &m, const std::vector<WordIndex> &words, bool begin_sentence = false) {
float ret = 0.0;
State right = begin_sentence ? m.BeginSentenceState() : m.NullContextState();
for (std::vector<WordIndex>::const_iterator i = words.begin(); i != words.end(); ++i) {
State copy(right);
ret += m.Score(copy, *i, right);
}
return ret;
}
template <class M> float RightToLeft(const M &m, const std::vector<WordIndex> &words, bool begin_sentence = false) {
float ret = 0.0;
ChartState state;
state.left.length = 0;
state.right.length = 0;
state.left.full = false;
for (std::vector<WordIndex>::const_reverse_iterator i = words.rbegin(); i != words.rend(); ++i) {
ChartState copy(state);
RuleScore<M> score(m, state);
score.Terminal(*i);
score.NonTerminal(copy, ret);
ret = score.Finish();
}
if (begin_sentence) {
ChartState copy(state);
RuleScore<M> score(m, state);
score.BeginSentence();
score.NonTerminal(copy, ret);
ret = score.Finish();
}
return ret;
}
template <class M> float TreeMiddle(const M &m, const std::vector<WordIndex> &words, bool begin_sentence = false) {
std::vector<std::pair<ChartState, float> > states(words.size());
for (unsigned int i = 0; i < words.size(); ++i) {
RuleScore<M> score(m, states[i].first);
score.Terminal(words[i]);
states[i].second = score.Finish();
}
while (states.size() > 1) {
std::vector<std::pair<ChartState, float> > upper((states.size() + 1) / 2);
for (unsigned int i = 0; i < states.size() / 2; ++i) {
RuleScore<M> score(m, upper[i].first);
score.NonTerminal(states[i*2].first, states[i*2].second);
score.NonTerminal(states[i*2+1].first, states[i*2+1].second);
upper[i].second = score.Finish();
}
if (states.size() % 2) {
upper.back() = states.back();
}
std::swap(states, upper);
}
if (states.empty()) return 0.0;
if (begin_sentence) {
ChartState ignored;
RuleScore<M> score(m, ignored);
score.BeginSentence();
score.NonTerminal(states.front().first, states.front().second);
return score.Finish();
} else {
return states.front().second;
}
}
template <class M> void LookupVocab(const M &m, const StringPiece &str, std::vector<WordIndex> &out) {
out.clear();
for (util::TokenIter<util::SingleCharacter, true> i(str, ' '); i; ++i) {
out.push_back(m.GetVocabulary().Index(*i));
}
}
#define TEXT_TEST(str) \
LookupVocab(m, str, words); \
expect = LeftToRight(m, words, rest); \
SLOPPY_CHECK_CLOSE(expect, RightToLeft(m, words, rest), 0.001); \
SLOPPY_CHECK_CLOSE(expect, TreeMiddle(m, words, rest), 0.001); \
// Build sentences, or parts thereof, from right to left.
template <class M> void GrowBig(const M &m, bool rest = false) {
std::vector<WordIndex> words;
float expect;
TEXT_TEST("in biarritz watching considering looking . on a little more loin also would consider higher to look good unknown the screening foo bar , unknown however unknown </s>");
TEXT_TEST("on a little more loin also would consider higher to look good unknown the screening foo bar , unknown however unknown </s>");
TEXT_TEST("on a little more loin also would consider higher to look good");
TEXT_TEST("more loin also would consider higher to look good");
TEXT_TEST("more loin also would consider higher to look");
TEXT_TEST("also would consider higher to look");
TEXT_TEST("also would consider higher");
TEXT_TEST("would consider higher to look");
TEXT_TEST("consider higher to look");
TEXT_TEST("consider higher to");
TEXT_TEST("consider higher");
}
template <class M> void GrowSmall(const M &m, bool rest = false) {
std::vector<WordIndex> words;
float expect;
TEXT_TEST("in biarritz watching considering looking . </s>");
TEXT_TEST("in biarritz watching considering looking .");
TEXT_TEST("in biarritz");
}
template <class M> void AlsoWouldConsiderHigher(const M &m) {
ChartState also;
{
RuleScore<M> score(m, also);
score.Terminal(m.GetVocabulary().Index("also"));
SLOPPY_CHECK_CLOSE(-1.687872, score.Finish(), 0.001);
}
ChartState would;
{
RuleScore<M> score(m, would);
score.Terminal(m.GetVocabulary().Index("would"));
SLOPPY_CHECK_CLOSE(-1.687872, score.Finish(), 0.001);
}
ChartState combine_also_would;
{
RuleScore<M> score(m, combine_also_would);
score.NonTerminal(also, -1.687872);
score.NonTerminal(would, -1.687872);
SLOPPY_CHECK_CLOSE(-1.687872 - 2.0, score.Finish(), 0.001);
}
BOOST_CHECK_EQUAL(2, combine_also_would.right.length);
ChartState also_would;
{
RuleScore<M> score(m, also_would);
score.Terminal(m.GetVocabulary().Index("also"));
score.Terminal(m.GetVocabulary().Index("would"));
SLOPPY_CHECK_CLOSE(-1.687872 - 2.0, score.Finish(), 0.001);
}
BOOST_CHECK_EQUAL(2, also_would.right.length);
ChartState consider;
{
RuleScore<M> score(m, consider);
score.Terminal(m.GetVocabulary().Index("consider"));
SLOPPY_CHECK_CLOSE(-1.687872, score.Finish(), 0.001);
}
BOOST_CHECK_EQUAL(1, consider.left.length);
BOOST_CHECK_EQUAL(1, consider.right.length);
BOOST_CHECK(!consider.left.full);
ChartState higher;
float higher_score;
{
RuleScore<M> score(m, higher);
score.Terminal(m.GetVocabulary().Index("higher"));
higher_score = score.Finish();
}
SLOPPY_CHECK_CLOSE(-1.509559, higher_score, 0.001);
BOOST_CHECK_EQUAL(1, higher.left.length);
BOOST_CHECK_EQUAL(1, higher.right.length);
BOOST_CHECK(!higher.left.full);
VCheck("higher", higher.right.words[0]);
SLOPPY_CHECK_CLOSE(-0.30103, higher.right.backoff[0], 0.001);
ChartState consider_higher;
{
RuleScore<M> score(m, consider_higher);
score.NonTerminal(consider, -1.687872);
score.NonTerminal(higher, higher_score);
SLOPPY_CHECK_CLOSE(-1.509559 - 1.687872 - 0.30103, score.Finish(), 0.001);
}
BOOST_CHECK_EQUAL(2, consider_higher.left.length);
BOOST_CHECK(!consider_higher.left.full);
ChartState full;
{
RuleScore<M> score(m, full);
score.NonTerminal(combine_also_would, -1.687872 - 2.0);
score.NonTerminal(consider_higher, -1.509559 - 1.687872 - 0.30103);
SLOPPY_CHECK_CLOSE(-10.6879, score.Finish(), 0.001);
}
BOOST_CHECK_EQUAL(4, full.right.length);
}
#define CHECK_SCORE(str, val) \
{ \
float got = val; \
std::vector<WordIndex> indices; \
LookupVocab(m, str, indices); \
SLOPPY_CHECK_CLOSE(LeftToRight(m, indices), got, 0.001); \
}
template <class M> void FullGrow(const M &m) {
std::vector<WordIndex> words;
LookupVocab(m, "in biarritz watching considering looking . </s>", words);
ChartState lexical[7];
float lexical_scores[7];
for (unsigned int i = 0; i < 7; ++i) {
RuleScore<M> score(m, lexical[i]);
score.Terminal(words[i]);
lexical_scores[i] = score.Finish();
}
CHECK_SCORE("in", lexical_scores[0]);
CHECK_SCORE("biarritz", lexical_scores[1]);
CHECK_SCORE("watching", lexical_scores[2]);
CHECK_SCORE("</s>", lexical_scores[6]);
ChartState l1[4];
float l1_scores[4];
{
RuleScore<M> score(m, l1[0]);
score.NonTerminal(lexical[0], lexical_scores[0]);
score.NonTerminal(lexical[1], lexical_scores[1]);
CHECK_SCORE("in biarritz", l1_scores[0] = score.Finish());
}
{
RuleScore<M> score(m, l1[1]);
score.NonTerminal(lexical[2], lexical_scores[2]);
score.NonTerminal(lexical[3], lexical_scores[3]);
CHECK_SCORE("watching considering", l1_scores[1] = score.Finish());
}
{
RuleScore<M> score(m, l1[2]);
score.NonTerminal(lexical[4], lexical_scores[4]);
score.NonTerminal(lexical[5], lexical_scores[5]);
CHECK_SCORE("looking .", l1_scores[2] = score.Finish());
}
BOOST_CHECK_EQUAL(l1[2].left.length, 1);
l1[3] = lexical[6];
l1_scores[3] = lexical_scores[6];
ChartState l2[2];
float l2_scores[2];
{
RuleScore<M> score(m, l2[0]);
score.NonTerminal(l1[0], l1_scores[0]);
score.NonTerminal(l1[1], l1_scores[1]);
CHECK_SCORE("in biarritz watching considering", l2_scores[0] = score.Finish());
}
{
RuleScore<M> score(m, l2[1]);
score.NonTerminal(l1[2], l1_scores[2]);
score.NonTerminal(l1[3], l1_scores[3]);
CHECK_SCORE("looking . </s>", l2_scores[1] = score.Finish());
}
BOOST_CHECK_EQUAL(l2[1].left.length, 1);
BOOST_CHECK(l2[1].left.full);
ChartState top;
{
RuleScore<M> score(m, top);
score.NonTerminal(l2[0], l2_scores[0]);
score.NonTerminal(l2[1], l2_scores[1]);
CHECK_SCORE("in biarritz watching considering looking . </s>", score.Finish());
}
}
const char *FileLocation() {
if (boost::unit_test::framework::master_test_suite().argc < 2) {
return "test.arpa";
}
return boost::unit_test::framework::master_test_suite().argv[1];
}
template <class M> void Everything() {
Config config;
config.messages = NULL;
M m(FileLocation(), config);
Short(m);
Charge(m);
GrowBig(m);
AlsoWouldConsiderHigher(m);
GrowSmall(m);
FullGrow(m);
}
BOOST_AUTO_TEST_CASE(ProbingAll) {
Everything<Model>();
}
BOOST_AUTO_TEST_CASE(TrieAll) {
Everything<TrieModel>();
}
BOOST_AUTO_TEST_CASE(QuantTrieAll) {
Everything<QuantTrieModel>();
}
BOOST_AUTO_TEST_CASE(ArrayQuantTrieAll) {
Everything<QuantArrayTrieModel>();
}
BOOST_AUTO_TEST_CASE(ArrayTrieAll) {
Everything<ArrayTrieModel>();
}
BOOST_AUTO_TEST_CASE(RestProbing) {
Config config;
config.messages = NULL;
RestProbingModel m(FileLocation(), config);
GrowBig(m, true);
}
} // namespace
} // namespace ngram
} // namespace lm

View File

@ -0,0 +1,23 @@
#include "lm/lm_exception.hh"
#include <cerrno>
#include <cstdio>
namespace lm {
ConfigException::ConfigException() throw() {}
ConfigException::~ConfigException() throw() {}
LoadException::LoadException() throw() {}
LoadException::~LoadException() throw() {}
FormatLoadException::FormatLoadException() throw() {}
FormatLoadException::~FormatLoadException() throw() {}
VocabLoadException::VocabLoadException() throw() {}
VocabLoadException::~VocabLoadException() throw() {}
SpecialWordMissingException::SpecialWordMissingException() throw() {}
SpecialWordMissingException::~SpecialWordMissingException() throw() {}
} // namespace lm

View File

@ -0,0 +1,50 @@
#ifndef LM_LM_EXCEPTION_H
#define LM_LM_EXCEPTION_H
// Named to avoid conflict with util/exception.hh.
#include "util/exception.hh"
#include "util/string_piece.hh"
#include <exception>
#include <string>
namespace lm {
typedef enum {THROW_UP, COMPLAIN, SILENT} WarningAction;
class ConfigException : public util::Exception {
public:
ConfigException() throw();
~ConfigException() throw();
};
class LoadException : public util::Exception {
public:
virtual ~LoadException() throw();
protected:
LoadException() throw();
};
class FormatLoadException : public LoadException {
public:
FormatLoadException() throw();
~FormatLoadException() throw();
};
class VocabLoadException : public LoadException {
public:
virtual ~VocabLoadException() throw();
VocabLoadException() throw();
};
class SpecialWordMissingException : public VocabLoadException {
public:
explicit SpecialWordMissingException() throw();
~SpecialWordMissingException() throw();
};
} // namespace lm
#endif // LM_LM_EXCEPTION

Some files were not shown because too many files have changed in this diff Show More