mirror of
https://github.com/moses-smt/mosesdecoder.git
synced 2024-08-17 07:20:48 +03:00
yanggao-softdep-hiero-v0
git-svn-id: https://mosesdecoder.svn.sourceforge.net/svnroot/mosesdecoder/branches/yanggao_maxent@4123 1f5c12ca-751b-0410-a591-d2e778427230
This commit is contained in:
parent
0016c3012f
commit
222b425762
49
trunk/.gitignore
vendored
Normal file
49
trunk/.gitignore
vendored
Normal file
@ -0,0 +1,49 @@
|
||||
*.[oa]
|
||||
*.la
|
||||
*.lo
|
||||
*.Po
|
||||
*~
|
||||
CreateOnDisk/src/CreateOnDiskPt
|
||||
Makefile
|
||||
Makefile.in
|
||||
aclocal.m4
|
||||
autom4te.cache/
|
||||
config.h
|
||||
config.log
|
||||
config.status
|
||||
configure
|
||||
kenlm/.deps/
|
||||
kenlm/.libs/
|
||||
kenlm/build_binary
|
||||
kenlm/query
|
||||
libtool
|
||||
mert/.deps/
|
||||
mert/Makefile
|
||||
mert/Makefile.in
|
||||
mert/extractor
|
||||
mert/mert
|
||||
misc/.deps/
|
||||
misc/Makefile
|
||||
misc/Makefile.in
|
||||
misc/processLexicalTable
|
||||
misc/processPhraseTable
|
||||
misc/queryLexicalTable
|
||||
misc/queryPhraseTable
|
||||
moses-chart/src/.deps/
|
||||
moses-chart-cmd/src/moses_chart
|
||||
moses-cmd/src/.deps/
|
||||
moses-cmd/src/Makefile
|
||||
moses-cmd/src/Makefile.in
|
||||
moses-cmd/src/checkplf
|
||||
moses-cmd/src/lmbrgrid
|
||||
moses-cmd/src/moses
|
||||
moses/src/.deps/
|
||||
moses/src/.libs/
|
||||
moses/src/Makefile
|
||||
moses/src/Makefile.in
|
||||
scripts/training/cmert-0.5/mert
|
||||
scripts/training/mbr/mbr
|
||||
scripts/training/phrase-extract/extract
|
||||
scripts/training/phrase-extract/score
|
||||
scripts/training/symal/symal
|
||||
stamp-h1
|
93
trunk/BUILD-INSTRUCTIONS.txt
Normal file
93
trunk/BUILD-INSTRUCTIONS.txt
Normal file
@ -0,0 +1,93 @@
|
||||
0) Preliminaries
|
||||
|
||||
Before building you need to decide what language model toolkit (SRI's,
|
||||
IRST's, or Ken's) you want to use.
|
||||
|
||||
If you want to use SRI's, you will need to download its source
|
||||
and build it. The SRILM can be downloaded from
|
||||
http://www.speech.sri.com/projects/srilm/download.html .
|
||||
|
||||
|
||||
If you want to use IRST's, you will need to download its source and
|
||||
build it. The IRSTLM can be downloaded from either the SourceForge
|
||||
website
|
||||
http://sourceforge.net/projects/irstlm
|
||||
or the official IRSTLM website
|
||||
http://hlt.fbk.eu/en/irstlm
|
||||
|
||||
|
||||
Ken's LM is included with the Moses distribution.
|
||||
|
||||
IMPORTANT: These instructions are for building the moses decoder ONLY,
|
||||
the training and tuning SCRIPTS contained in scripts/ must be built
|
||||
and installed separately. Also, they may require modification to
|
||||
work in certain environments.
|
||||
|
||||
Versions 1.9 (or higher) of aclocal and automake are required.
|
||||
|
||||
For Mac OSX users:
|
||||
Standard distribution usually includes versions 1.6.
|
||||
Get correct versions, and set the environment variables ACLOCAL and
|
||||
AUTOMAKE to the correct paths in ./regenerate-makefiles.sh.
|
||||
|
||||
--------------------------------------------------------------------------
|
||||
|
||||
1) Instructions for building with SRILM
|
||||
|
||||
Build SRILM according to their release instructions. Make sure that
|
||||
you DO NOT override the MACHINE_TYPE variable on the command line when
|
||||
you do so, as this can lead to problems locating the library.
|
||||
|
||||
./regenerate-makefiles.sh
|
||||
./configure [--with-srilm=/path/to/srilm] [--with-irstlm=/path/to/irstlm]
|
||||
|
||||
The resulting decoder binary will be moses-cmd/src/moses .
|
||||
|
||||
--------------------------------------------------------------------------
|
||||
|
||||
2) Instructions for building with IRSTLM
|
||||
|
||||
Build IRSTLM according to its release instructions. Make sure that
|
||||
you DO NOT override the MACHINE_TYPE variable on the command line when
|
||||
you do so, as this can lead to problems locating the library.
|
||||
|
||||
./regenerate-makefiles.sh
|
||||
./configure [--with-srilm=/path/to/srilm] [--with-irstlm=/path/to/irstlm]
|
||||
|
||||
The resulting decoder binary will be moses-cmd/src/moses .
|
||||
|
||||
--------------------------------------------------------------------------
|
||||
|
||||
3) Instructions for building with Ken's LM
|
||||
|
||||
./regenerate-makefiles.sh
|
||||
./configure
|
||||
|
||||
The resulting decoder binary will be moses-cmd/src/moses .
|
||||
Use language model 8 in your moses.ini:
|
||||
[lmodel-file]
|
||||
8 0 2 /path/to/lm.arpa
|
||||
|
||||
If you don't want Ken's LM, ./configure --without-kenlm
|
||||
|
||||
--------------------------------------------------------------------------
|
||||
|
||||
|
||||
|
||||
ALTERNATIVE WAYS TO BUILD ON UNIX AND OTHER PLATFORMS
|
||||
|
||||
Microsoft Windows
|
||||
-----------------
|
||||
Tested on 32-bit Windows XP and Vista using Visual Studio 2005.
|
||||
Again, refer to the old manual
|
||||
http://homepages.inf.ed.ac.uk/s0565741/papers/developers-manual.pdf
|
||||
The Windows build doesn't use the SRI or IRST language model libraries as they can't be compiled
|
||||
under Windows using Visual Studio. Instead, an internal language model, which behave like SRILM is used,
|
||||
however, it can only handle up to trigrams.
|
||||
|
||||
Binaries for all external libraries needed can be downloaded from
|
||||
http://www.statmt.org/moses/?n=Moses.LibrariesUsed
|
||||
|
||||
Only the decoder is developed and tested under Windows. There are difficulties using the training scripts under Windows, even with Cygwin.
|
||||
|
||||
|
106
trunk/CreateOnDisk/CreateOnDisk.vcxproj
Normal file
106
trunk/CreateOnDisk/CreateOnDisk.vcxproj
Normal file
@ -0,0 +1,106 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>{88AE90C9-72D2-42ED-8389-770ACDCD4308}</ProjectGuid>
|
||||
<RootNamespace>CreateOnDisk</RootNamespace>
|
||||
<Keyword>Win32Proj</Keyword>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup>
|
||||
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<MinimalRebuild>true</MinimalRebuild>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<AdditionalDependencies>zlib.lib;$(OutDir)moses.lib;$(OutDir)OnDiskPt.lib</AdditionalDependencies>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<TargetMachine>MachineX86</TargetMachine>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<AdditionalDependencies>zlib.lib;$(OutDir)moses.lib;$(OutDir)OnDiskPt.lib</AdditionalDependencies>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<TargetMachine>MachineX86</TargetMachine>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="src\Main.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="src\Main.h" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\moses\moses.vcxproj">
|
||||
<Project>{8122157a-0de5-44ff-8e5b-024ed6ace7af}</Project>
|
||||
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\OnDiskPt\OnDiskPt.vcxproj">
|
||||
<Project>{8b07671b-cbaf-4514-affd-ce238cd427e9}</Project>
|
||||
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
</Project>
|
344
trunk/CreateOnDisk/CreateOnDisk.xcodeproj/project.pbxproj
Normal file
344
trunk/CreateOnDisk/CreateOnDisk.xcodeproj/project.pbxproj
Normal file
@ -0,0 +1,344 @@
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 45;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
1ED4FB4B11BDBAA7004E826A /* Main.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1ED4FB4911BDBAA7004E826A /* Main.cpp */; };
|
||||
1ED4FB6011BDBAFB004E826A /* libOnDiskPt.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1ED4FB5F11BDBAE6004E826A /* libOnDiskPt.a */; };
|
||||
1ED4FB6111BDBB00004E826A /* libmoses.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1ED4FB5611BDBAD7004E826A /* libmoses.a */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
1ED4FB5511BDBAD7004E826A /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 1ED4FB4E11BDBAD7004E826A /* moses.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = D2AAC046055464E500DB518D;
|
||||
remoteInfo = moses;
|
||||
};
|
||||
1ED4FB5E11BDBAE6004E826A /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 1ED4FB5711BDBAE6004E826A /* OnDiskPt.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = D2AAC046055464E500DB518D;
|
||||
remoteInfo = OnDiskPt;
|
||||
};
|
||||
1ED4FB7211BDBC05004E826A /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 1ED4FB4E11BDBAD7004E826A /* moses.xcodeproj */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = D2AAC045055464E500DB518D;
|
||||
remoteInfo = moses;
|
||||
};
|
||||
1ED4FB7411BDBC09004E826A /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 1ED4FB5711BDBAE6004E826A /* OnDiskPt.xcodeproj */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = D2AAC045055464E500DB518D;
|
||||
remoteInfo = OnDiskPt;
|
||||
};
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
8DD76F690486A84900D96B5E /* CopyFiles */ = {
|
||||
isa = PBXCopyFilesBuildPhase;
|
||||
buildActionMask = 8;
|
||||
dstPath = /usr/share/man/man1/;
|
||||
dstSubfolderSpec = 0;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 1;
|
||||
};
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
1E4FC4861251FFBF00FB0D9D /* CreateOnDisk */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = CreateOnDisk; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
1ED4FB4911BDBAA7004E826A /* Main.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = Main.cpp; path = src/Main.cpp; sourceTree = "<group>"; };
|
||||
1ED4FB4A11BDBAA7004E826A /* Main.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Main.h; path = src/Main.h; sourceTree = "<group>"; };
|
||||
1ED4FB4E11BDBAD7004E826A /* moses.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = moses.xcodeproj; path = ../moses/moses.xcodeproj; sourceTree = SOURCE_ROOT; };
|
||||
1ED4FB5711BDBAE6004E826A /* OnDiskPt.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = OnDiskPt.xcodeproj; path = ../OnDiskPt/OnDiskPt.xcodeproj; sourceTree = SOURCE_ROOT; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
8DD76F660486A84900D96B5E /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
1ED4FB6111BDBB00004E826A /* libmoses.a in Frameworks */,
|
||||
1ED4FB6011BDBAFB004E826A /* libOnDiskPt.a in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
08FB7794FE84155DC02AAC07 /* CreateOnDisk */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1ED4FB5711BDBAE6004E826A /* OnDiskPt.xcodeproj */,
|
||||
1ED4FB4E11BDBAD7004E826A /* moses.xcodeproj */,
|
||||
08FB7795FE84155DC02AAC07 /* Source */,
|
||||
C6859E8C029090F304C91782 /* Documentation */,
|
||||
1AB674ADFE9D54B511CA2CBB /* Products */,
|
||||
);
|
||||
name = CreateOnDisk;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
08FB7795FE84155DC02AAC07 /* Source */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1ED4FB4911BDBAA7004E826A /* Main.cpp */,
|
||||
1ED4FB4A11BDBAA7004E826A /* Main.h */,
|
||||
);
|
||||
name = Source;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
1AB674ADFE9D54B511CA2CBB /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1E4FC4861251FFBF00FB0D9D /* CreateOnDisk */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
1ED4FB4F11BDBAD7004E826A /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1ED4FB5611BDBAD7004E826A /* libmoses.a */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
1ED4FB5811BDBAE6004E826A /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1ED4FB5F11BDBAE6004E826A /* libOnDiskPt.a */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
C6859E8C029090F304C91782 /* Documentation */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
);
|
||||
name = Documentation;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
8DD76F620486A84900D96B5E /* CreateOnDisk */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 1DEB923108733DC60010E9CD /* Build configuration list for PBXNativeTarget "CreateOnDisk" */;
|
||||
buildPhases = (
|
||||
8DD76F640486A84900D96B5E /* Sources */,
|
||||
8DD76F660486A84900D96B5E /* Frameworks */,
|
||||
8DD76F690486A84900D96B5E /* CopyFiles */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
1ED4FB7311BDBC05004E826A /* PBXTargetDependency */,
|
||||
1ED4FB7511BDBC09004E826A /* PBXTargetDependency */,
|
||||
);
|
||||
name = CreateOnDisk;
|
||||
productInstallPath = "$(HOME)/bin";
|
||||
productName = CreateOnDisk;
|
||||
productReference = 1E4FC4861251FFBF00FB0D9D /* CreateOnDisk */;
|
||||
productType = "com.apple.product-type.tool";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
08FB7793FE84155DC02AAC07 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
buildConfigurationList = 1DEB923508733DC60010E9CD /* Build configuration list for PBXProject "CreateOnDisk" */;
|
||||
compatibilityVersion = "Xcode 3.1";
|
||||
developmentRegion = English;
|
||||
hasScannedForEncodings = 1;
|
||||
knownRegions = (
|
||||
English,
|
||||
Japanese,
|
||||
French,
|
||||
German,
|
||||
);
|
||||
mainGroup = 08FB7794FE84155DC02AAC07 /* CreateOnDisk */;
|
||||
projectDirPath = "";
|
||||
projectReferences = (
|
||||
{
|
||||
ProductGroup = 1ED4FB4F11BDBAD7004E826A /* Products */;
|
||||
ProjectRef = 1ED4FB4E11BDBAD7004E826A /* moses.xcodeproj */;
|
||||
},
|
||||
{
|
||||
ProductGroup = 1ED4FB5811BDBAE6004E826A /* Products */;
|
||||
ProjectRef = 1ED4FB5711BDBAE6004E826A /* OnDiskPt.xcodeproj */;
|
||||
},
|
||||
);
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
8DD76F620486A84900D96B5E /* CreateOnDisk */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXReferenceProxy section */
|
||||
1ED4FB5611BDBAD7004E826A /* libmoses.a */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = archive.ar;
|
||||
path = libmoses.a;
|
||||
remoteRef = 1ED4FB5511BDBAD7004E826A /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
1ED4FB5F11BDBAE6004E826A /* libOnDiskPt.a */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = archive.ar;
|
||||
path = libOnDiskPt.a;
|
||||
remoteRef = 1ED4FB5E11BDBAE6004E826A /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
/* End PBXReferenceProxy section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
8DD76F640486A84900D96B5E /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
1ED4FB4B11BDBAA7004E826A /* Main.cpp in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXTargetDependency section */
|
||||
1ED4FB7311BDBC05004E826A /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = moses;
|
||||
targetProxy = 1ED4FB7211BDBC05004E826A /* PBXContainerItemProxy */;
|
||||
};
|
||||
1ED4FB7511BDBC09004E826A /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = OnDiskPt;
|
||||
targetProxy = 1ED4FB7411BDBC09004E826A /* PBXContainerItemProxy */;
|
||||
};
|
||||
/* End PBXTargetDependency section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
1DEB923208733DC60010E9CD /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
GCC_DYNAMIC_NO_PIC = NO;
|
||||
GCC_ENABLE_FIX_AND_CONTINUE = YES;
|
||||
GCC_MODEL_TUNING = G5;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
INSTALL_PATH = /usr/local/bin;
|
||||
LIBRARY_SEARCH_PATHS = (
|
||||
../irstlm/lib,
|
||||
../srilm/lib/macosx,
|
||||
../randlm/lib,
|
||||
../kenlm,
|
||||
);
|
||||
OTHER_LDFLAGS = (
|
||||
"-lz",
|
||||
"-lirstlm",
|
||||
"-lmisc",
|
||||
"-ldstruct",
|
||||
"-loolm",
|
||||
"-lflm",
|
||||
"-llattice",
|
||||
"-lkenlm",
|
||||
"-lrandlm",
|
||||
);
|
||||
PRODUCT_NAME = CreateOnDisk;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
1DEB923308733DC60010E9CD /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
GCC_MODEL_TUNING = G5;
|
||||
INSTALL_PATH = /usr/local/bin;
|
||||
LIBRARY_SEARCH_PATHS = (
|
||||
../irstlm/lib,
|
||||
../srilm/lib/macosx,
|
||||
../randlm/lib,
|
||||
../kenlm,
|
||||
);
|
||||
OTHER_LDFLAGS = (
|
||||
"-lz",
|
||||
"-lirstlm",
|
||||
"-lmisc",
|
||||
"-ldstruct",
|
||||
"-loolm",
|
||||
"-lflm",
|
||||
"-llattice",
|
||||
"-lkenlm",
|
||||
"-lrandlm",
|
||||
);
|
||||
PRODUCT_NAME = CreateOnDisk;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
1DEB923608733DC60010E9CD /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
|
||||
GCC_C_LANGUAGE_STANDARD = gnu99;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
HEADER_SEARCH_PATHS = ../../irstlm/include;
|
||||
LIBRARY_SEARCH_PATHS = "";
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
PREBINDING = NO;
|
||||
SDKROOT = macosx10.6;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
1DEB923708733DC60010E9CD /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
|
||||
GCC_C_LANGUAGE_STANDARD = gnu99;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
HEADER_SEARCH_PATHS = ../../irstlm/include;
|
||||
LIBRARY_SEARCH_PATHS = "";
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
PREBINDING = NO;
|
||||
SDKROOT = macosx10.6;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
1DEB923108733DC60010E9CD /* Build configuration list for PBXNativeTarget "CreateOnDisk" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
1DEB923208733DC60010E9CD /* Debug */,
|
||||
1DEB923308733DC60010E9CD /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
1DEB923508733DC60010E9CD /* Build configuration list for PBXProject "CreateOnDisk" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
1DEB923608733DC60010E9CD /* Debug */,
|
||||
1DEB923708733DC60010E9CD /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
};
|
||||
rootObject = 08FB7793FE84155DC02AAC07 /* Project object */;
|
||||
}
|
240
trunk/CreateOnDisk/src/Main.cpp
Normal file
240
trunk/CreateOnDisk/src/Main.cpp
Normal file
@ -0,0 +1,240 @@
|
||||
// $Id$
|
||||
/***********************************************************************
|
||||
Moses - factored phrase-based, hierarchical and syntactic language decoder
|
||||
Copyright (C) 2009 Hieu Hoang
|
||||
|
||||
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
|
||||
***********************************************************************/
|
||||
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <iterator>
|
||||
#include "../../moses/src/InputFileStream.h"
|
||||
#include "../../moses/src/Util.h"
|
||||
#include "../../moses/src/UserMessage.h"
|
||||
#include "../../OnDiskPt/src/OnDiskWrapper.h"
|
||||
#include "../../OnDiskPt/src/SourcePhrase.h"
|
||||
#include "../../OnDiskPt/src/TargetPhrase.h"
|
||||
#include "../../OnDiskPt/src/TargetPhraseCollection.h"
|
||||
#include "../../OnDiskPt/src/Word.h"
|
||||
#include "../../OnDiskPt/src/Vocab.h"
|
||||
#include "Main.h"
|
||||
|
||||
using namespace std;
|
||||
using namespace OnDiskPt;
|
||||
|
||||
int main (int argc, char * const argv[])
|
||||
{
|
||||
// insert code here...
|
||||
Moses::ResetUserTime();
|
||||
Moses::PrintUserTime("Starting");
|
||||
|
||||
assert(argc == 8);
|
||||
|
||||
int numSourceFactors = Moses::Scan<int>(argv[1])
|
||||
, numTargetFactors = Moses::Scan<int>(argv[2])
|
||||
, numScores = Moses::Scan<int>(argv[3])
|
||||
, tableLimit = Moses::Scan<int>(argv[4]);
|
||||
TargetPhraseCollection::s_sortScoreInd = Moses::Scan<int>(argv[5]);
|
||||
assert(TargetPhraseCollection::s_sortScoreInd < numScores);
|
||||
|
||||
const string filePath = argv[6]
|
||||
,destPath = argv[7];
|
||||
|
||||
|
||||
Moses::InputFileStream inStream(filePath);
|
||||
|
||||
OnDiskWrapper onDiskWrapper;
|
||||
bool retDb = onDiskWrapper.BeginSave(destPath, numSourceFactors, numTargetFactors, numScores);
|
||||
assert(retDb);
|
||||
|
||||
PhraseNode &rootNode = onDiskWrapper.GetRootSourceNode();
|
||||
size_t lineNum = 0;
|
||||
char line[100000];
|
||||
|
||||
//while(getline(inStream, line))
|
||||
while(inStream.getline(line, 100000)) {
|
||||
lineNum++;
|
||||
if (lineNum%1000 == 0) cerr << "." << flush;
|
||||
if (lineNum%10000 == 0) cerr << ":" << flush;
|
||||
if (lineNum%100000 == 0) cerr << lineNum << flush;
|
||||
//cerr << lineNum << " " << line << endl;
|
||||
|
||||
std::vector<float> misc(1);
|
||||
SourcePhrase sourcePhrase;
|
||||
TargetPhrase *targetPhrase = new TargetPhrase(numScores);
|
||||
Tokenize(sourcePhrase, *targetPhrase, line, onDiskWrapper, numScores, misc);
|
||||
assert(misc.size() == onDiskWrapper.GetNumCounts());
|
||||
|
||||
rootNode.AddTargetPhrase(sourcePhrase, targetPhrase, onDiskWrapper, tableLimit, misc);
|
||||
}
|
||||
|
||||
rootNode.Save(onDiskWrapper, 0, tableLimit);
|
||||
onDiskWrapper.EndSave();
|
||||
|
||||
Moses::PrintUserTime("Finished");
|
||||
|
||||
//pause();
|
||||
return 0;
|
||||
|
||||
} // main()
|
||||
|
||||
bool Flush(const OnDiskPt::SourcePhrase *prevSourcePhrase, const OnDiskPt::SourcePhrase *currSourcePhrase)
|
||||
{
|
||||
if (prevSourcePhrase == NULL)
|
||||
return false;
|
||||
|
||||
assert(currSourcePhrase);
|
||||
bool ret = (*currSourcePhrase > *prevSourcePhrase);
|
||||
//cerr << *prevSourcePhrase << endl << *currSourcePhrase << " " << ret << endl << endl;
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
void Tokenize(SourcePhrase &sourcePhrase, TargetPhrase &targetPhrase, char *line, OnDiskWrapper &onDiskWrapper, int numScores, vector<float> &misc)
|
||||
{
|
||||
size_t scoreInd = 0;
|
||||
|
||||
// MAIN LOOP
|
||||
size_t stage = 0;
|
||||
/* 0 = source phrase
|
||||
1 = target phrase
|
||||
2 = scores
|
||||
3 = align
|
||||
4 = count
|
||||
*/
|
||||
char *tok = strtok (line," ");
|
||||
while (tok != NULL) {
|
||||
if (0 == strcmp(tok, "|||")) {
|
||||
++stage;
|
||||
} else {
|
||||
switch (stage) {
|
||||
case 0: {
|
||||
Tokenize(sourcePhrase, tok, true, true, onDiskWrapper);
|
||||
break;
|
||||
}
|
||||
case 1: {
|
||||
Tokenize(targetPhrase, tok, false, true, onDiskWrapper);
|
||||
break;
|
||||
}
|
||||
case 2: {
|
||||
float score = Moses::Scan<float>(tok);
|
||||
targetPhrase.SetScore(score, scoreInd);
|
||||
++scoreInd;
|
||||
break;
|
||||
}
|
||||
case 3: {
|
||||
targetPhrase.Create1AlignFromString(tok);
|
||||
break;
|
||||
}
|
||||
case 4:
|
||||
++stage;
|
||||
break;
|
||||
case 5: {
|
||||
// count info. Only store the 2nd one
|
||||
float val = Moses::Scan<float>(tok);
|
||||
misc[0] = val;
|
||||
++stage;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
assert(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
tok = strtok (NULL, " ");
|
||||
} // while (tok != NULL)
|
||||
|
||||
assert(scoreInd == numScores);
|
||||
targetPhrase.SortAlign();
|
||||
|
||||
} // Tokenize()
|
||||
|
||||
void Tokenize(OnDiskPt::Phrase &phrase
|
||||
, const std::string &token, bool addSourceNonTerm, bool addTargetNonTerm
|
||||
, OnDiskPt::OnDiskWrapper &onDiskWrapper)
|
||||
{
|
||||
|
||||
bool nonTerm = false;
|
||||
size_t tokSize = token.size();
|
||||
int comStr =token.compare(0, 1, "[");
|
||||
|
||||
if (comStr == 0) {
|
||||
comStr = token.compare(tokSize - 1, 1, "]");
|
||||
nonTerm = comStr == 0;
|
||||
}
|
||||
|
||||
if (nonTerm) {
|
||||
// non-term
|
||||
size_t splitPos = token.find_first_of("[", 2);
|
||||
string wordStr = token.substr(0, splitPos);
|
||||
|
||||
if (splitPos == string::npos) {
|
||||
// lhs - only 1 word
|
||||
Word *word = new Word();
|
||||
word->CreateFromString(wordStr, onDiskWrapper.GetVocab());
|
||||
phrase.AddWord(word);
|
||||
} else {
|
||||
// source & target non-terms
|
||||
if (addSourceNonTerm) {
|
||||
Word *word = new Word();
|
||||
word->CreateFromString(wordStr, onDiskWrapper.GetVocab());
|
||||
phrase.AddWord(word);
|
||||
}
|
||||
|
||||
wordStr = token.substr(splitPos, tokSize - splitPos);
|
||||
if (addTargetNonTerm) {
|
||||
Word *word = new Word();
|
||||
word->CreateFromString(wordStr, onDiskWrapper.GetVocab());
|
||||
phrase.AddWord(word);
|
||||
}
|
||||
|
||||
}
|
||||
} else {
|
||||
// term
|
||||
Word *word = new Word();
|
||||
word->CreateFromString(token, onDiskWrapper.GetVocab());
|
||||
phrase.AddWord(word);
|
||||
}
|
||||
}
|
||||
|
||||
void InsertTargetNonTerminals(std::vector<std::string> &sourceToks, const std::vector<std::string> &targetToks, const ::AlignType &alignments)
|
||||
{
|
||||
for (int ind = alignments.size() - 1; ind >= 0; --ind) {
|
||||
const ::AlignPair &alignPair = alignments[ind];
|
||||
size_t sourcePos = alignPair.first
|
||||
,targetPos = alignPair.second;
|
||||
|
||||
const string &target = targetToks[targetPos];
|
||||
sourceToks.insert(sourceToks.begin() + sourcePos + 1, target);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
class AlignOrderer
|
||||
{
|
||||
public:
|
||||
bool operator()(const ::AlignPair &a, const ::AlignPair &b) const {
|
||||
return a.first < b.first;
|
||||
}
|
||||
};
|
||||
|
||||
void SortAlign(::AlignType &alignments)
|
||||
{
|
||||
std::sort(alignments.begin(), alignments.end(), AlignOrderer());
|
||||
}
|
39
trunk/CreateOnDisk/src/Main.h
Normal file
39
trunk/CreateOnDisk/src/Main.h
Normal file
@ -0,0 +1,39 @@
|
||||
#pragma once
|
||||
// $Id$
|
||||
/***********************************************************************
|
||||
Moses - factored phrase-based, hierarchical and syntactic language decoder
|
||||
Copyright (C) 2009 Hieu Hoang
|
||||
|
||||
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
|
||||
***********************************************************************/
|
||||
#include <string>
|
||||
#include "../../OnDiskPt/src/SourcePhrase.h"
|
||||
#include "../../OnDiskPt/src/TargetPhrase.h"
|
||||
|
||||
typedef std::pair<size_t, size_t> AlignPair;
|
||||
typedef std::vector<AlignPair> AlignType;
|
||||
|
||||
void Tokenize(OnDiskPt::Phrase &phrase
|
||||
, const std::string &token, bool addSourceNonTerm, bool addTargetNonTerm
|
||||
, OnDiskPt::OnDiskWrapper &onDiskWrapper);
|
||||
void Tokenize(OnDiskPt::SourcePhrase &sourcePhrase, OnDiskPt::TargetPhrase &targetPhrase
|
||||
, char *line, OnDiskPt::OnDiskWrapper &onDiskWrapper
|
||||
, int numScores
|
||||
, std::vector<float> &misc);
|
||||
|
||||
void InsertTargetNonTerminals(std::vector<std::string> &sourceToks, const std::vector<std::string> &targetToks, const AlignType &alignments);
|
||||
void SortAlign(AlignType &alignments);
|
||||
bool Flush(const OnDiskPt::SourcePhrase *prevSource, const OnDiskPt::SourcePhrase *currSource);
|
||||
|
9
trunk/CreateOnDisk/src/Makefile.am
Normal file
9
trunk/CreateOnDisk/src/Makefile.am
Normal file
@ -0,0 +1,9 @@
|
||||
bin_PROGRAMS = CreateOnDiskPt
|
||||
CreateOnDiskPt_SOURCES = Main.cpp
|
||||
AM_CPPFLAGS = -W -Wall -ffor-scope -D_FILE_OFFSET_BITS=64 -D_LARGE_FILES -DUSE_HYPO_POOL -I$(top_srcdir)/moses/src $(BOOST_CPPFLAGS)
|
||||
|
||||
CreateOnDiskPt_LDADD = -L$(top_srcdir)/OnDiskPt/src -L$(top_srcdir)/moses/src -lOnDiskPt -lmoses $(BOOST_THREAD_LDFLAGS) $(BOOST_THREAD_LIBS) @KENLM_LDFLAGS@
|
||||
CreateOnDiskPt_DEPENDENCIES = $(top_srcdir)/OnDiskPt/src/libOnDiskPt.a $(top_srcdir)/moses/src/libmoses.la @KENLM_DEPS@
|
||||
|
||||
|
||||
|
14
trunk/Makefile.am
Normal file
14
trunk/Makefile.am
Normal file
@ -0,0 +1,14 @@
|
||||
# not a GNU package. You can remove this line, if
|
||||
# have all needed files, that a GNU package needs
|
||||
AUTOMAKE_OPTIONS = foreign
|
||||
|
||||
ACLOCAL_AMFLAGS = -I m4
|
||||
|
||||
# order is important here: build moses before moses-cmd
|
||||
if WITH_MERT
|
||||
MERT = mert
|
||||
endif
|
||||
if WITH_SERVER
|
||||
SERVER = server
|
||||
endif
|
||||
SUBDIRS = kenlm moses/src OnDiskPt/src moses-cmd/src misc moses-chart-cmd/src CreateOnDisk/src $(MERT) $(SERVER)
|
94
trunk/OnDiskPt/OnDiskPt.vcxproj
Normal file
94
trunk/OnDiskPt/OnDiskPt.vcxproj
Normal file
@ -0,0 +1,94 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>{8B07671B-CBAF-4514-AFFD-CE238CD427E9}</ProjectGuid>
|
||||
<RootNamespace>OnDiskPt</RootNamespace>
|
||||
<Keyword>Win32Proj</Keyword>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup>
|
||||
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<MinimalRebuild>true</MinimalRebuild>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="src\OnDiskWrapper.cpp" />
|
||||
<ClCompile Include="src\Phrase.cpp" />
|
||||
<ClCompile Include="src\PhraseNode.cpp" />
|
||||
<ClCompile Include="src\SourcePhrase.cpp" />
|
||||
<ClCompile Include="src\TargetPhrase.cpp" />
|
||||
<ClCompile Include="src\TargetPhraseCollection.cpp" />
|
||||
<ClCompile Include="src\Vocab.cpp" />
|
||||
<ClCompile Include="src\Word.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="src\OnDiskWrapper.h" />
|
||||
<ClInclude Include="src\Phrase.h" />
|
||||
<ClInclude Include="src\PhraseNode.h" />
|
||||
<ClInclude Include="src\SourcePhrase.h" />
|
||||
<ClInclude Include="src\TargetPhrase.h" />
|
||||
<ClInclude Include="src\TargetPhraseCollection.h" />
|
||||
<ClInclude Include="src\Vocab.h" />
|
||||
<ClInclude Include="src\Word.h" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
</Project>
|
264
trunk/OnDiskPt/OnDiskPt.xcodeproj/project.pbxproj
Normal file
264
trunk/OnDiskPt/OnDiskPt.xcodeproj/project.pbxproj
Normal file
@ -0,0 +1,264 @@
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 45;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
1ED4FB1911BDBA2B004E826A /* OnDiskWrapper.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1ED4FB0811BDBA2B004E826A /* OnDiskWrapper.cpp */; };
|
||||
1ED4FB1A11BDBA2B004E826A /* OnDiskWrapper.h in Headers */ = {isa = PBXBuildFile; fileRef = 1ED4FB0911BDBA2B004E826A /* OnDiskWrapper.h */; };
|
||||
1ED4FB1B11BDBA2B004E826A /* Phrase.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1ED4FB0A11BDBA2B004E826A /* Phrase.cpp */; };
|
||||
1ED4FB1C11BDBA2B004E826A /* Phrase.h in Headers */ = {isa = PBXBuildFile; fileRef = 1ED4FB0B11BDBA2B004E826A /* Phrase.h */; };
|
||||
1ED4FB1D11BDBA2B004E826A /* PhraseNode.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1ED4FB0C11BDBA2B004E826A /* PhraseNode.cpp */; };
|
||||
1ED4FB1E11BDBA2B004E826A /* PhraseNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 1ED4FB0D11BDBA2B004E826A /* PhraseNode.h */; };
|
||||
1ED4FB1F11BDBA2B004E826A /* SourcePhrase.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1ED4FB0E11BDBA2B004E826A /* SourcePhrase.cpp */; };
|
||||
1ED4FB2011BDBA2B004E826A /* SourcePhrase.h in Headers */ = {isa = PBXBuildFile; fileRef = 1ED4FB0F11BDBA2B004E826A /* SourcePhrase.h */; };
|
||||
1ED4FB2111BDBA2B004E826A /* TargetPhrase.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1ED4FB1011BDBA2B004E826A /* TargetPhrase.cpp */; };
|
||||
1ED4FB2211BDBA2B004E826A /* TargetPhrase.h in Headers */ = {isa = PBXBuildFile; fileRef = 1ED4FB1111BDBA2B004E826A /* TargetPhrase.h */; };
|
||||
1ED4FB2311BDBA2B004E826A /* TargetPhraseCollection.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1ED4FB1211BDBA2B004E826A /* TargetPhraseCollection.cpp */; };
|
||||
1ED4FB2411BDBA2B004E826A /* TargetPhraseCollection.h in Headers */ = {isa = PBXBuildFile; fileRef = 1ED4FB1311BDBA2B004E826A /* TargetPhraseCollection.h */; };
|
||||
1ED4FB2511BDBA2B004E826A /* Vocab.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1ED4FB1411BDBA2B004E826A /* Vocab.cpp */; };
|
||||
1ED4FB2611BDBA2B004E826A /* Vocab.h in Headers */ = {isa = PBXBuildFile; fileRef = 1ED4FB1511BDBA2B004E826A /* Vocab.h */; };
|
||||
1ED4FB2711BDBA2B004E826A /* Word.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1ED4FB1611BDBA2B004E826A /* Word.cpp */; };
|
||||
1ED4FB2811BDBA2B004E826A /* Word.h in Headers */ = {isa = PBXBuildFile; fileRef = 1ED4FB1711BDBA2B004E826A /* Word.h */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
1ED4FB0811BDBA2B004E826A /* OnDiskWrapper.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = OnDiskWrapper.cpp; path = src/OnDiskWrapper.cpp; sourceTree = "<group>"; };
|
||||
1ED4FB0911BDBA2B004E826A /* OnDiskWrapper.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = OnDiskWrapper.h; path = src/OnDiskWrapper.h; sourceTree = "<group>"; };
|
||||
1ED4FB0A11BDBA2B004E826A /* Phrase.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = Phrase.cpp; path = src/Phrase.cpp; sourceTree = "<group>"; };
|
||||
1ED4FB0B11BDBA2B004E826A /* Phrase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Phrase.h; path = src/Phrase.h; sourceTree = "<group>"; };
|
||||
1ED4FB0C11BDBA2B004E826A /* PhraseNode.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = PhraseNode.cpp; path = src/PhraseNode.cpp; sourceTree = "<group>"; };
|
||||
1ED4FB0D11BDBA2B004E826A /* PhraseNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = PhraseNode.h; path = src/PhraseNode.h; sourceTree = "<group>"; };
|
||||
1ED4FB0E11BDBA2B004E826A /* SourcePhrase.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = SourcePhrase.cpp; path = src/SourcePhrase.cpp; sourceTree = "<group>"; };
|
||||
1ED4FB0F11BDBA2B004E826A /* SourcePhrase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SourcePhrase.h; path = src/SourcePhrase.h; sourceTree = "<group>"; };
|
||||
1ED4FB1011BDBA2B004E826A /* TargetPhrase.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TargetPhrase.cpp; path = src/TargetPhrase.cpp; sourceTree = "<group>"; };
|
||||
1ED4FB1111BDBA2B004E826A /* TargetPhrase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TargetPhrase.h; path = src/TargetPhrase.h; sourceTree = "<group>"; };
|
||||
1ED4FB1211BDBA2B004E826A /* TargetPhraseCollection.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TargetPhraseCollection.cpp; path = src/TargetPhraseCollection.cpp; sourceTree = "<group>"; };
|
||||
1ED4FB1311BDBA2B004E826A /* TargetPhraseCollection.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TargetPhraseCollection.h; path = src/TargetPhraseCollection.h; sourceTree = "<group>"; };
|
||||
1ED4FB1411BDBA2B004E826A /* Vocab.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = Vocab.cpp; path = src/Vocab.cpp; sourceTree = "<group>"; };
|
||||
1ED4FB1511BDBA2B004E826A /* Vocab.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Vocab.h; path = src/Vocab.h; sourceTree = "<group>"; };
|
||||
1ED4FB1611BDBA2B004E826A /* Word.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = Word.cpp; path = src/Word.cpp; sourceTree = "<group>"; };
|
||||
1ED4FB1711BDBA2B004E826A /* Word.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Word.h; path = src/Word.h; sourceTree = "<group>"; };
|
||||
D2AAC046055464E500DB518D /* libOnDiskPt.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libOnDiskPt.a; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
D289987405E68DCB004EDB86 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
08FB7794FE84155DC02AAC07 /* OnDiskPt */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
08FB7795FE84155DC02AAC07 /* Source */,
|
||||
C6A0FF2B0290797F04C91782 /* Documentation */,
|
||||
1AB674ADFE9D54B511CA2CBB /* Products */,
|
||||
);
|
||||
name = OnDiskPt;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
08FB7795FE84155DC02AAC07 /* Source */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1ED4FB0811BDBA2B004E826A /* OnDiskWrapper.cpp */,
|
||||
1ED4FB0911BDBA2B004E826A /* OnDiskWrapper.h */,
|
||||
1ED4FB0A11BDBA2B004E826A /* Phrase.cpp */,
|
||||
1ED4FB0B11BDBA2B004E826A /* Phrase.h */,
|
||||
1ED4FB0C11BDBA2B004E826A /* PhraseNode.cpp */,
|
||||
1ED4FB0D11BDBA2B004E826A /* PhraseNode.h */,
|
||||
1ED4FB0E11BDBA2B004E826A /* SourcePhrase.cpp */,
|
||||
1ED4FB0F11BDBA2B004E826A /* SourcePhrase.h */,
|
||||
1ED4FB1011BDBA2B004E826A /* TargetPhrase.cpp */,
|
||||
1ED4FB1111BDBA2B004E826A /* TargetPhrase.h */,
|
||||
1ED4FB1211BDBA2B004E826A /* TargetPhraseCollection.cpp */,
|
||||
1ED4FB1311BDBA2B004E826A /* TargetPhraseCollection.h */,
|
||||
1ED4FB1411BDBA2B004E826A /* Vocab.cpp */,
|
||||
1ED4FB1511BDBA2B004E826A /* Vocab.h */,
|
||||
1ED4FB1611BDBA2B004E826A /* Word.cpp */,
|
||||
1ED4FB1711BDBA2B004E826A /* Word.h */,
|
||||
);
|
||||
name = Source;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
1AB674ADFE9D54B511CA2CBB /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
D2AAC046055464E500DB518D /* libOnDiskPt.a */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
C6A0FF2B0290797F04C91782 /* Documentation */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
);
|
||||
name = Documentation;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXHeadersBuildPhase section */
|
||||
D2AAC043055464E500DB518D /* Headers */ = {
|
||||
isa = PBXHeadersBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
1ED4FB1A11BDBA2B004E826A /* OnDiskWrapper.h in Headers */,
|
||||
1ED4FB1C11BDBA2B004E826A /* Phrase.h in Headers */,
|
||||
1ED4FB1E11BDBA2B004E826A /* PhraseNode.h in Headers */,
|
||||
1ED4FB2011BDBA2B004E826A /* SourcePhrase.h in Headers */,
|
||||
1ED4FB2211BDBA2B004E826A /* TargetPhrase.h in Headers */,
|
||||
1ED4FB2411BDBA2B004E826A /* TargetPhraseCollection.h in Headers */,
|
||||
1ED4FB2611BDBA2B004E826A /* Vocab.h in Headers */,
|
||||
1ED4FB2811BDBA2B004E826A /* Word.h in Headers */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXHeadersBuildPhase section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
D2AAC045055464E500DB518D /* OnDiskPt */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 1DEB91EB08733DB70010E9CD /* Build configuration list for PBXNativeTarget "OnDiskPt" */;
|
||||
buildPhases = (
|
||||
D2AAC043055464E500DB518D /* Headers */,
|
||||
D2AAC044055464E500DB518D /* Sources */,
|
||||
D289987405E68DCB004EDB86 /* Frameworks */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = OnDiskPt;
|
||||
productName = OnDiskPt;
|
||||
productReference = D2AAC046055464E500DB518D /* libOnDiskPt.a */;
|
||||
productType = "com.apple.product-type.library.static";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
08FB7793FE84155DC02AAC07 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
buildConfigurationList = 1DEB91EF08733DB70010E9CD /* Build configuration list for PBXProject "OnDiskPt" */;
|
||||
compatibilityVersion = "Xcode 3.1";
|
||||
developmentRegion = English;
|
||||
hasScannedForEncodings = 1;
|
||||
knownRegions = (
|
||||
English,
|
||||
Japanese,
|
||||
French,
|
||||
German,
|
||||
);
|
||||
mainGroup = 08FB7794FE84155DC02AAC07 /* OnDiskPt */;
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
D2AAC045055464E500DB518D /* OnDiskPt */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
D2AAC044055464E500DB518D /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
1ED4FB1911BDBA2B004E826A /* OnDiskWrapper.cpp in Sources */,
|
||||
1ED4FB1B11BDBA2B004E826A /* Phrase.cpp in Sources */,
|
||||
1ED4FB1D11BDBA2B004E826A /* PhraseNode.cpp in Sources */,
|
||||
1ED4FB1F11BDBA2B004E826A /* SourcePhrase.cpp in Sources */,
|
||||
1ED4FB2111BDBA2B004E826A /* TargetPhrase.cpp in Sources */,
|
||||
1ED4FB2311BDBA2B004E826A /* TargetPhraseCollection.cpp in Sources */,
|
||||
1ED4FB2511BDBA2B004E826A /* Vocab.cpp in Sources */,
|
||||
1ED4FB2711BDBA2B004E826A /* Word.cpp in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
1DEB91EC08733DB70010E9CD /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
GCC_DYNAMIC_NO_PIC = NO;
|
||||
GCC_ENABLE_FIX_AND_CONTINUE = YES;
|
||||
GCC_MODEL_TUNING = G5;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
INSTALL_PATH = /usr/local/lib;
|
||||
PRODUCT_NAME = OnDiskPt;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
1DEB91ED08733DB70010E9CD /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
GCC_MODEL_TUNING = G5;
|
||||
INSTALL_PATH = /usr/local/lib;
|
||||
PRODUCT_NAME = OnDiskPt;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
1DEB91F008733DB70010E9CD /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
|
||||
GCC_C_LANGUAGE_STANDARD = gnu99;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
PREBINDING = NO;
|
||||
SDKROOT = macosx10.6;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
1DEB91F108733DB70010E9CD /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
|
||||
GCC_C_LANGUAGE_STANDARD = gnu99;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
PREBINDING = NO;
|
||||
SDKROOT = macosx10.6;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
1DEB91EB08733DB70010E9CD /* Build configuration list for PBXNativeTarget "OnDiskPt" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
1DEB91EC08733DB70010E9CD /* Debug */,
|
||||
1DEB91ED08733DB70010E9CD /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
1DEB91EF08733DB70010E9CD /* Build configuration list for PBXProject "OnDiskPt" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
1DEB91F008733DB70010E9CD /* Debug */,
|
||||
1DEB91F108733DB70010E9CD /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
};
|
||||
rootObject = 08FB7793FE84155DC02AAC07 /* Project object */;
|
||||
}
|
14
trunk/OnDiskPt/src/Makefile.am
Normal file
14
trunk/OnDiskPt/src/Makefile.am
Normal file
@ -0,0 +1,14 @@
|
||||
lib_LIBRARIES = libOnDiskPt.a
|
||||
AM_CPPFLAGS = -W -Wall -ffor-scope -D_FILE_OFFSET_BITS=64 -D_LARGE_FILES $(BOOST_CPPFLAGS)
|
||||
libOnDiskPt_a_SOURCES = \
|
||||
OnDiskWrapper.cpp \
|
||||
SourcePhrase.cpp \
|
||||
TargetPhrase.cpp \
|
||||
Word.cpp \
|
||||
Phrase.cpp \
|
||||
PhraseNode.cpp \
|
||||
TargetPhraseCollection.cpp \
|
||||
Vocab.cpp
|
||||
|
||||
|
||||
|
231
trunk/OnDiskPt/src/OnDiskWrapper.cpp
Normal file
231
trunk/OnDiskPt/src/OnDiskWrapper.cpp
Normal file
@ -0,0 +1,231 @@
|
||||
// $Id$
|
||||
/***********************************************************************
|
||||
Moses - factored phrase-based, hierarchical and syntactic language decoder
|
||||
Copyright (C) 2009 Hieu Hoang
|
||||
|
||||
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
|
||||
***********************************************************************/
|
||||
#ifdef WIN32
|
||||
#include <direct.h>
|
||||
#endif
|
||||
#include <sys/stat.h>
|
||||
#include <cassert>
|
||||
#include <string>
|
||||
#include "OnDiskWrapper.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
namespace OnDiskPt
|
||||
{
|
||||
|
||||
OnDiskWrapper::OnDiskWrapper()
|
||||
{
|
||||
}
|
||||
|
||||
OnDiskWrapper::~OnDiskWrapper()
|
||||
{
|
||||
delete m_rootSourceNode;
|
||||
}
|
||||
|
||||
bool OnDiskWrapper::BeginLoad(const std::string &filePath)
|
||||
{
|
||||
if (!OpenForLoad(filePath))
|
||||
return false;
|
||||
|
||||
if (!m_vocab.Load(*this))
|
||||
return false;
|
||||
|
||||
UINT64 rootFilePos = GetMisc("RootNodeOffset");
|
||||
m_rootSourceNode = new PhraseNode(rootFilePos, *this);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool OnDiskWrapper::OpenForLoad(const std::string &filePath)
|
||||
{
|
||||
m_fileSource.open((filePath + "/Source.dat").c_str(), ios::in | ios::binary);
|
||||
assert(m_fileSource.is_open());
|
||||
|
||||
m_fileTargetInd.open((filePath + "/TargetInd.dat").c_str(), ios::in | ios::binary);
|
||||
assert(m_fileTargetInd.is_open());
|
||||
|
||||
m_fileTargetColl.open((filePath + "/TargetColl.dat").c_str(), ios::in | ios::binary);
|
||||
assert(m_fileTargetColl.is_open());
|
||||
|
||||
m_fileVocab.open((filePath + "/Vocab.dat").c_str(), ios::in);
|
||||
assert(m_fileVocab.is_open());
|
||||
|
||||
m_fileMisc.open((filePath + "/Misc.dat").c_str(), ios::in);
|
||||
assert(m_fileMisc.is_open());
|
||||
|
||||
// set up root node
|
||||
LoadMisc();
|
||||
m_numSourceFactors = GetMisc("NumSourceFactors");
|
||||
m_numTargetFactors = GetMisc("NumTargetFactors");
|
||||
m_numScores = GetMisc("NumScores");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool OnDiskWrapper::LoadMisc()
|
||||
{
|
||||
char line[100000];
|
||||
|
||||
while(m_fileMisc.getline(line, 100000)) {
|
||||
vector<string> tokens;
|
||||
Moses::Tokenize(tokens, line);
|
||||
assert(tokens.size() == 2);
|
||||
const string &key = tokens[0];
|
||||
m_miscInfo[key] = Moses::Scan<UINT64>(tokens[1]);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool OnDiskWrapper::BeginSave(const std::string &filePath
|
||||
, int numSourceFactors, int numTargetFactors, int numScores)
|
||||
{
|
||||
m_numSourceFactors = numSourceFactors;
|
||||
m_numTargetFactors = numTargetFactors;
|
||||
m_numScores = numScores;
|
||||
m_filePath = filePath;
|
||||
|
||||
#ifdef WIN32
|
||||
mkdir(filePath.c_str());
|
||||
#else
|
||||
mkdir(filePath.c_str(), 0777);
|
||||
#endif
|
||||
|
||||
m_fileSource.open((filePath + "/Source.dat").c_str(), ios::out | ios::in | ios::binary | ios::ate | ios::trunc);
|
||||
assert(m_fileSource.is_open());
|
||||
|
||||
m_fileTargetInd.open((filePath + "/TargetInd.dat").c_str(), ios::out | ios::binary | ios::ate | ios::trunc);
|
||||
assert(m_fileTargetInd.is_open());
|
||||
|
||||
m_fileTargetColl.open((filePath + "/TargetColl.dat").c_str(), ios::out | ios::binary | ios::ate | ios::trunc);
|
||||
assert(m_fileTargetColl.is_open());
|
||||
|
||||
m_fileVocab.open((filePath + "/Vocab.dat").c_str(), ios::out | ios::ate | ios::trunc);
|
||||
assert(m_fileVocab.is_open());
|
||||
|
||||
m_fileMisc.open((filePath + "/Misc.dat").c_str(), ios::out | ios::ate | ios::trunc);
|
||||
assert(m_fileMisc.is_open());
|
||||
|
||||
// offset by 1. 0 offset is reserved
|
||||
char c = 0xff;
|
||||
m_fileSource.write(&c, 1);
|
||||
assert(1 == m_fileSource.tellp());
|
||||
|
||||
m_fileTargetInd.write(&c, 1);
|
||||
assert(1 == m_fileTargetInd.tellp());
|
||||
|
||||
m_fileTargetColl.write(&c, 1);
|
||||
assert(1 == m_fileTargetColl.tellp());
|
||||
|
||||
// set up root node
|
||||
assert(GetNumCounts() == 1);
|
||||
vector<float> counts(GetNumCounts());
|
||||
counts[0] = DEFAULT_COUNT;
|
||||
m_rootSourceNode = new PhraseNode();
|
||||
m_rootSourceNode->AddCounts(counts);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void OnDiskWrapper::EndSave()
|
||||
{
|
||||
bool ret = m_rootSourceNode->Saved();
|
||||
assert(ret);
|
||||
|
||||
GetVocab().Save(*this);
|
||||
|
||||
SaveMisc();
|
||||
|
||||
m_fileMisc.close();
|
||||
m_fileVocab.close();
|
||||
m_fileSource.close();
|
||||
m_fileTarget.close();
|
||||
m_fileTargetInd.close();
|
||||
m_fileTargetColl.close();
|
||||
}
|
||||
|
||||
void OnDiskWrapper::SaveMisc()
|
||||
{
|
||||
m_fileMisc << "Version 3" << endl;
|
||||
m_fileMisc << "NumSourceFactors " << m_numSourceFactors << endl;
|
||||
m_fileMisc << "NumTargetFactors " << m_numTargetFactors << endl;
|
||||
m_fileMisc << "NumScores " << m_numScores << endl;
|
||||
m_fileMisc << "RootNodeOffset " << m_rootSourceNode->GetFilePos() << endl;
|
||||
}
|
||||
|
||||
size_t OnDiskWrapper::GetSourceWordSize() const
|
||||
{
|
||||
return m_numSourceFactors * sizeof(UINT64) + sizeof(char);
|
||||
}
|
||||
|
||||
size_t OnDiskWrapper::GetTargetWordSize() const
|
||||
{
|
||||
return m_numTargetFactors * sizeof(UINT64) + sizeof(char);
|
||||
}
|
||||
|
||||
UINT64 OnDiskWrapper::GetMisc(const std::string &key) const
|
||||
{
|
||||
std::map<std::string, UINT64>::const_iterator iter;
|
||||
iter = m_miscInfo.find(key);
|
||||
assert(iter != m_miscInfo.end());
|
||||
|
||||
return iter->second;
|
||||
}
|
||||
|
||||
PhraseNode &OnDiskWrapper::GetRootSourceNode()
|
||||
{
|
||||
return *m_rootSourceNode;
|
||||
}
|
||||
|
||||
Word *OnDiskWrapper::ConvertFromMoses(Moses::FactorDirection /* direction */
|
||||
, const std::vector<Moses::FactorType> &factorsVec
|
||||
, const Moses::Word &origWord) const
|
||||
{
|
||||
bool isNonTerminal = origWord.IsNonTerminal();
|
||||
Word *newWord = new Word(1, isNonTerminal); // TODO - num of factors
|
||||
|
||||
for (size_t ind = 0 ; ind < factorsVec.size() ; ++ind) {
|
||||
size_t factorType = factorsVec[ind];
|
||||
|
||||
const Moses::Factor *factor = origWord.GetFactor(factorType);
|
||||
assert(factor);
|
||||
|
||||
string str = factor->GetString();
|
||||
if (isNonTerminal) {
|
||||
str = "[" + str + "]";
|
||||
}
|
||||
|
||||
bool found;
|
||||
UINT64 vocabId = m_vocab.GetVocabId(str, found);
|
||||
if (!found) {
|
||||
// factor not in phrase table -> phrse definately not in. exit
|
||||
delete newWord;
|
||||
return NULL;
|
||||
} else {
|
||||
newWord->SetVocabId(ind, vocabId);
|
||||
}
|
||||
} // for (size_t factorType
|
||||
|
||||
return newWord;
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
102
trunk/OnDiskPt/src/OnDiskWrapper.h
Normal file
102
trunk/OnDiskPt/src/OnDiskWrapper.h
Normal file
@ -0,0 +1,102 @@
|
||||
#pragma once
|
||||
// $Id$
|
||||
/***********************************************************************
|
||||
Moses - factored phrase-based, hierarchical and syntactic language decoder
|
||||
Copyright (C) 2009 Hieu Hoang
|
||||
|
||||
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
|
||||
***********************************************************************/
|
||||
#include <string>
|
||||
#include <fstream>
|
||||
#include "Vocab.h"
|
||||
#include "PhraseNode.h"
|
||||
#include "../../moses/src/Word.h"
|
||||
|
||||
namespace OnDiskPt
|
||||
{
|
||||
const float DEFAULT_COUNT = 66666;
|
||||
|
||||
class OnDiskWrapper
|
||||
{
|
||||
protected:
|
||||
Vocab m_vocab;
|
||||
std::string m_filePath;
|
||||
int m_numSourceFactors, m_numTargetFactors, m_numScores;
|
||||
std::fstream m_fileMisc, m_fileVocab, m_fileSource, m_fileTarget, m_fileTargetInd, m_fileTargetColl;
|
||||
|
||||
size_t m_defaultNodeSize;
|
||||
PhraseNode *m_rootSourceNode;
|
||||
|
||||
std::map<std::string, UINT64> m_miscInfo;
|
||||
|
||||
void SaveMisc();
|
||||
bool OpenForLoad(const std::string &filePath);
|
||||
bool LoadMisc();
|
||||
|
||||
public:
|
||||
OnDiskWrapper();
|
||||
~OnDiskWrapper();
|
||||
|
||||
bool BeginLoad(const std::string &filePath);
|
||||
|
||||
bool BeginSave(const std::string &filePath
|
||||
, int numSourceFactors, int numTargetFactors, int numScores);
|
||||
void EndSave();
|
||||
|
||||
Vocab &GetVocab() {
|
||||
return m_vocab;
|
||||
}
|
||||
|
||||
size_t GetSourceWordSize() const;
|
||||
size_t GetTargetWordSize() const;
|
||||
|
||||
std::fstream &GetFileSource() {
|
||||
return m_fileSource;
|
||||
}
|
||||
std::fstream &GetFileTargetInd() {
|
||||
return m_fileTargetInd;
|
||||
}
|
||||
std::fstream &GetFileTargetColl() {
|
||||
return m_fileTargetColl;
|
||||
}
|
||||
std::fstream &GetFileVocab() {
|
||||
return m_fileVocab;
|
||||
}
|
||||
|
||||
size_t GetNumSourceFactors() const {
|
||||
return m_numSourceFactors;
|
||||
}
|
||||
size_t GetNumTargetFactors() const {
|
||||
return m_numTargetFactors;
|
||||
}
|
||||
|
||||
size_t GetNumScores() const {
|
||||
return m_numScores;
|
||||
}
|
||||
size_t GetNumCounts() const {
|
||||
return 1;
|
||||
}
|
||||
|
||||
PhraseNode &GetRootSourceNode();
|
||||
|
||||
UINT64 GetMisc(const std::string &key) const;
|
||||
|
||||
Word *ConvertFromMoses(Moses::FactorDirection direction
|
||||
, const std::vector<Moses::FactorType> &factorsVec
|
||||
, const Moses::Word &origWord) const;
|
||||
|
||||
};
|
||||
|
||||
}
|
112
trunk/OnDiskPt/src/Phrase.cpp
Normal file
112
trunk/OnDiskPt/src/Phrase.cpp
Normal file
@ -0,0 +1,112 @@
|
||||
// $Id$
|
||||
/***********************************************************************
|
||||
Moses - factored phrase-based, hierarchical and syntactic language decoder
|
||||
Copyright (C) 2009 Hieu Hoang
|
||||
|
||||
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
|
||||
***********************************************************************/
|
||||
#include <iostream>
|
||||
#include <cassert>
|
||||
#include "../../moses/src/Util.h"
|
||||
#include "Phrase.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
namespace OnDiskPt
|
||||
{
|
||||
|
||||
Phrase::Phrase(const Phrase ©)
|
||||
:m_words(copy.GetSize())
|
||||
{
|
||||
for (size_t pos = 0; pos < copy.GetSize(); ++pos) {
|
||||
const Word &oldWord = copy.GetWord(pos);
|
||||
Word *newWord = new Word(oldWord);
|
||||
m_words[pos] = newWord;
|
||||
}
|
||||
}
|
||||
|
||||
Phrase::~Phrase()
|
||||
{
|
||||
Moses::RemoveAllInColl(m_words);
|
||||
}
|
||||
|
||||
void Phrase::AddWord(Word *word)
|
||||
{
|
||||
m_words.push_back(word);
|
||||
}
|
||||
|
||||
void Phrase::AddWord(Word *word, size_t pos)
|
||||
{
|
||||
assert(pos < m_words.size());
|
||||
m_words.insert(m_words.begin() + pos + 1, word);
|
||||
}
|
||||
|
||||
int Phrase::Compare(const Phrase &compare) const
|
||||
{
|
||||
int ret = 0;
|
||||
for (size_t pos = 0; pos < GetSize(); ++pos) {
|
||||
if (pos >= compare.GetSize()) {
|
||||
// we're bigger than the other. Put 1st
|
||||
ret = -1;
|
||||
break;
|
||||
}
|
||||
|
||||
const Word &thisWord = GetWord(pos)
|
||||
,&compareWord = compare.GetWord(pos);
|
||||
int wordRet = thisWord.Compare(compareWord);
|
||||
if (wordRet != 0) {
|
||||
ret = wordRet;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (ret == 0) {
|
||||
assert(compare.GetSize() >= GetSize());
|
||||
ret = (compare.GetSize() > GetSize()) ? 1 : 0;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! transitive comparison
|
||||
bool Phrase::operator<(const Phrase &compare) const
|
||||
{
|
||||
int ret = Compare(compare);
|
||||
return ret < 0;
|
||||
}
|
||||
|
||||
bool Phrase::operator>(const Phrase &compare) const
|
||||
{
|
||||
int ret = Compare(compare);
|
||||
return ret > 0;
|
||||
}
|
||||
|
||||
bool Phrase::operator==(const Phrase &compare) const
|
||||
{
|
||||
int ret = Compare(compare);
|
||||
return ret == 0;
|
||||
}
|
||||
|
||||
std::ostream& operator<<(std::ostream &out, const Phrase &phrase)
|
||||
{
|
||||
for (size_t pos = 0; pos < phrase.GetSize(); ++pos) {
|
||||
const Word &word = phrase.GetWord(pos);
|
||||
out << word << " ";
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
}
|
||||
|
57
trunk/OnDiskPt/src/Phrase.h
Normal file
57
trunk/OnDiskPt/src/Phrase.h
Normal file
@ -0,0 +1,57 @@
|
||||
#pragma once
|
||||
// $Id$
|
||||
/***********************************************************************
|
||||
Moses - factored phrase-based, hierarchical and syntactic language decoder
|
||||
Copyright (C) 2009 Hieu Hoang
|
||||
|
||||
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
|
||||
***********************************************************************/
|
||||
#include <vector>
|
||||
#include <iostream>
|
||||
#include "Word.h"
|
||||
|
||||
namespace OnDiskPt
|
||||
{
|
||||
|
||||
class Phrase
|
||||
{
|
||||
friend std::ostream& operator<<(std::ostream&, const Phrase&);
|
||||
|
||||
protected:
|
||||
std::vector<Word*> m_words;
|
||||
|
||||
public:
|
||||
Phrase()
|
||||
{}
|
||||
Phrase(const Phrase ©);
|
||||
virtual ~Phrase();
|
||||
|
||||
void AddWord(Word *word);
|
||||
void AddWord(Word *word, size_t pos);
|
||||
|
||||
const Word &GetWord(size_t pos) const {
|
||||
return *m_words[pos];
|
||||
}
|
||||
size_t GetSize() const {
|
||||
return m_words.size();
|
||||
}
|
||||
|
||||
int Compare(const Phrase &compare) const;
|
||||
bool operator<(const Phrase &compare) const;
|
||||
bool operator>(const Phrase &compare) const;
|
||||
bool operator==(const Phrase &compare) const;
|
||||
};
|
||||
|
||||
}
|
272
trunk/OnDiskPt/src/PhraseNode.cpp
Normal file
272
trunk/OnDiskPt/src/PhraseNode.cpp
Normal file
@ -0,0 +1,272 @@
|
||||
// $Id$
|
||||
/***********************************************************************
|
||||
Moses - factored phrase-based, hierarchical and syntactic language decoder
|
||||
Copyright (C) 2009 Hieu Hoang
|
||||
|
||||
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
|
||||
***********************************************************************/
|
||||
#include <cassert>
|
||||
#include "PhraseNode.h"
|
||||
#include "OnDiskWrapper.h"
|
||||
#include "TargetPhraseCollection.h"
|
||||
#include "SourcePhrase.h"
|
||||
#include "../../moses/src/Util.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
namespace OnDiskPt
|
||||
{
|
||||
|
||||
size_t PhraseNode::GetNodeSize(size_t numChildren, size_t wordSize, size_t countSize)
|
||||
{
|
||||
size_t ret = sizeof(UINT64) * 2 // num children, value
|
||||
+ (wordSize + sizeof(UINT64)) * numChildren // word + ptr to next source node
|
||||
+ sizeof(float) * countSize; // count info
|
||||
return ret;
|
||||
}
|
||||
|
||||
PhraseNode::PhraseNode()
|
||||
:m_currChild(NULL)
|
||||
,m_saved(false)
|
||||
,m_memLoad(NULL)
|
||||
,m_value(0)
|
||||
{
|
||||
}
|
||||
|
||||
PhraseNode::PhraseNode(UINT64 filePos, OnDiskWrapper &onDiskWrapper)
|
||||
:m_counts(onDiskWrapper.GetNumCounts())
|
||||
{
|
||||
// load saved node
|
||||
m_filePos = filePos;
|
||||
|
||||
size_t countSize = onDiskWrapper.GetNumCounts();
|
||||
|
||||
std::fstream &file = onDiskWrapper.GetFileSource();
|
||||
file.seekg(filePos);
|
||||
assert(filePos == file.tellg());
|
||||
|
||||
file.read((char*) &m_numChildrenLoad, sizeof(UINT64));
|
||||
|
||||
size_t memAlloc = GetNodeSize(m_numChildrenLoad, onDiskWrapper.GetSourceWordSize(), countSize);
|
||||
m_memLoad = (char*) malloc(memAlloc);
|
||||
|
||||
// go to start of node again
|
||||
file.seekg(filePos);
|
||||
assert(filePos == file.tellg());
|
||||
|
||||
// read everything into memory
|
||||
file.read(m_memLoad, memAlloc);
|
||||
assert(filePos + memAlloc == file.tellg());
|
||||
|
||||
// get value
|
||||
m_value = ((UINT64*)m_memLoad)[1];
|
||||
|
||||
// get counts
|
||||
float *memFloat = (float*) (m_memLoad + sizeof(UINT64) * 2);
|
||||
|
||||
assert(countSize == 1);
|
||||
m_counts[0] = memFloat[0];
|
||||
|
||||
m_memLoadLast = m_memLoad + memAlloc;
|
||||
}
|
||||
|
||||
PhraseNode::~PhraseNode()
|
||||
{
|
||||
free(m_memLoad);
|
||||
//assert(m_saved);
|
||||
}
|
||||
|
||||
float PhraseNode::GetCount(size_t ind) const
|
||||
{
|
||||
return m_counts[ind];
|
||||
}
|
||||
|
||||
void PhraseNode::Save(OnDiskWrapper &onDiskWrapper, size_t pos, size_t tableLimit)
|
||||
{
|
||||
assert(!m_saved);
|
||||
|
||||
// save this node
|
||||
m_targetPhraseColl.Sort(tableLimit);
|
||||
m_targetPhraseColl.Save(onDiskWrapper);
|
||||
m_value = m_targetPhraseColl.GetFilePos();
|
||||
|
||||
size_t numCounts = onDiskWrapper.GetNumCounts();
|
||||
|
||||
size_t memAlloc = GetNodeSize(GetSize(), onDiskWrapper.GetSourceWordSize(), numCounts);
|
||||
char *mem = (char*) malloc(memAlloc);
|
||||
//memset(mem, 0xfe, memAlloc);
|
||||
|
||||
size_t memUsed = 0;
|
||||
UINT64 *memArray = (UINT64*) mem;
|
||||
memArray[0] = GetSize(); // num of children
|
||||
memArray[1] = m_value; // file pos of corresponding target phrases
|
||||
memUsed += 2 * sizeof(UINT64);
|
||||
|
||||
// count info
|
||||
float *memFloat = (float*) (mem + memUsed);
|
||||
assert(numCounts == 1);
|
||||
memFloat[0] = (m_counts.size() == 0) ? DEFAULT_COUNT : m_counts[0]; // if count = 0, put in very large num to make sure its still used. HACK
|
||||
memUsed += sizeof(float) * numCounts;
|
||||
|
||||
// recursively save chm_countsildren
|
||||
ChildColl::iterator iter;
|
||||
for (iter = m_children.begin(); iter != m_children.end(); ++iter) {
|
||||
const Word &childWord = iter->first;
|
||||
PhraseNode &childNode = iter->second;
|
||||
|
||||
// recursive
|
||||
if (!childNode.Saved())
|
||||
childNode.Save(onDiskWrapper, pos + 1, tableLimit);
|
||||
|
||||
char *currMem = mem + memUsed;
|
||||
size_t wordMemUsed = childWord.WriteToMemory(currMem);
|
||||
memUsed += wordMemUsed;
|
||||
|
||||
UINT64 *memArray = (UINT64*) (mem + memUsed);
|
||||
memArray[0] = childNode.GetFilePos();
|
||||
memUsed += sizeof(UINT64);
|
||||
|
||||
}
|
||||
|
||||
// save this node
|
||||
//Moses::DebugMem(mem, memAlloc);
|
||||
assert(memUsed == memAlloc);
|
||||
|
||||
std::fstream &file = onDiskWrapper.GetFileSource();
|
||||
m_filePos = file.tellp();
|
||||
file.seekp(0, ios::end);
|
||||
file.write(mem, memUsed);
|
||||
|
||||
UINT64 endPos = file.tellp();
|
||||
assert(m_filePos + memUsed == endPos);
|
||||
|
||||
free(mem);
|
||||
|
||||
m_children.clear();
|
||||
m_saved = true;
|
||||
}
|
||||
|
||||
void PhraseNode::AddTargetPhrase(const SourcePhrase &sourcePhrase, TargetPhrase *targetPhrase
|
||||
, OnDiskWrapper &onDiskWrapper, size_t tableLimit
|
||||
, const std::vector<float> &counts)
|
||||
{
|
||||
AddTargetPhrase(0, sourcePhrase, targetPhrase, onDiskWrapper, tableLimit, counts);
|
||||
}
|
||||
|
||||
void PhraseNode::AddTargetPhrase(size_t pos, const SourcePhrase &sourcePhrase
|
||||
, TargetPhrase *targetPhrase, OnDiskWrapper &onDiskWrapper
|
||||
, size_t tableLimit, const std::vector<float> &counts)
|
||||
{
|
||||
size_t phraseSize = sourcePhrase.GetSize();
|
||||
if (pos < phraseSize) {
|
||||
const Word &word = sourcePhrase.GetWord(pos);
|
||||
|
||||
PhraseNode &node = m_children[word];
|
||||
if (m_currChild != &node) {
|
||||
// new node
|
||||
node.SetPos(pos);
|
||||
|
||||
if (m_currChild) {
|
||||
m_currChild->Save(onDiskWrapper, pos, tableLimit);
|
||||
}
|
||||
|
||||
m_currChild = &node;
|
||||
}
|
||||
|
||||
node.AddTargetPhrase(pos + 1, sourcePhrase, targetPhrase, onDiskWrapper, tableLimit, counts);
|
||||
} else {
|
||||
// drilled down to the right node
|
||||
m_counts = counts;
|
||||
m_targetPhraseColl.AddTargetPhrase(targetPhrase);
|
||||
}
|
||||
}
|
||||
|
||||
const PhraseNode *PhraseNode::GetChild(const Word &wordSought, OnDiskWrapper &onDiskWrapper) const
|
||||
{
|
||||
const PhraseNode *ret = NULL;
|
||||
|
||||
int l = 0;
|
||||
int r = m_numChildrenLoad - 1;
|
||||
int x;
|
||||
|
||||
while (r >= l) {
|
||||
x = (l + r) / 2;
|
||||
|
||||
Word wordFound;
|
||||
UINT64 childFilePos;
|
||||
GetChild(wordFound, childFilePos, x, onDiskWrapper);
|
||||
|
||||
if (wordSought == wordFound) {
|
||||
ret = new PhraseNode(childFilePos, onDiskWrapper);
|
||||
break;
|
||||
}
|
||||
if (wordSought < wordFound)
|
||||
r = x - 1;
|
||||
else
|
||||
l = x + 1;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
void PhraseNode::GetChild(Word &wordFound, UINT64 &childFilePos, size_t ind, OnDiskWrapper &onDiskWrapper) const
|
||||
{
|
||||
|
||||
size_t wordSize = onDiskWrapper.GetSourceWordSize();
|
||||
size_t childSize = wordSize + sizeof(UINT64);
|
||||
size_t numFactors = onDiskWrapper.GetNumSourceFactors();
|
||||
|
||||
char *currMem = m_memLoad
|
||||
+ sizeof(UINT64) * 2 // size & file pos of target phrase coll
|
||||
+ sizeof(float) * onDiskWrapper.GetNumCounts() // count info
|
||||
+ childSize * ind;
|
||||
|
||||
size_t memRead = ReadChild(wordFound, childFilePos, currMem, numFactors);
|
||||
assert(memRead == childSize);
|
||||
}
|
||||
|
||||
size_t PhraseNode::ReadChild(Word &wordFound, UINT64 &childFilePos, const char *mem, size_t numFactors) const
|
||||
{
|
||||
size_t memRead = wordFound.ReadFromMemory(mem, numFactors);
|
||||
|
||||
const char *currMem = mem + memRead;
|
||||
UINT64 *memArray = (UINT64*) (currMem);
|
||||
childFilePos = memArray[0];
|
||||
|
||||
memRead += sizeof(UINT64);
|
||||
return memRead;
|
||||
}
|
||||
|
||||
const TargetPhraseCollection *PhraseNode::GetTargetPhraseCollection(size_t tableLimit, OnDiskWrapper &onDiskWrapper) const
|
||||
{
|
||||
TargetPhraseCollection *ret = new TargetPhraseCollection();
|
||||
|
||||
if (m_value > 0)
|
||||
ret->ReadFromFile(tableLimit, m_value, onDiskWrapper);
|
||||
else {
|
||||
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
std::ostream& operator<<(std::ostream &out, const PhraseNode &node)
|
||||
{
|
||||
out << "node (" << node.GetFilePos() << "," << node.GetValue() << "," << node.m_pos << ")";
|
||||
return out;
|
||||
}
|
||||
|
||||
}
|
||||
|
103
trunk/OnDiskPt/src/PhraseNode.h
Normal file
103
trunk/OnDiskPt/src/PhraseNode.h
Normal file
@ -0,0 +1,103 @@
|
||||
#pragma once
|
||||
// $Id$
|
||||
/***********************************************************************
|
||||
Moses - factored phrase-based, hierarchical and syntactic language decoder
|
||||
Copyright (C) 2009 Hieu Hoang
|
||||
|
||||
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
|
||||
***********************************************************************/
|
||||
#include <fstream>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include "Word.h"
|
||||
#include "TargetPhraseCollection.h"
|
||||
|
||||
namespace OnDiskPt
|
||||
{
|
||||
|
||||
class OnDiskWrapper;
|
||||
class SourcePhrase;
|
||||
|
||||
class PhraseNode
|
||||
{
|
||||
friend std::ostream& operator<<(std::ostream&, const PhraseNode&);
|
||||
protected:
|
||||
UINT64 m_filePos, m_value;
|
||||
|
||||
typedef std::map<Word, PhraseNode> ChildColl;
|
||||
ChildColl m_children;
|
||||
PhraseNode *m_currChild;
|
||||
bool m_saved;
|
||||
size_t m_pos;
|
||||
std::vector<float> m_counts;
|
||||
|
||||
TargetPhraseCollection m_targetPhraseColl;
|
||||
|
||||
char *m_memLoad, *m_memLoadLast;
|
||||
UINT64 m_numChildrenLoad;
|
||||
|
||||
void AddTargetPhrase(size_t pos, const SourcePhrase &sourcePhrase
|
||||
, TargetPhrase *targetPhrase, OnDiskWrapper &onDiskWrapper
|
||||
, size_t tableLimit, const std::vector<float> &counts);
|
||||
size_t ReadChild(Word &wordFound, UINT64 &childFilePos, const char *mem, size_t numFactors) const;
|
||||
void GetChild(Word &wordFound, UINT64 &childFilePos, size_t ind, OnDiskWrapper &onDiskWrapper) const;
|
||||
|
||||
public:
|
||||
static size_t GetNodeSize(size_t numChildren, size_t wordSize, size_t countSize);
|
||||
|
||||
PhraseNode(); // unsaved node
|
||||
PhraseNode(UINT64 filePos, OnDiskWrapper &onDiskWrapper); // load saved node
|
||||
~PhraseNode();
|
||||
|
||||
void Add(const Word &word, UINT64 nextFilePos, size_t wordSize);
|
||||
void Save(OnDiskWrapper &onDiskWrapper, size_t pos, size_t tableLimit);
|
||||
|
||||
void AddTargetPhrase(const SourcePhrase &sourcePhrase, TargetPhrase *targetPhrase
|
||||
, OnDiskWrapper &onDiskWrapper, size_t tableLimit
|
||||
, const std::vector<float> &counts);
|
||||
|
||||
UINT64 GetFilePos() const {
|
||||
return m_filePos;
|
||||
}
|
||||
UINT64 GetValue() const {
|
||||
return m_value;
|
||||
}
|
||||
void SetValue(UINT64 value) {
|
||||
m_value = value;
|
||||
}
|
||||
size_t GetSize() const {
|
||||
return m_children.size();
|
||||
}
|
||||
|
||||
bool Saved() const {
|
||||
return m_saved;
|
||||
}
|
||||
|
||||
void SetPos(size_t pos) {
|
||||
m_pos = pos;
|
||||
}
|
||||
|
||||
const PhraseNode *GetChild(const Word &wordSought, OnDiskWrapper &onDiskWrapper) const;
|
||||
const TargetPhraseCollection *GetTargetPhraseCollection(size_t tableLimit, OnDiskWrapper &onDiskWrapper) const;
|
||||
|
||||
void AddCounts(const std::vector<float> &counts) {
|
||||
m_counts = counts;
|
||||
}
|
||||
float GetCount(size_t ind) const;
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
28
trunk/OnDiskPt/src/SourcePhrase.cpp
Normal file
28
trunk/OnDiskPt/src/SourcePhrase.cpp
Normal file
@ -0,0 +1,28 @@
|
||||
// $Id$
|
||||
/***********************************************************************
|
||||
Moses - factored phrase-based, hierarchical and syntactic language decoder
|
||||
Copyright (C) 2009 Hieu Hoang
|
||||
|
||||
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
|
||||
***********************************************************************/
|
||||
#include <cassert>
|
||||
#include "SourcePhrase.h"
|
||||
|
||||
namespace OnDiskPt
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
|
35
trunk/OnDiskPt/src/SourcePhrase.h
Normal file
35
trunk/OnDiskPt/src/SourcePhrase.h
Normal file
@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
// $Id$
|
||||
/***********************************************************************
|
||||
Moses - factored phrase-based, hierarchical and syntactic language decoder
|
||||
Copyright (C) 2009 Hieu Hoang
|
||||
|
||||
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
|
||||
***********************************************************************/
|
||||
#include <vector>
|
||||
#include "Phrase.h"
|
||||
#include "Word.h"
|
||||
|
||||
namespace OnDiskPt
|
||||
{
|
||||
|
||||
class SourcePhrase: public Phrase
|
||||
{
|
||||
protected:
|
||||
|
||||
public:
|
||||
};
|
||||
|
||||
}
|
326
trunk/OnDiskPt/src/TargetPhrase.cpp
Normal file
326
trunk/OnDiskPt/src/TargetPhrase.cpp
Normal file
@ -0,0 +1,326 @@
|
||||
// $Id$
|
||||
/***********************************************************************
|
||||
Moses - factored phrase-based, hierarchical and syntactic language decoder
|
||||
Copyright (C) 2009 Hieu Hoang
|
||||
|
||||
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
|
||||
***********************************************************************/
|
||||
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
#include "../../moses/src/Util.h"
|
||||
#include "../../moses/src/TargetPhrase.h"
|
||||
#include "../../moses/src/PhraseDictionary.h"
|
||||
#include "../../moses/src/DummyScoreProducers.h"
|
||||
#include "TargetPhrase.h"
|
||||
#include "OnDiskWrapper.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
namespace OnDiskPt
|
||||
{
|
||||
|
||||
TargetPhrase::TargetPhrase(size_t numScores)
|
||||
:m_scores(numScores)
|
||||
{
|
||||
}
|
||||
|
||||
TargetPhrase::TargetPhrase(const TargetPhrase ©)
|
||||
:Phrase(copy)
|
||||
,m_scores(copy.m_scores)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
TargetPhrase::~TargetPhrase()
|
||||
{
|
||||
}
|
||||
|
||||
void TargetPhrase::SetLHS(Word *lhs)
|
||||
{
|
||||
AddWord(lhs);
|
||||
}
|
||||
|
||||
void TargetPhrase::Create1AlignFromString(const std::string &align1Str)
|
||||
{
|
||||
vector<size_t> alignPoints;
|
||||
Moses::Tokenize<size_t>(alignPoints, align1Str, "-");
|
||||
assert(alignPoints.size() == 2);
|
||||
m_align.push_back(pair<size_t, size_t>(alignPoints[0], alignPoints[1]) );
|
||||
}
|
||||
|
||||
void TargetPhrase::SetScore(float score, size_t ind)
|
||||
{
|
||||
assert(ind < m_scores.size());
|
||||
m_scores[ind] = score;
|
||||
}
|
||||
|
||||
class AlignOrderer
|
||||
{
|
||||
public:
|
||||
bool operator()(const AlignPair &a, const AlignPair &b) const {
|
||||
return a.first < b.first;
|
||||
}
|
||||
};
|
||||
|
||||
void TargetPhrase::SortAlign()
|
||||
{
|
||||
std::sort(m_align.begin(), m_align.end(), AlignOrderer());
|
||||
}
|
||||
|
||||
char *TargetPhrase::WriteToMemory(OnDiskWrapper &onDiskWrapper, size_t &memUsed) const
|
||||
{
|
||||
size_t phraseSize = GetSize();
|
||||
size_t targetWordSize = onDiskWrapper.GetTargetWordSize();
|
||||
|
||||
size_t memNeeded = sizeof(UINT64) // num of words
|
||||
+ targetWordSize * phraseSize; // actual words. lhs as last words
|
||||
memUsed = 0;
|
||||
UINT64 *mem = (UINT64*) malloc(memNeeded);
|
||||
|
||||
// write size
|
||||
mem[0] = phraseSize;
|
||||
memUsed += sizeof(UINT64);
|
||||
|
||||
// write each word
|
||||
for (size_t pos = 0; pos < phraseSize; ++pos) {
|
||||
const Word &word = GetWord(pos);
|
||||
char *currPtr = (char*)mem + memUsed;
|
||||
memUsed += word.WriteToMemory((char*) currPtr);
|
||||
}
|
||||
|
||||
assert(memUsed == memNeeded);
|
||||
return (char *) mem;
|
||||
}
|
||||
|
||||
void TargetPhrase::Save(OnDiskWrapper &onDiskWrapper)
|
||||
{
|
||||
// save in target ind
|
||||
size_t memUsed;
|
||||
char *mem = WriteToMemory(onDiskWrapper, memUsed);
|
||||
|
||||
std::fstream &file = onDiskWrapper.GetFileTargetInd();
|
||||
|
||||
UINT64 startPos = file.tellp();
|
||||
|
||||
file.seekp(0, ios::end);
|
||||
file.write(mem, memUsed);
|
||||
|
||||
UINT64 endPos = file.tellp();
|
||||
assert(startPos + memUsed == endPos);
|
||||
|
||||
m_filePos = startPos;
|
||||
free(mem);
|
||||
}
|
||||
|
||||
char *TargetPhrase::WriteOtherInfoToMemory(OnDiskWrapper &onDiskWrapper, size_t &memUsed) const
|
||||
{
|
||||
// allocate mem
|
||||
size_t numScores = onDiskWrapper.GetNumScores()
|
||||
,numAlign = GetAlign().size();
|
||||
|
||||
size_t memNeeded = sizeof(UINT64); // file pos (phrase id)
|
||||
memNeeded += sizeof(UINT64) + 2 * sizeof(UINT64) * numAlign; // align
|
||||
memNeeded += sizeof(float) * numScores; // scores
|
||||
|
||||
char *mem = (char*) malloc(memNeeded);
|
||||
//memset(mem, 0, memNeeded);
|
||||
|
||||
memUsed = 0;
|
||||
|
||||
// phrase id
|
||||
memcpy(mem, &m_filePos, sizeof(UINT64));
|
||||
memUsed += sizeof(UINT64);
|
||||
|
||||
// align
|
||||
memUsed += WriteAlignToMemory(mem + memUsed);
|
||||
|
||||
// scores
|
||||
memUsed += WriteScoresToMemory(mem + memUsed);
|
||||
|
||||
//DebugMem(mem, memNeeded);
|
||||
assert(memNeeded == memUsed);
|
||||
return mem;
|
||||
}
|
||||
|
||||
size_t TargetPhrase::WriteAlignToMemory(char *mem) const
|
||||
{
|
||||
size_t memUsed = 0;
|
||||
|
||||
// num of alignments
|
||||
UINT64 numAlign = m_align.size();
|
||||
memcpy(mem, &numAlign, sizeof(numAlign));
|
||||
memUsed += sizeof(numAlign);
|
||||
|
||||
// actual alignments
|
||||
AlignType::const_iterator iter;
|
||||
for (iter = m_align.begin(); iter != m_align.end(); ++iter) {
|
||||
const AlignPair &alignPair = *iter;
|
||||
|
||||
memcpy(mem + memUsed, &alignPair.first, sizeof(alignPair.first));
|
||||
memUsed += sizeof(alignPair.first);
|
||||
|
||||
memcpy(mem + memUsed, &alignPair.second, sizeof(alignPair.second));
|
||||
memUsed += sizeof(alignPair.second);
|
||||
}
|
||||
|
||||
return memUsed;
|
||||
}
|
||||
|
||||
size_t TargetPhrase::WriteScoresToMemory(char *mem) const
|
||||
{
|
||||
float *scoreMem = (float*) mem;
|
||||
|
||||
for (size_t ind = 0; ind < m_scores.size(); ++ind)
|
||||
scoreMem[ind] = m_scores[ind];
|
||||
|
||||
size_t memUsed = sizeof(float) * m_scores.size();
|
||||
return memUsed;
|
||||
}
|
||||
|
||||
|
||||
Moses::TargetPhrase *TargetPhrase::ConvertToMoses(const std::vector<Moses::FactorType> & /*inputFactors */
|
||||
, const std::vector<Moses::FactorType> &outputFactors
|
||||
, const Vocab &vocab
|
||||
, const Moses::PhraseDictionary &phraseDict
|
||||
, const std::vector<float> &weightT
|
||||
, const Moses::WordPenaltyProducer* wpProducer
|
||||
, const Moses::LMList &lmList) const
|
||||
{
|
||||
Moses::TargetPhrase *ret = new Moses::TargetPhrase(Moses::Output);
|
||||
|
||||
// words
|
||||
size_t phraseSize = GetSize();
|
||||
assert(phraseSize > 0); // last word is lhs
|
||||
--phraseSize;
|
||||
|
||||
for (size_t pos = 0; pos < phraseSize; ++pos) {
|
||||
Moses::Word *mosesWord = GetWord(pos).ConvertToMoses(Moses::Output, outputFactors, vocab);
|
||||
ret->AddWord(*mosesWord);
|
||||
delete mosesWord;
|
||||
}
|
||||
|
||||
// scores
|
||||
ret->SetScoreChart(phraseDict.GetFeature(), m_scores, weightT, lmList, wpProducer);
|
||||
|
||||
// alignments
|
||||
std::set<std::pair<size_t, size_t> > alignmentInfo;
|
||||
for (size_t ind = 0; ind < m_align.size(); ++ind) {
|
||||
const std::pair<size_t, size_t> &entry = m_align[ind];
|
||||
alignmentInfo.insert(entry);
|
||||
}
|
||||
ret->SetAlignmentInfo(alignmentInfo);
|
||||
|
||||
Moses::Word *lhs = GetWord(GetSize() - 1).ConvertToMoses(Moses::Output, outputFactors, vocab);
|
||||
ret->SetTargetLHS(*lhs);
|
||||
delete lhs;
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
UINT64 TargetPhrase::ReadOtherInfoFromFile(UINT64 filePos, std::fstream &fileTPColl)
|
||||
{
|
||||
assert(filePos == fileTPColl.tellg());
|
||||
|
||||
UINT64 memUsed = 0;
|
||||
fileTPColl.read((char*) &m_filePos, sizeof(UINT64));
|
||||
memUsed += sizeof(UINT64);
|
||||
assert(m_filePos != 0);
|
||||
|
||||
memUsed += ReadAlignFromFile(fileTPColl);
|
||||
assert((memUsed + filePos) == fileTPColl.tellg());
|
||||
|
||||
memUsed += ReadScoresFromFile(fileTPColl);
|
||||
assert((memUsed + filePos) == fileTPColl.tellg());
|
||||
|
||||
return memUsed;
|
||||
}
|
||||
|
||||
UINT64 TargetPhrase::ReadFromFile(std::fstream &fileTP, size_t numFactors)
|
||||
{
|
||||
UINT64 bytesRead = 0;
|
||||
|
||||
fileTP.seekg(m_filePos);
|
||||
|
||||
UINT64 numWords;
|
||||
fileTP.read((char*) &numWords, sizeof(UINT64));
|
||||
bytesRead += sizeof(UINT64);
|
||||
|
||||
for (size_t ind = 0; ind < numWords; ++ind) {
|
||||
Word *word = new Word();
|
||||
bytesRead += word->ReadFromFile(fileTP, numFactors);
|
||||
AddWord(word);
|
||||
}
|
||||
|
||||
return bytesRead;
|
||||
}
|
||||
|
||||
UINT64 TargetPhrase::ReadAlignFromFile(std::fstream &fileTPColl)
|
||||
{
|
||||
UINT64 bytesRead = 0;
|
||||
|
||||
UINT64 numAlign;
|
||||
fileTPColl.read((char*) &numAlign, sizeof(UINT64));
|
||||
bytesRead += sizeof(UINT64);
|
||||
|
||||
for (size_t ind = 0; ind < numAlign; ++ind) {
|
||||
AlignPair alignPair;
|
||||
fileTPColl.read((char*) &alignPair.first, sizeof(UINT64));
|
||||
fileTPColl.read((char*) &alignPair.second, sizeof(UINT64));
|
||||
m_align.push_back(alignPair);
|
||||
|
||||
bytesRead += sizeof(UINT64) * 2;
|
||||
}
|
||||
|
||||
return bytesRead;
|
||||
}
|
||||
|
||||
UINT64 TargetPhrase::ReadScoresFromFile(std::fstream &fileTPColl)
|
||||
{
|
||||
assert(m_scores.size() > 0);
|
||||
|
||||
UINT64 bytesRead = 0;
|
||||
|
||||
for (size_t ind = 0; ind < m_scores.size(); ++ind) {
|
||||
fileTPColl.read((char*) &m_scores[ind], sizeof(float));
|
||||
|
||||
bytesRead += sizeof(float);
|
||||
}
|
||||
|
||||
std::transform(m_scores.begin(),m_scores.end(),m_scores.begin(), Moses::TransformScore);
|
||||
std::transform(m_scores.begin(),m_scores.end(),m_scores.begin(), Moses::FloorScore);
|
||||
|
||||
return bytesRead;
|
||||
}
|
||||
|
||||
std::ostream& operator<<(std::ostream &out, const TargetPhrase &phrase)
|
||||
{
|
||||
out << (const Phrase&) phrase << ", " ;
|
||||
|
||||
for (size_t ind = 0; ind < phrase.m_align.size(); ++ind) {
|
||||
const AlignPair &alignPair = phrase.m_align[ind];
|
||||
out << alignPair.first << "-" << alignPair.second << " ";
|
||||
}
|
||||
out << ", ";
|
||||
|
||||
for (size_t ind = 0; ind < phrase.m_scores.size(); ++ind) {
|
||||
out << phrase.m_scores[ind] << " ";
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
96
trunk/OnDiskPt/src/TargetPhrase.h
Normal file
96
trunk/OnDiskPt/src/TargetPhrase.h
Normal file
@ -0,0 +1,96 @@
|
||||
#pragma once
|
||||
// $Id$
|
||||
/***********************************************************************
|
||||
Moses - factored phrase-based, hierarchical and syntactic language decoder
|
||||
Copyright (C) 2009 Hieu Hoang
|
||||
|
||||
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
|
||||
***********************************************************************/
|
||||
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "Word.h"
|
||||
#include "Phrase.h"
|
||||
|
||||
namespace Moses
|
||||
{
|
||||
class PhraseDictionary;
|
||||
class TargetPhrase;
|
||||
class LMList;
|
||||
class Phrase;
|
||||
class WordPenaltyProducer;
|
||||
}
|
||||
|
||||
namespace OnDiskPt
|
||||
{
|
||||
|
||||
typedef std::pair<UINT64, UINT64> AlignPair;
|
||||
typedef std::vector<AlignPair> AlignType;
|
||||
|
||||
class TargetPhrase: public Phrase
|
||||
{
|
||||
friend std::ostream& operator<<(std::ostream&, const TargetPhrase&);
|
||||
protected:
|
||||
AlignType m_align;
|
||||
|
||||
std::vector<float> m_scores;
|
||||
UINT64 m_filePos;
|
||||
|
||||
size_t WriteAlignToMemory(char *mem) const;
|
||||
size_t WriteScoresToMemory(char *mem) const;
|
||||
|
||||
UINT64 ReadAlignFromFile(std::fstream &fileTPColl);
|
||||
UINT64 ReadScoresFromFile(std::fstream &fileTPColl);
|
||||
|
||||
public:
|
||||
TargetPhrase(size_t numScores);
|
||||
TargetPhrase(const TargetPhrase ©);
|
||||
virtual ~TargetPhrase();
|
||||
|
||||
void SetLHS(Word *lhs);
|
||||
|
||||
void Create1AlignFromString(const std::string &align1Str);
|
||||
void SetScore(float score, size_t ind);
|
||||
|
||||
const AlignType &GetAlign() const {
|
||||
return m_align;
|
||||
}
|
||||
void SortAlign();
|
||||
|
||||
char *WriteToMemory(OnDiskWrapper &onDiskWrapper, size_t &memUsed) const;
|
||||
char *WriteOtherInfoToMemory(OnDiskWrapper &onDiskWrapper, size_t &memUsed) const;
|
||||
void Save(OnDiskWrapper &onDiskWrapper);
|
||||
|
||||
UINT64 GetFilePos() const {
|
||||
return m_filePos;
|
||||
}
|
||||
float GetScore(size_t ind) const {
|
||||
return m_scores[ind];
|
||||
}
|
||||
|
||||
Moses::TargetPhrase *ConvertToMoses(const std::vector<Moses::FactorType> &inputFactors
|
||||
, const std::vector<Moses::FactorType> &outputFactors
|
||||
, const Vocab &vocab
|
||||
, const Moses::PhraseDictionary &phraseDict
|
||||
, const std::vector<float> &weightT
|
||||
, const Moses::WordPenaltyProducer* wpProducer
|
||||
, const Moses::LMList &lmList) const;
|
||||
UINT64 ReadOtherInfoFromFile(UINT64 filePos, std::fstream &fileTPColl);
|
||||
UINT64 ReadFromFile(std::fstream &fileTP, size_t numFactors);
|
||||
|
||||
};
|
||||
|
||||
}
|
201
trunk/OnDiskPt/src/TargetPhraseCollection.cpp
Normal file
201
trunk/OnDiskPt/src/TargetPhraseCollection.cpp
Normal file
@ -0,0 +1,201 @@
|
||||
// $Id$
|
||||
/***********************************************************************
|
||||
Moses - factored phrase-based, hierarchical and syntactic language decoder
|
||||
Copyright (C) 2009 Hieu Hoang
|
||||
|
||||
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
|
||||
***********************************************************************/
|
||||
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
#include "../../moses/src/Util.h"
|
||||
#include "../../moses/src/TargetPhraseCollection.h"
|
||||
#include "../../moses/src/PhraseDictionary.h"
|
||||
#include "TargetPhraseCollection.h"
|
||||
#include "Vocab.h"
|
||||
#include "OnDiskWrapper.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
namespace OnDiskPt
|
||||
{
|
||||
|
||||
size_t TargetPhraseCollection::s_sortScoreInd;
|
||||
|
||||
TargetPhraseCollection::TargetPhraseCollection()
|
||||
:m_filePos(777)
|
||||
{}
|
||||
|
||||
TargetPhraseCollection::TargetPhraseCollection(const TargetPhraseCollection ©)
|
||||
:m_filePos(copy.m_filePos)
|
||||
,m_debugStr(copy.m_debugStr)
|
||||
{
|
||||
}
|
||||
|
||||
TargetPhraseCollection::~TargetPhraseCollection()
|
||||
{
|
||||
Moses::RemoveAllInColl(m_coll);
|
||||
}
|
||||
|
||||
void TargetPhraseCollection::AddTargetPhrase(TargetPhrase *targetPhrase)
|
||||
{
|
||||
m_coll.push_back(targetPhrase);
|
||||
}
|
||||
|
||||
void TargetPhraseCollection::Sort(size_t tableLimit)
|
||||
{
|
||||
std::sort(m_coll.begin(), m_coll.end(), TargetPhraseOrderByScore());
|
||||
|
||||
if (m_coll.size() > tableLimit) {
|
||||
CollType::iterator iter;
|
||||
for (iter = m_coll.begin() + tableLimit ; iter != m_coll.end(); ++iter) {
|
||||
delete *iter;
|
||||
}
|
||||
m_coll.resize(tableLimit);
|
||||
}
|
||||
}
|
||||
|
||||
void TargetPhraseCollection::Save(OnDiskWrapper &onDiskWrapper)
|
||||
{
|
||||
std::fstream &file = onDiskWrapper.GetFileTargetColl();
|
||||
|
||||
size_t memUsed = sizeof(UINT64);
|
||||
char *mem = (char*) malloc(memUsed);
|
||||
|
||||
// size of coll
|
||||
UINT64 numPhrases = GetSize();
|
||||
((UINT64*)mem)[0] = numPhrases;
|
||||
|
||||
// MAIN LOOP
|
||||
CollType::iterator iter;
|
||||
for (iter = m_coll.begin(); iter != m_coll.end(); ++iter) {
|
||||
// save phrase
|
||||
TargetPhrase &targetPhrase = **iter;
|
||||
targetPhrase.Save(onDiskWrapper);
|
||||
|
||||
// save coll
|
||||
size_t memUsedTPOtherInfo;
|
||||
char *memTPOtherInfo = targetPhrase.WriteOtherInfoToMemory(onDiskWrapper, memUsedTPOtherInfo);
|
||||
|
||||
// expand existing mem
|
||||
mem = (char*) realloc(mem, memUsed + memUsedTPOtherInfo);
|
||||
memcpy(mem + memUsed, memTPOtherInfo, memUsedTPOtherInfo);
|
||||
memUsed += memUsedTPOtherInfo;
|
||||
|
||||
free(memTPOtherInfo);
|
||||
}
|
||||
|
||||
// total number of bytes
|
||||
//((UINT64*)mem)[0] = (UINT64) memUsed;
|
||||
|
||||
UINT64 startPos = file.tellp();
|
||||
file.seekp(0, ios::end);
|
||||
file.write((char*) mem, memUsed);
|
||||
|
||||
free(mem);
|
||||
|
||||
UINT64 endPos = file.tellp();
|
||||
assert(startPos + memUsed == endPos);
|
||||
|
||||
m_filePos = startPos;
|
||||
|
||||
}
|
||||
|
||||
Moses::TargetPhraseCollection *TargetPhraseCollection::ConvertToMoses(const std::vector<Moses::FactorType> &inputFactors
|
||||
, const std::vector<Moses::FactorType> &outputFactors
|
||||
, const Moses::PhraseDictionary &phraseDict
|
||||
, const std::vector<float> &weightT
|
||||
, const Moses::WordPenaltyProducer* wpProducer
|
||||
, const Moses::LMList &lmList
|
||||
, const std::string & /* filePath */
|
||||
, Vocab &vocab) const
|
||||
{
|
||||
Moses::TargetPhraseCollection *ret = new Moses::TargetPhraseCollection();
|
||||
|
||||
CollType::const_iterator iter;
|
||||
for (iter = m_coll.begin(); iter != m_coll.end(); ++iter) {
|
||||
const TargetPhrase &tp = **iter;
|
||||
Moses::TargetPhrase *mosesPhrase = tp.ConvertToMoses(inputFactors, outputFactors
|
||||
, vocab
|
||||
, phraseDict
|
||||
, weightT
|
||||
, wpProducer
|
||||
, lmList);
|
||||
|
||||
/*
|
||||
// debugging output
|
||||
stringstream strme;
|
||||
strme << filePath << " " << *mosesPhrase;
|
||||
mosesPhrase->SetDebugOutput(strme.str());
|
||||
*/
|
||||
|
||||
ret->Add(mosesPhrase);
|
||||
}
|
||||
|
||||
ret->Sort(true, phraseDict.GetTableLimit());
|
||||
|
||||
return ret;
|
||||
|
||||
}
|
||||
|
||||
void TargetPhraseCollection::ReadFromFile(size_t tableLimit, UINT64 filePos, OnDiskWrapper &onDiskWrapper)
|
||||
{
|
||||
fstream &fileTPColl = onDiskWrapper.GetFileTargetColl();
|
||||
fstream &fileTP = onDiskWrapper.GetFileTargetInd();
|
||||
|
||||
size_t numScores = onDiskWrapper.GetNumScores();
|
||||
size_t numTargetFactors = onDiskWrapper.GetNumTargetFactors();
|
||||
|
||||
UINT64 numPhrases;
|
||||
|
||||
UINT64 currFilePos = filePos;
|
||||
fileTPColl.seekg(filePos);
|
||||
fileTPColl.read((char*) &numPhrases, sizeof(UINT64));
|
||||
|
||||
// table limit
|
||||
numPhrases = std::min(numPhrases, (UINT64) tableLimit);
|
||||
|
||||
currFilePos += sizeof(UINT64);
|
||||
|
||||
for (size_t ind = 0; ind < numPhrases; ++ind) {
|
||||
TargetPhrase *tp = new TargetPhrase(numScores);
|
||||
|
||||
UINT64 sizeOtherInfo = tp->ReadOtherInfoFromFile(currFilePos, fileTPColl);
|
||||
tp->ReadFromFile(fileTP, numTargetFactors);
|
||||
|
||||
currFilePos += sizeOtherInfo;
|
||||
|
||||
m_coll.push_back(tp);
|
||||
}
|
||||
}
|
||||
|
||||
UINT64 TargetPhraseCollection::GetFilePos() const
|
||||
{
|
||||
return m_filePos;
|
||||
}
|
||||
|
||||
const std::string TargetPhraseCollection::GetDebugStr() const
|
||||
{
|
||||
return m_debugStr;
|
||||
}
|
||||
|
||||
void TargetPhraseCollection::SetDebugStr(const std::string &str)
|
||||
{
|
||||
m_debugStr = str;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
85
trunk/OnDiskPt/src/TargetPhraseCollection.h
Normal file
85
trunk/OnDiskPt/src/TargetPhraseCollection.h
Normal file
@ -0,0 +1,85 @@
|
||||
// $Id$
|
||||
/***********************************************************************
|
||||
Moses - factored phrase-based, hierarchical and syntactic language decoder
|
||||
Copyright (C) 2009 Hieu Hoang
|
||||
|
||||
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
|
||||
***********************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "TargetPhrase.h"
|
||||
#include "Vocab.h"
|
||||
|
||||
namespace Moses
|
||||
{
|
||||
class TargetPhraseCollection;
|
||||
class PhraseDictionary;
|
||||
class LMList;
|
||||
class WordPenaltyProducer;
|
||||
}
|
||||
|
||||
namespace OnDiskPt
|
||||
{
|
||||
|
||||
class TargetPhraseCollection
|
||||
{
|
||||
class TargetPhraseOrderByScore
|
||||
{
|
||||
public:
|
||||
bool operator()(const TargetPhrase* a, const TargetPhrase *b) const {
|
||||
return a->GetScore(s_sortScoreInd) > b->GetScore(s_sortScoreInd);
|
||||
}
|
||||
};
|
||||
|
||||
protected:
|
||||
typedef std::vector<TargetPhrase*> CollType;
|
||||
CollType m_coll;
|
||||
UINT64 m_filePos;
|
||||
std::string m_debugStr;
|
||||
|
||||
public:
|
||||
static size_t s_sortScoreInd;
|
||||
|
||||
TargetPhraseCollection();
|
||||
TargetPhraseCollection(const TargetPhraseCollection ©);
|
||||
|
||||
~TargetPhraseCollection();
|
||||
void AddTargetPhrase(TargetPhrase *targetPhrase);
|
||||
void Sort(size_t tableLimit);
|
||||
|
||||
void Save(OnDiskWrapper &onDiskWrapper);
|
||||
|
||||
size_t GetSize() const {
|
||||
return m_coll.size();
|
||||
}
|
||||
UINT64 GetFilePos() const;
|
||||
|
||||
Moses::TargetPhraseCollection *ConvertToMoses(const std::vector<Moses::FactorType> &inputFactors
|
||||
, const std::vector<Moses::FactorType> &outputFactors
|
||||
, const Moses::PhraseDictionary &phraseDict
|
||||
, const std::vector<float> &weightT
|
||||
, const Moses::WordPenaltyProducer* wpProducer
|
||||
, const Moses::LMList &lmList
|
||||
, const std::string &filePath
|
||||
, Vocab &vocab) const;
|
||||
void ReadFromFile(size_t tableLimit, UINT64 filePos, OnDiskWrapper &onDiskWrapper);
|
||||
|
||||
const std::string GetDebugStr() const;
|
||||
void SetDebugStr(const std::string &str);
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
109
trunk/OnDiskPt/src/Vocab.cpp
Normal file
109
trunk/OnDiskPt/src/Vocab.cpp
Normal file
@ -0,0 +1,109 @@
|
||||
// $Id$
|
||||
/***********************************************************************
|
||||
Moses - factored phrase-based, hierarchical and syntactic language decoder
|
||||
Copyright (C) 2009 Hieu Hoang
|
||||
|
||||
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
|
||||
***********************************************************************/
|
||||
#include <string>
|
||||
#include <fstream>
|
||||
#include "OnDiskWrapper.h"
|
||||
#include "Vocab.h"
|
||||
#include "../../moses/src/FactorCollection.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
namespace OnDiskPt
|
||||
{
|
||||
|
||||
bool Vocab::Load(OnDiskWrapper &onDiskWrapper)
|
||||
{
|
||||
fstream &file = onDiskWrapper.GetFileVocab();
|
||||
|
||||
string line;
|
||||
while(getline(file, line)) {
|
||||
vector<string> tokens;
|
||||
Moses::Tokenize(tokens, line);
|
||||
assert(tokens.size() == 2);
|
||||
const string &key = tokens[0];
|
||||
m_vocabColl[key] = Moses::Scan<UINT64>(tokens[1]);
|
||||
}
|
||||
|
||||
// create lookup
|
||||
// assume contiguous vocab id
|
||||
m_lookup.resize(m_vocabColl.size() + 1);
|
||||
|
||||
CollType::const_iterator iter;
|
||||
for (iter = m_vocabColl.begin(); iter != m_vocabColl.end(); ++iter) {
|
||||
UINT32 vocabId = iter->second;
|
||||
const std::string &word = iter->first;
|
||||
|
||||
m_lookup[vocabId] = word;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void Vocab::Save(OnDiskWrapper &onDiskWrapper)
|
||||
{
|
||||
fstream &file = onDiskWrapper.GetFileVocab();
|
||||
CollType::const_iterator iterVocab;
|
||||
for (iterVocab = m_vocabColl.begin(); iterVocab != m_vocabColl.end(); ++iterVocab) {
|
||||
const string &word = iterVocab->first;
|
||||
UINT32 vocabId = iterVocab->second;
|
||||
|
||||
file << word << " " << vocabId << endl;
|
||||
}
|
||||
}
|
||||
|
||||
UINT64 Vocab::AddVocabId(const std::string &factorString)
|
||||
{
|
||||
// find string id
|
||||
CollType::const_iterator iter = m_vocabColl.find(factorString);
|
||||
if (iter == m_vocabColl.end()) {
|
||||
// add new vocab entry
|
||||
m_vocabColl[factorString] = m_nextId;
|
||||
return m_nextId++;
|
||||
} else {
|
||||
// return existing entry
|
||||
return iter->second;
|
||||
}
|
||||
}
|
||||
|
||||
UINT64 Vocab::GetVocabId(const std::string &factorString, bool &found) const
|
||||
{
|
||||
// find string id
|
||||
CollType::const_iterator iter = m_vocabColl.find(factorString);
|
||||
if (iter == m_vocabColl.end()) {
|
||||
found = false;
|
||||
return 0; //return whatever
|
||||
} else {
|
||||
// return existing entry
|
||||
found = true;
|
||||
return iter->second;
|
||||
}
|
||||
}
|
||||
|
||||
const Moses::Factor *Vocab::GetFactor(UINT32 vocabId, Moses::FactorType factorType, Moses::FactorDirection direction, bool isNonTerminal) const
|
||||
{
|
||||
string str = GetString(vocabId);
|
||||
if (isNonTerminal) {
|
||||
str = str.substr(1, str.size() - 2);
|
||||
}
|
||||
const Moses::Factor *factor = Moses::FactorCollection::Instance().AddFactor(direction, factorType, str);
|
||||
return factor;
|
||||
}
|
||||
|
||||
}
|
61
trunk/OnDiskPt/src/Vocab.h
Normal file
61
trunk/OnDiskPt/src/Vocab.h
Normal file
@ -0,0 +1,61 @@
|
||||
#pragma once
|
||||
// $Id$
|
||||
/***********************************************************************
|
||||
Moses - factored phrase-based, hierarchical and syntactic language decoder
|
||||
Copyright (C) 2009 Hieu Hoang
|
||||
|
||||
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
|
||||
***********************************************************************/
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include "../../moses/src/TypeDef.h"
|
||||
|
||||
namespace Moses
|
||||
{
|
||||
class Factor;
|
||||
}
|
||||
|
||||
namespace OnDiskPt
|
||||
{
|
||||
|
||||
class OnDiskWrapper;
|
||||
|
||||
class Vocab
|
||||
{
|
||||
protected:
|
||||
typedef std::map<std::string, UINT64> CollType;
|
||||
CollType m_vocabColl;
|
||||
|
||||
std::vector<std::string> m_lookup; // opposite of m_vocabColl
|
||||
UINT64 m_nextId; // starts @ 1
|
||||
|
||||
const std::string &GetString(UINT32 vocabId) const {
|
||||
return m_lookup[vocabId];
|
||||
}
|
||||
|
||||
public:
|
||||
Vocab()
|
||||
:m_nextId(1)
|
||||
{}
|
||||
UINT64 AddVocabId(const std::string &factorString);
|
||||
UINT64 GetVocabId(const std::string &factorString, bool &found) const;
|
||||
const Moses::Factor *GetFactor(UINT32 vocabId, Moses::FactorType factorType, Moses::FactorDirection direction, bool isNonTerminal) const;
|
||||
|
||||
bool Load(OnDiskWrapper &onDiskWrapper);
|
||||
void Save(OnDiskWrapper &onDiskWrapper);
|
||||
};
|
||||
|
||||
}
|
||||
|
162
trunk/OnDiskPt/src/Word.cpp
Normal file
162
trunk/OnDiskPt/src/Word.cpp
Normal file
@ -0,0 +1,162 @@
|
||||
// $Id$
|
||||
/***********************************************************************
|
||||
Moses - factored phrase-based, hierarchical and syntactic language decoder
|
||||
Copyright (C) 2009 Hieu Hoang
|
||||
|
||||
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
|
||||
***********************************************************************/
|
||||
|
||||
#include "../../moses/src/Util.h"
|
||||
#include "../../moses/src/Word.h"
|
||||
#include "Word.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
namespace OnDiskPt
|
||||
{
|
||||
|
||||
Word::Word(const Word ©)
|
||||
:m_isNonTerminal(copy.m_isNonTerminal)
|
||||
,m_factors(copy.m_factors)
|
||||
{}
|
||||
|
||||
Word::~Word()
|
||||
{}
|
||||
|
||||
void Word::CreateFromString(const std::string &inString, Vocab &vocab)
|
||||
{
|
||||
if (inString.substr(0, 1) == "[" && inString.substr(inString.size() - 1, 1) == "]") {
|
||||
// non-term
|
||||
m_isNonTerminal = true;
|
||||
} else {
|
||||
m_isNonTerminal = false;
|
||||
}
|
||||
|
||||
m_factors.resize(1);
|
||||
m_factors[0] = vocab.AddVocabId(inString);
|
||||
}
|
||||
|
||||
size_t Word::WriteToMemory(char *mem) const
|
||||
{
|
||||
UINT64 *vocabMem = (UINT64*) mem;
|
||||
|
||||
// factors
|
||||
for (size_t ind = 0; ind < m_factors.size(); ind++)
|
||||
vocabMem[ind] = m_factors[ind];
|
||||
|
||||
size_t size = sizeof(UINT64) * m_factors.size();
|
||||
|
||||
// is non-term
|
||||
char bNonTerm = (char) m_isNonTerminal;
|
||||
mem[size] = bNonTerm;
|
||||
++size;
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
size_t Word::ReadFromMemory(const char *mem, size_t numFactors)
|
||||
{
|
||||
m_factors.resize(numFactors);
|
||||
UINT64 *vocabMem = (UINT64*) mem;
|
||||
|
||||
// factors
|
||||
for (size_t ind = 0; ind < m_factors.size(); ind++)
|
||||
m_factors[ind] = vocabMem[ind];
|
||||
|
||||
size_t memUsed = sizeof(UINT64) * m_factors.size();
|
||||
|
||||
// is non-term
|
||||
char bNonTerm;
|
||||
bNonTerm = mem[memUsed];
|
||||
m_isNonTerminal = (bool) bNonTerm;
|
||||
++memUsed;
|
||||
|
||||
return memUsed;
|
||||
}
|
||||
|
||||
size_t Word::ReadFromFile(std::fstream &file, size_t numFactors)
|
||||
{
|
||||
size_t memAlloc = numFactors * sizeof(UINT64) + sizeof(char);
|
||||
char *mem = (char*) malloc(memAlloc);
|
||||
file.read(mem, memAlloc);
|
||||
|
||||
size_t memUsed = ReadFromMemory(mem, numFactors);
|
||||
assert(memAlloc == memUsed);
|
||||
free(mem);
|
||||
|
||||
return memUsed;
|
||||
}
|
||||
|
||||
Moses::Word *Word::ConvertToMoses(Moses::FactorDirection direction
|
||||
, const std::vector<Moses::FactorType> &outputFactorsVec
|
||||
, const Vocab &vocab) const
|
||||
{
|
||||
Moses::Word *ret = new Moses::Word(m_isNonTerminal);
|
||||
|
||||
for (size_t ind = 0; ind < m_factors.size(); ++ind) {
|
||||
Moses::FactorType factorType = outputFactorsVec[ind];
|
||||
UINT32 vocabId = m_factors[ind];
|
||||
const Moses::Factor *factor = vocab.GetFactor(vocabId, factorType, direction, m_isNonTerminal);
|
||||
ret->SetFactor(factorType, factor);
|
||||
}
|
||||
|
||||
return ret;
|
||||
|
||||
}
|
||||
|
||||
int Word::Compare(const Word &compare) const
|
||||
{
|
||||
int ret;
|
||||
|
||||
if (m_isNonTerminal != compare.m_isNonTerminal)
|
||||
return m_isNonTerminal ?-1 : 1;
|
||||
|
||||
if (m_factors < compare.m_factors)
|
||||
ret = -1;
|
||||
else if (m_factors > compare.m_factors)
|
||||
ret = 1;
|
||||
else
|
||||
ret = 0;
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool Word::operator<(const Word &compare) const
|
||||
{
|
||||
int ret = Compare(compare);
|
||||
return ret < 0;
|
||||
}
|
||||
|
||||
bool Word::operator==(const Word &compare) const
|
||||
{
|
||||
int ret = Compare(compare);
|
||||
return ret == 0;
|
||||
}
|
||||
|
||||
std::ostream& operator<<(std::ostream &out, const Word &word)
|
||||
{
|
||||
out << "[";
|
||||
|
||||
std::vector<UINT64>::const_iterator iter;
|
||||
for (iter = word.m_factors.begin(); iter != word.m_factors.end(); ++iter) {
|
||||
out << *iter << "|";
|
||||
}
|
||||
|
||||
out << (word.m_isNonTerminal ? "n" : "t");
|
||||
out << "]";
|
||||
|
||||
return out;
|
||||
}
|
||||
}
|
79
trunk/OnDiskPt/src/Word.h
Normal file
79
trunk/OnDiskPt/src/Word.h
Normal file
@ -0,0 +1,79 @@
|
||||
#pragma once
|
||||
// $Id$
|
||||
/***********************************************************************
|
||||
Moses - factored phrase-based, hierarchical and syntactic language decoder
|
||||
Copyright (C) 2009 Hieu Hoang
|
||||
|
||||
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
|
||||
***********************************************************************/
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include "Vocab.h"
|
||||
|
||||
namespace Moses
|
||||
{
|
||||
class Word;
|
||||
}
|
||||
|
||||
namespace OnDiskPt
|
||||
{
|
||||
|
||||
class Word
|
||||
{
|
||||
friend std::ostream& operator<<(std::ostream&, const Word&);
|
||||
|
||||
protected:
|
||||
bool m_isNonTerminal;
|
||||
std::vector<UINT64> m_factors;
|
||||
|
||||
public:
|
||||
explicit Word()
|
||||
{}
|
||||
|
||||
explicit Word(size_t numFactors, bool isNonTerminal)
|
||||
:m_isNonTerminal(isNonTerminal)
|
||||
,m_factors(numFactors)
|
||||
{}
|
||||
|
||||
Word(const Word ©);
|
||||
~Word();
|
||||
|
||||
|
||||
void CreateFromString(const std::string &inString, Vocab &vocab);
|
||||
bool IsNonTerminal() const {
|
||||
return m_isNonTerminal;
|
||||
}
|
||||
|
||||
size_t WriteToMemory(char *mem) const;
|
||||
size_t ReadFromMemory(const char *mem, size_t numFactors);
|
||||
size_t ReadFromFile(std::fstream &file, size_t numFactors);
|
||||
|
||||
void SetVocabId(size_t ind, UINT32 vocabId) {
|
||||
m_factors[ind] = vocabId;
|
||||
}
|
||||
|
||||
Moses::Word *ConvertToMoses(Moses::FactorDirection direction
|
||||
, const std::vector<Moses::FactorType> &outputFactorsVec
|
||||
, const Vocab &vocab) const;
|
||||
|
||||
int Compare(const Word &compare) const;
|
||||
bool operator<(const Word &compare) const;
|
||||
bool operator==(const Word &compare) const;
|
||||
|
||||
};
|
||||
}
|
||||
|
1463
trunk/config.guess
vendored
Executable file
1463
trunk/config.guess
vendored
Executable file
File diff suppressed because it is too large
Load Diff
107
trunk/config.h.in
Normal file
107
trunk/config.h.in
Normal file
@ -0,0 +1,107 @@
|
||||
/* config.h.in. Generated from configure.in by autoheader. */
|
||||
|
||||
/* Defined if the requested minimum BOOST version is satisfied */
|
||||
#undef HAVE_BOOST
|
||||
|
||||
/* Define to 1 if you have <boost/thread.hpp> */
|
||||
#undef HAVE_BOOST_THREAD_HPP
|
||||
|
||||
/* Define to 1 if you have the <dlfcn.h> header file. */
|
||||
#undef HAVE_DLFCN_H
|
||||
|
||||
/* flag for DMapLM */
|
||||
#undef HAVE_DMAPLM
|
||||
|
||||
/* Define to 1 if you have the <getopt.h> header file. */
|
||||
#undef HAVE_GETOPT_H
|
||||
|
||||
/* Define to 1 if you have the <inttypes.h> header file. */
|
||||
#undef HAVE_INTTYPES_H
|
||||
|
||||
/* flag for IRSTLM */
|
||||
#undef HAVE_IRSTLM
|
||||
|
||||
/* flag for KENLM */
|
||||
#undef HAVE_KENLM
|
||||
|
||||
/* Define to 1 if you have the `oolm' library (-loolm). */
|
||||
#undef HAVE_LIBOOLM
|
||||
|
||||
/* Define to 1 if you have the `tcmalloc' library (-ltcmalloc). */
|
||||
#undef HAVE_LIBTCMALLOC
|
||||
|
||||
/* Define to 1 if you have the <memory.h> header file. */
|
||||
#undef HAVE_MEMORY_H
|
||||
|
||||
/* Define to 1 if you have the <nl-cpt.h> header file. */
|
||||
#undef HAVE_NL_CPT_H
|
||||
|
||||
/* flag for ORLM */
|
||||
#undef HAVE_ORLM
|
||||
|
||||
/* flag for protobuf */
|
||||
#undef HAVE_PROTOBUF
|
||||
|
||||
/* flag for RandLM */
|
||||
#undef HAVE_RANDLM
|
||||
|
||||
/* flag for SRILM */
|
||||
#undef HAVE_SRILM
|
||||
|
||||
/* Define to 1 if you have the <stdint.h> header file. */
|
||||
#undef HAVE_STDINT_H
|
||||
|
||||
/* Define to 1 if you have the <stdlib.h> header file. */
|
||||
#undef HAVE_STDLIB_H
|
||||
|
||||
/* Define to 1 if you have the <strings.h> header file. */
|
||||
#undef HAVE_STRINGS_H
|
||||
|
||||
/* Define to 1 if you have the <string.h> header file. */
|
||||
#undef HAVE_STRING_H
|
||||
|
||||
/* flag for Syntactic Parser */
|
||||
#undef HAVE_SYNLM
|
||||
|
||||
/* Define to 1 if you have the <sys/stat.h> header file. */
|
||||
#undef HAVE_SYS_STAT_H
|
||||
|
||||
/* Define to 1 if you have the <sys/types.h> header file. */
|
||||
#undef HAVE_SYS_TYPES_H
|
||||
|
||||
/* Define to 1 if you have the <unistd.h> header file. */
|
||||
#undef HAVE_UNISTD_H
|
||||
|
||||
/* Define to the sub-directory in which libtool stores uninstalled libraries.
|
||||
*/
|
||||
#undef LT_OBJDIR
|
||||
|
||||
/* Name of package */
|
||||
#undef PACKAGE
|
||||
|
||||
/* Define to the address where bug reports for this package should be sent. */
|
||||
#undef PACKAGE_BUGREPORT
|
||||
|
||||
/* Define to the full name of this package. */
|
||||
#undef PACKAGE_NAME
|
||||
|
||||
/* Define to the full name and version of this package. */
|
||||
#undef PACKAGE_STRING
|
||||
|
||||
/* Define to the one symbol short name of this package. */
|
||||
#undef PACKAGE_TARNAME
|
||||
|
||||
/* Define to the home page for this package. */
|
||||
#undef PACKAGE_URL
|
||||
|
||||
/* Define to the version of this package. */
|
||||
#undef PACKAGE_VERSION
|
||||
|
||||
/* Define to 1 if you have the ANSI C header files. */
|
||||
#undef STDC_HEADERS
|
||||
|
||||
/* Flag to enable use of Boost pool */
|
||||
#undef USE_BOOST_POOL
|
||||
|
||||
/* Version number of package */
|
||||
#undef VERSION
|
1579
trunk/config.sub
vendored
Executable file
1579
trunk/config.sub
vendored
Executable file
File diff suppressed because it is too large
Load Diff
360
trunk/configure.in
Normal file
360
trunk/configure.in
Normal file
@ -0,0 +1,360 @@
|
||||
AC_INIT(moses/src)
|
||||
|
||||
AM_CONFIG_HEADER(config.h)
|
||||
AM_INIT_AUTOMAKE(moses, 0.1)
|
||||
|
||||
AC_CONFIG_MACRO_DIR([m4])
|
||||
|
||||
AC_PROG_CXX
|
||||
AC_PROG_CXXCPP
|
||||
AC_LANG_CPLUSPLUS
|
||||
|
||||
AC_DISABLE_SHARED
|
||||
AC_PROG_LIBTOOL
|
||||
# Shared library are disabled for default
|
||||
#LT_INIT([disable-shared])
|
||||
|
||||
AX_XMLRPC_C
|
||||
|
||||
AC_ARG_WITH(protobuf,
|
||||
[AC_HELP_STRING([--with-protobuf=PATH], [(optional) path to Google protobuf])],
|
||||
[with_protobuf=$withval],
|
||||
[with_protobuf=no]
|
||||
)
|
||||
|
||||
AC_ARG_WITH(srilm,
|
||||
[AC_HELP_STRING([--with-srilm=PATH], [(optional) path to SRI's LM toolkit])],
|
||||
[with_srilm=$withval],
|
||||
[with_srilm=no]
|
||||
)
|
||||
|
||||
AC_ARG_WITH(srilm-dynamic,
|
||||
[AC_HELP_STRING([--with-srilm-dynamic], [(optional) link dynamically with srilm])],
|
||||
[with_srilm_dynamic=yes],
|
||||
[with_srilm_dynamic=no]
|
||||
)
|
||||
|
||||
AC_ARG_WITH(srilm-arch,
|
||||
[AC_HELP_STRING([--with-srilm-arch=ARCH], [(optional) architecture for which SRILM was built])],
|
||||
[with_srilm_arch=$withval],
|
||||
[with_srilm_arch=no]
|
||||
)
|
||||
|
||||
|
||||
AC_ARG_WITH(irstlm,
|
||||
[AC_HELP_STRING([--with-irstlm=PATH], [(optional) path to IRST's LM toolkit])],
|
||||
[with_irstlm=$withval],
|
||||
[with_irstlm=no]
|
||||
)
|
||||
|
||||
AC_ARG_WITH(kenlm,
|
||||
[AC_HELP_STRING([--with-kenlm], [(optional) Include Ken's LM toolkit; default is yes])],
|
||||
[with_kenlm=$withval],
|
||||
[with_kenlm=yes]
|
||||
)
|
||||
|
||||
AC_ARG_WITH(randlm,
|
||||
[AC_HELP_STRING([--with-randlm=PATH], [(optional) path to RandLM toolkit])],
|
||||
[with_randlm=$withval],
|
||||
[with_randlm=no]
|
||||
)
|
||||
AC_ARG_WITH(orlm,
|
||||
[AC_HELP_STRING([--with-orlm=PATH], [(optional) path to ORLM])],
|
||||
[with_orlm=$withval],
|
||||
[with_orlm=no]
|
||||
)
|
||||
AC_ARG_WITH(dmaplm,
|
||||
[AC_HELP_STRING([--with-dmaplm=PATH], [(optional) path to DMapLM])],
|
||||
[with_dmaplm=$withval],
|
||||
[with_dmaplm=no]
|
||||
)
|
||||
|
||||
AC_ARG_WITH(synlm,
|
||||
[AC_HELP_STRING([--with-synlm], [(optional) Include syntactic language model parser; default is no])],
|
||||
[with_synlm=$withval],
|
||||
[with_synlm=no]
|
||||
)
|
||||
|
||||
AC_ARG_WITH(notrace,
|
||||
[AC_HELP_STRING([--notrace], [disable trace])],
|
||||
[without_trace=yes],
|
||||
)
|
||||
|
||||
|
||||
|
||||
AC_ARG_ENABLE(profiling,
|
||||
[AC_HELP_STRING([--enable-profiling], [moses will dump profiling info])],
|
||||
[CPPFLAGS="$CPPFLAGS -pg"; LDFLAGS="$LDFLAGS -pg" ]
|
||||
)
|
||||
|
||||
AC_ARG_ENABLE(optimization,
|
||||
[AC_HELP_STRING([--enable-optimization], [compile with -O3 flag])],
|
||||
[CPPFLAGS="$CPPFLAGS -O3"; LDFLAGS="$LDFLAGS -O3" ]
|
||||
)
|
||||
|
||||
AC_ARG_ENABLE(threads,
|
||||
[AC_HELP_STRING([--enable-threads], [compile threadsafe library and multi-threaded moses (mosesmt)])],
|
||||
[],
|
||||
[enable_threads=no]
|
||||
)
|
||||
|
||||
AC_ARG_ENABLE(boost,
|
||||
[AC_HELP_STRING([--enable-boost], [use Boost library])],
|
||||
[],
|
||||
[enable_boost=no]
|
||||
)
|
||||
|
||||
AC_ARG_WITH(zlib,
|
||||
[AC_HELP_STRING([--with-zlib=PATH], [(optional) path to zlib])],
|
||||
[with_zlib=$withval],
|
||||
[with_zlib=no]
|
||||
)
|
||||
|
||||
AC_ARG_WITH(tcmalloc,
|
||||
[AC_HELP_STRING([--with-tcmalloc], [(optional) link with tcmalloc; default is no])],
|
||||
[with_tcmalloc=$withval],
|
||||
[with_tcmalloc=no]
|
||||
)
|
||||
|
||||
require_boost=no
|
||||
if test "x$enable_threads" != 'xno' || test "x$enable_boost" != 'xno'
|
||||
then
|
||||
require_boost=yes
|
||||
fi
|
||||
|
||||
AC_ARG_ENABLE(boost-pool,
|
||||
[AC_HELP_STRING([--enable-boost-pool], [(optional) try to improve speed by selectively using Boost pool allocation (may increase total memory use); default is yes if Boost enabled])],
|
||||
[],
|
||||
[enable_boost_pool=$require_boost]
|
||||
)
|
||||
|
||||
|
||||
AM_CONDITIONAL([INTERNAL_LM], false)
|
||||
AM_CONDITIONAL([SRI_LM], false)
|
||||
AM_CONDITIONAL([IRST_LM], false)
|
||||
AM_CONDITIONAL([KEN_LM], false)
|
||||
AM_CONDITIONAL([RAND_LM], false)
|
||||
AM_CONDITIONAL([ORLM_LM], false)
|
||||
AM_CONDITIONAL([DMAP_LM], false)
|
||||
AM_CONDITIONAL([SYN_LM], false)
|
||||
AM_CONDITIONAL([PROTOBUF], false)
|
||||
AM_CONDITIONAL([am__fastdepCC], false)
|
||||
AM_CONDITIONAL([WITH_THREADS],false)
|
||||
|
||||
|
||||
if test "x$without_trace" = 'xyes'
|
||||
then
|
||||
AC_MSG_NOTICE([trace disabled, most regression test will fail])
|
||||
else
|
||||
AC_MSG_NOTICE([trace enabled (default)])
|
||||
CPPFLAGS="$CPPFLAGS -DTRACE_ENABLE=1"
|
||||
fi
|
||||
|
||||
if test "x$require_boost" = 'xyes'
|
||||
then
|
||||
AC_MSG_NOTICE([Using Boost library])
|
||||
BOOST_REQUIRE([1.36.0])
|
||||
fi
|
||||
|
||||
if test "x$enable_threads" = 'xyes'
|
||||
then
|
||||
AC_MSG_NOTICE([Building threaded moses])
|
||||
BOOST_THREADS
|
||||
CPPFLAGS="$CPPFLAGS -DWITH_THREADS"
|
||||
AM_CONDITIONAL([WITH_THREADS],true)
|
||||
else
|
||||
AC_MSG_NOTICE([Building non-threaded moses. This will disable the moses server])
|
||||
fi
|
||||
|
||||
if test "x$with_protobuf" != 'xno'
|
||||
then
|
||||
SAVE_CPPFLAGS="$CPPFLAGS"
|
||||
CPPFLAGS="$CPPFLAGS -I${with_protobuf}/include"
|
||||
|
||||
AC_CHECK_HEADER(google/protobuf/message.h,
|
||||
[AC_DEFINE([HAVE_PROTOBUF], [], [flag for protobuf])],
|
||||
[AC_MSG_ERROR([Cannot find protobuf!])])
|
||||
|
||||
LIB_PROTOBUF="-lprotobuf"
|
||||
LDFLAGS="$LDFLAGS -L${with_protobuf}/lib"
|
||||
LIBS="$LIBS $LIB_PROTOBUF"
|
||||
AC_PATH_PROG(PROTOC,protoc,,"${PATH}:${with_protobuf}/bin")
|
||||
FMTLIBS="$FMTLIBS libprotobuf.a"
|
||||
AM_CONDITIONAL([PROTOBUF], true)
|
||||
fi
|
||||
|
||||
if test "x$with_srilm" != 'xno'
|
||||
then
|
||||
SAVE_CPPFLAGS="$CPPFLAGS"
|
||||
CPPFLAGS="$CPPFLAGS -I${with_srilm}/include"
|
||||
|
||||
AC_CHECK_HEADER(Ngram.h,
|
||||
[AC_DEFINE([HAVE_SRILM], [], [flag for SRILM])],
|
||||
[AC_MSG_ERROR([Cannot find SRILM!])])
|
||||
|
||||
if test "x$with_srilm_dynamic" != 'xyes'
|
||||
then
|
||||
LIB_SRILM="-loolm -ldstruct -lmisc -lflm"
|
||||
# ROOT/lib/i686-m64/liboolm.a
|
||||
# ROOT/lib/i686-m64/libdstruct.a
|
||||
# ROOT/lib/i686-m64/libmisc.a
|
||||
if test "x$with_srilm_arch" != 'xno'
|
||||
then
|
||||
MY_ARCH=${with_srilm_arch}
|
||||
else
|
||||
MY_ARCH=`${with_srilm}/sbin/machine-type`
|
||||
fi
|
||||
LDFLAGS="$LDFLAGS -L${with_srilm}/lib/${MY_ARCH} -L${with_srilm}/flm/obj/${MY_ARCH}"
|
||||
LIBS="$LIBS $LIB_SRILM"
|
||||
FMTLIBS="$FMTLIBS liboolm.a libdstruct.a libmisc.a"
|
||||
else
|
||||
LDFLAGS="$LDFLAGS -L${with_srilm}/lib"
|
||||
LIBS="$LIBS -lsrilm"
|
||||
fi
|
||||
AC_CHECK_LIB([oolm], [trigram_init], [], [AC_MSG_ERROR([Cannot find SRILM's library in ${with_srilm}/lib/${MY_ARCH} ])])
|
||||
AM_CONDITIONAL([SRI_LM], true)
|
||||
fi
|
||||
|
||||
if test "x$with_irstlm" != 'xno'
|
||||
then
|
||||
SAVE_CPPFLAGS="$CPPFLAGS"
|
||||
CPPFLAGS="$CPPFLAGS -I${with_irstlm}/include"
|
||||
|
||||
|
||||
AC_MSG_NOTICE([])
|
||||
AC_MSG_NOTICE([!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!])
|
||||
AC_MSG_NOTICE([!!! You are linking the IRSTLM library; be sure the release is >= 5.50.01 !!!])
|
||||
AC_MSG_NOTICE([!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!])
|
||||
AC_MSG_NOTICE([])
|
||||
|
||||
|
||||
AC_CHECK_HEADER(n_gram.h,
|
||||
[AC_DEFINE([HAVE_IRSTLM], [], [flag for IRSTLM])],
|
||||
[AC_MSG_ERROR([Cannot find IRST-LM in ${with_irstlm}])])
|
||||
|
||||
MY_ARCH=`uname -m`
|
||||
LIB_IRSTLM="-lirstlm"
|
||||
LDFLAGS="$LDFLAGS -L${with_irstlm}/lib"
|
||||
LIBS="$LIBS $LIB_IRSTLM"
|
||||
FMTLIBS="$FMTLIBS libirstlm.a"
|
||||
AM_CONDITIONAL([IRST_LM], true)
|
||||
fi
|
||||
|
||||
if test "x$with_kenlm" != 'xno'
|
||||
then
|
||||
SAVE_CPPFLAGS="$CPPFLAGS"
|
||||
CPPFLAGS="$CPPFLAGS -I${PWD}/kenlm"
|
||||
|
||||
AC_CHECK_HEADER(lm/model.hh,
|
||||
[AC_DEFINE([HAVE_KENLM], [], [flag for KENLM])],
|
||||
[AC_MSG_ERROR([Cannot find KEN-LM in ${PWD}/kenlm])])
|
||||
|
||||
KENLM_LDFLAGS="-L\$(top_srcdir)/kenlm -lkenlm -lz"
|
||||
KENLM_DEPS="\$(top_srcdir)/kenlm/libkenlm.la"
|
||||
FMTLIBS="$FMTLIBS libkenlm.la"
|
||||
AM_CONDITIONAL([KEN_LM], true)
|
||||
else
|
||||
KENLM_LDFLAGS=""
|
||||
KENLM_DEPS=""
|
||||
fi
|
||||
AC_SUBST(KENLM_LDFLAGS)
|
||||
AC_SUBST(KENLM_DEPS)
|
||||
|
||||
if test "x$with_randlm" != 'xno'
|
||||
then
|
||||
SAVE_CPPFLAGS="$CPPFLAGS"
|
||||
CPPFLAGS="$CPPFLAGS -I${with_randlm}/include"
|
||||
|
||||
AC_CHECK_HEADER(RandLM.h,
|
||||
[AC_DEFINE([HAVE_RANDLM], [], [flag for RandLM])],
|
||||
[AC_MSG_ERROR([Cannot find RandLM!])])
|
||||
|
||||
|
||||
MY_ARCH=`uname -m`
|
||||
LIB_RANDLM="-lrandlm"
|
||||
LDFLAGS="$LDFLAGS -L${with_randlm}/lib"
|
||||
LIBS="$LIBS $LIB_RANDLM"
|
||||
FMTLIBS="$FMTLIBS librandlm.a"
|
||||
AM_CONDITIONAL([RAND_LM], true)
|
||||
fi
|
||||
|
||||
if test "x$with_dmaplm" != 'xno'
|
||||
then
|
||||
SAVE_CPPFLAGS="$CPPFLAGS"
|
||||
CPPFLAGS="$CPPFLAGS -I${with_dmaplm}/src/DMap"
|
||||
|
||||
AC_CHECK_HEADER(StructLanguageModel.h,
|
||||
[AC_DEFINE([HAVE_DMAPLM], [], [flag for DMapLM])],
|
||||
[AC_MSG_ERROR([Cannot find DMapLM!])])
|
||||
|
||||
LDFLAGS="$LDFLAGS -L${with_dmaplm}/src/DMap"
|
||||
LIBS="$LIBS -lDMap"
|
||||
FMTLIBS="FMTLIBS libdmap.la"
|
||||
AM_CONDITIONAL([DMAP_LM], true)
|
||||
fi
|
||||
|
||||
if test "x$with_orlm" != 'xno'
|
||||
then
|
||||
SAVE_CPPFLAGS="$CPPFLAGS"
|
||||
CPPFLAGS="$CPPFLAGS -I${with_orlm}/"
|
||||
|
||||
AC_CHECK_HEADER(onlineRLM.h,
|
||||
#AC_CHECK_HEADER(multiOnlineRLM.h,
|
||||
[AC_DEFINE([HAVE_ORLM], [], [flag for ORLM])],
|
||||
[AC_MSG_ERROR([Cannot find ORLM!])])
|
||||
|
||||
MY_ARCH=`uname -m`
|
||||
AM_CONDITIONAL([ORLM_LM], true)
|
||||
fi
|
||||
if test "x$with_tcmalloc" != 'xno'
|
||||
then
|
||||
AC_CHECK_LIB([tcmalloc], [malloc], [], [AC_MSG_ERROR([Cannot find tcmalloc])])
|
||||
fi
|
||||
|
||||
|
||||
if test "x$enable_boost_pool" != 'xno'
|
||||
then
|
||||
AC_CHECK_HEADER(boost/pool/object_pool.hpp,
|
||||
[AC_DEFINE([USE_BOOST_POOL], [], [Flag to enable use of Boost pool])],
|
||||
[AC_MSG_WARN([Cannot find boost/pool/object_pool.hpp])]
|
||||
)
|
||||
fi
|
||||
|
||||
if test "x$with_synlm" != 'xno'
|
||||
then
|
||||
SAVE_CPPFLAGS="$CPPFLAGS"
|
||||
CPPFLAGS="$CPPFLAGS -I${PWD}/synlm/hhmm/rvtl/include -I${PWD}/synlm/hhmm/wsjparse/include -lm"
|
||||
|
||||
AC_CHECK_HEADERS(nl-cpt.h,
|
||||
[AC_DEFINE([HAVE_SYNLM], [], [flag for Syntactic Parser])],
|
||||
[AC_MSG_ERROR([Cannot find SYNLM in ${PWD}/synlm/hhmm])])
|
||||
|
||||
AM_CONDITIONAL([SYN_LM], true)
|
||||
|
||||
fi
|
||||
|
||||
|
||||
AM_CONDITIONAL([WITH_MERT],false)
|
||||
AC_CHECK_HEADERS([getopt.h],
|
||||
[AM_CONDITIONAL([WITH_MERT],true)],
|
||||
[AC_MSG_WARN([Cannot find getopt.h - disabling new mert])])
|
||||
|
||||
AM_CONDITIONAL([WITH_SERVER],false)
|
||||
if test "x$have_xmlrpc_c" = "xyes" && test "x$enable_threads" = "xyes"; then
|
||||
AM_CONDITIONAL([WITH_SERVER],true)
|
||||
else
|
||||
AC_MSG_NOTICE([Disabling server])
|
||||
fi
|
||||
|
||||
if test "x$with_zlib" != 'xno'
|
||||
then
|
||||
CPPFLAGS="$CPPFLAGS -I${with_zlib}/include"
|
||||
LDFLAGS="$LDFLAGS -L${with_zlib}/lib"
|
||||
fi
|
||||
|
||||
LIBS="$LIBS -lz"
|
||||
|
||||
|
||||
AC_CONFIG_FILES(Makefile OnDiskPt/src/Makefile moses/src/Makefile moses-cmd/src/Makefile moses-chart-cmd/src/Makefile misc/Makefile mert/Makefile server/Makefile CreateOnDisk/src/Makefile kenlm/Makefile)
|
||||
|
||||
AC_OUTPUT()
|
441
trunk/depcomp
Executable file
441
trunk/depcomp
Executable file
@ -0,0 +1,441 @@
|
||||
#! /bin/sh
|
||||
|
||||
# depcomp - compile a program generating dependencies as side-effects
|
||||
# Copyright 1999, 2000 Free Software Foundation, Inc.
|
||||
|
||||
# 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 2, 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, write to the Free Software
|
||||
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
|
||||
# 02111-1307, USA.
|
||||
|
||||
# As a special exception to the GNU General Public License, if you
|
||||
# distribute this file as part of a program that contains a
|
||||
# configuration script generated by Autoconf, you may include it under
|
||||
# the same distribution terms that you use for the rest of that program.
|
||||
|
||||
# Originally written by Alexandre Oliva <oliva@dcc.unicamp.br>.
|
||||
|
||||
if test -z "$depmode" || test -z "$source" || test -z "$object"; then
|
||||
echo "depcomp: Variables source, object and depmode must be set" 1>&2
|
||||
exit 1
|
||||
fi
|
||||
# `libtool' can also be set to `yes' or `no'.
|
||||
|
||||
depfile=${depfile-`echo "$object" | sed 's,\([^/]*\)$,.deps/\1,;s/\.\([^.]*\)$/.P\1/'`}
|
||||
tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`}
|
||||
|
||||
rm -f "$tmpdepfile"
|
||||
|
||||
# Some modes work just like other modes, but use different flags. We
|
||||
# parameterize here, but still list the modes in the big case below,
|
||||
# to make depend.m4 easier to write. Note that we *cannot* use a case
|
||||
# here, because this file can only contain one case statement.
|
||||
if test "$depmode" = hp; then
|
||||
# HP compiler uses -M and no extra arg.
|
||||
gccflag=-M
|
||||
depmode=gcc
|
||||
fi
|
||||
|
||||
if test "$depmode" = dashXmstdout; then
|
||||
# This is just like dashmstdout with a different argument.
|
||||
dashmflag=-xM
|
||||
depmode=dashmstdout
|
||||
fi
|
||||
|
||||
case "$depmode" in
|
||||
gcc3)
|
||||
## gcc 3 implements dependency tracking that does exactly what
|
||||
## we want. Yay! Note: for some reason libtool 1.4 doesn't like
|
||||
## it if -MD -MP comes after the -MF stuff. Hmm.
|
||||
"$@" -MT "$object" -MD -MP -MF "$tmpdepfile"
|
||||
stat=$?
|
||||
if test $stat -eq 0; then :
|
||||
else
|
||||
rm -f "$tmpdepfile"
|
||||
exit $stat
|
||||
fi
|
||||
mv "$tmpdepfile" "$depfile"
|
||||
;;
|
||||
|
||||
gcc)
|
||||
## There are various ways to get dependency output from gcc. Here's
|
||||
## why we pick this rather obscure method:
|
||||
## - Don't want to use -MD because we'd like the dependencies to end
|
||||
## up in a subdir. Having to rename by hand is ugly.
|
||||
## (We might end up doing this anyway to support other compilers.)
|
||||
## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like
|
||||
## -MM, not -M (despite what the docs say).
|
||||
## - Using -M directly means running the compiler twice (even worse
|
||||
## than renaming).
|
||||
if test -z "$gccflag"; then
|
||||
gccflag=-MD,
|
||||
fi
|
||||
"$@" -Wp,"$gccflag$tmpdepfile"
|
||||
stat=$?
|
||||
if test $stat -eq 0; then :
|
||||
else
|
||||
rm -f "$tmpdepfile"
|
||||
exit $stat
|
||||
fi
|
||||
rm -f "$depfile"
|
||||
echo "$object : \\" > "$depfile"
|
||||
alpha=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
|
||||
## The second -e expression handles DOS-style file names with drive letters.
|
||||
sed -e 's/^[^:]*: / /' \
|
||||
-e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile"
|
||||
## This next piece of magic avoids the `deleted header file' problem.
|
||||
## The problem is that when a header file which appears in a .P file
|
||||
## is deleted, the dependency causes make to die (because there is
|
||||
## typically no way to rebuild the header). We avoid this by adding
|
||||
## dummy dependencies for each header file. Too bad gcc doesn't do
|
||||
## this for us directly.
|
||||
tr ' ' '
|
||||
' < "$tmpdepfile" |
|
||||
## Some versions of gcc put a space before the `:'. On the theory
|
||||
## that the space means something, we add a space to the output as
|
||||
## well.
|
||||
## Some versions of the HPUX 10.20 sed can't process this invocation
|
||||
## correctly. Breaking it into two sed invocations is a workaround.
|
||||
sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
|
||||
rm -f "$tmpdepfile"
|
||||
;;
|
||||
|
||||
hp)
|
||||
# This case exists only to let depend.m4 do its work. It works by
|
||||
# looking at the text of this script. This case will never be run,
|
||||
# since it is checked for above.
|
||||
exit 1
|
||||
;;
|
||||
|
||||
sgi)
|
||||
if test "$libtool" = yes; then
|
||||
"$@" "-Wp,-MDupdate,$tmpdepfile"
|
||||
else
|
||||
"$@" -MDupdate "$tmpdepfile"
|
||||
fi
|
||||
stat=$?
|
||||
if test $stat -eq 0; then :
|
||||
else
|
||||
rm -f "$tmpdepfile"
|
||||
exit $stat
|
||||
fi
|
||||
rm -f "$depfile"
|
||||
|
||||
if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files
|
||||
echo "$object : \\" > "$depfile"
|
||||
|
||||
# Clip off the initial element (the dependent). Don't try to be
|
||||
# clever and replace this with sed code, as IRIX sed won't handle
|
||||
# lines with more than a fixed number of characters (4096 in
|
||||
# IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines;
|
||||
# the IRIX cc adds comments like `#:fec' to the end of the
|
||||
# dependency line.
|
||||
tr ' ' '
|
||||
' < "$tmpdepfile" \
|
||||
| sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' | \
|
||||
tr '
|
||||
' ' ' >> $depfile
|
||||
echo >> $depfile
|
||||
|
||||
# The second pass generates a dummy entry for each header file.
|
||||
tr ' ' '
|
||||
' < "$tmpdepfile" \
|
||||
| sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \
|
||||
>> $depfile
|
||||
else
|
||||
# The sourcefile does not contain any dependencies, so just
|
||||
# store a dummy comment line, to avoid errors with the Makefile
|
||||
# "include basename.Plo" scheme.
|
||||
echo "#dummy" > "$depfile"
|
||||
fi
|
||||
rm -f "$tmpdepfile"
|
||||
;;
|
||||
|
||||
aix)
|
||||
# The C for AIX Compiler uses -M and outputs the dependencies
|
||||
# in a .u file. This file always lives in the current directory.
|
||||
# Also, the AIX compiler puts `$object:' at the start of each line;
|
||||
# $object doesn't have directory information.
|
||||
stripped=`echo "$object" | sed -e 's,^.*/,,' -e 's/\(.*\)\..*$/\1/'`
|
||||
tmpdepfile="$stripped.u"
|
||||
outname="$stripped.o"
|
||||
if test "$libtool" = yes; then
|
||||
"$@" -Wc,-M
|
||||
else
|
||||
"$@" -M
|
||||
fi
|
||||
|
||||
stat=$?
|
||||
if test $stat -eq 0; then :
|
||||
else
|
||||
rm -f "$tmpdepfile"
|
||||
exit $stat
|
||||
fi
|
||||
|
||||
if test -f "$tmpdepfile"; then
|
||||
# Each line is of the form `foo.o: dependent.h'.
|
||||
# Do two passes, one to just change these to
|
||||
# `$object: dependent.h' and one to simply `dependent.h:'.
|
||||
sed -e "s,^$outname:,$object :," < "$tmpdepfile" > "$depfile"
|
||||
sed -e "s,^$outname: \(.*\)$,\1:," < "$tmpdepfile" >> "$depfile"
|
||||
else
|
||||
# The sourcefile does not contain any dependencies, so just
|
||||
# store a dummy comment line, to avoid errors with the Makefile
|
||||
# "include basename.Plo" scheme.
|
||||
echo "#dummy" > "$depfile"
|
||||
fi
|
||||
rm -f "$tmpdepfile"
|
||||
;;
|
||||
|
||||
icc)
|
||||
# Must come before tru64.
|
||||
|
||||
# Intel's C compiler understands `-MD -MF file'. However
|
||||
# icc -MD -MF foo.d -c -o sub/foo.o sub/foo.c
|
||||
# will fill foo.d with something like
|
||||
# foo.o: sub/foo.c
|
||||
# foo.o: sub/foo.h
|
||||
# which is wrong. We want:
|
||||
# sub/foo.o: sub/foo.c
|
||||
# sub/foo.o: sub/foo.h
|
||||
# sub/foo.c:
|
||||
# sub/foo.h:
|
||||
|
||||
"$@" -MD -MF "$tmpdepfile"
|
||||
stat=$?
|
||||
if test $stat -eq 0; then :
|
||||
else
|
||||
rm -f "$tmpdepfile"
|
||||
exit $stat
|
||||
fi
|
||||
rm -f "$depfile"
|
||||
# Each line is of the form `foo.o: dependent.h'.
|
||||
# Do two passes, one to just change these to
|
||||
# `$object: dependent.h' and one to simply `dependent.h:'.
|
||||
sed -e "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile"
|
||||
sed -e "s,^[^:]*: \(.*\)$,\1:," < "$tmpdepfile" >> "$depfile"
|
||||
rm -f "$tmpdepfile"
|
||||
;;
|
||||
|
||||
tru64)
|
||||
# The Tru64 AIX compiler uses -MD to generate dependencies as a side
|
||||
# effect. `cc -MD -o foo.o ...' puts the dependencies into `foo.o.d'.
|
||||
# At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put
|
||||
# dependencies in `foo.d' instead, so we check for that too.
|
||||
# Subdirectories are respected.
|
||||
|
||||
tmpdepfile1="$object.d"
|
||||
tmpdepfile2=`echo "$object" | sed -e 's/.o$/.d/'`
|
||||
if test "$libtool" = yes; then
|
||||
"$@" -Wc,-MD
|
||||
else
|
||||
"$@" -MD
|
||||
fi
|
||||
|
||||
stat=$?
|
||||
if test $stat -eq 0; then :
|
||||
else
|
||||
rm -f "$tmpdepfile1" "$tmpdepfile2"
|
||||
exit $stat
|
||||
fi
|
||||
|
||||
if test -f "$tmpdepfile1"; then
|
||||
tmpdepfile="$tmpdepfile1"
|
||||
else
|
||||
tmpdepfile="$tmpdepfile2"
|
||||
fi
|
||||
if test -f "$tmpdepfile"; then
|
||||
sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile"
|
||||
# That's a space and a tab in the [].
|
||||
sed -e 's,^.*\.[a-z]*:[ ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile"
|
||||
else
|
||||
echo "#dummy" > "$depfile"
|
||||
fi
|
||||
rm -f "$tmpdepfile"
|
||||
;;
|
||||
|
||||
#nosideeffect)
|
||||
# This comment above is used by automake to tell side-effect
|
||||
# dependency tracking mechanisms from slower ones.
|
||||
|
||||
dashmstdout)
|
||||
# Important note: in order to support this mode, a compiler *must*
|
||||
# always write the proprocessed file to stdout, regardless of -o,
|
||||
# because we must use -o when running libtool.
|
||||
test -z "$dashmflag" && dashmflag=-M
|
||||
( IFS=" "
|
||||
case " $* " in
|
||||
*" --mode=compile "*) # this is libtool, let us make it quiet
|
||||
for arg
|
||||
do # cycle over the arguments
|
||||
case "$arg" in
|
||||
"--mode=compile")
|
||||
# insert --quiet before "--mode=compile"
|
||||
set fnord "$@" --quiet
|
||||
shift # fnord
|
||||
;;
|
||||
esac
|
||||
set fnord "$@" "$arg"
|
||||
shift # fnord
|
||||
shift # "$arg"
|
||||
done
|
||||
;;
|
||||
esac
|
||||
"$@" $dashmflag | sed 's:^[^:]*\:[ ]*:'"$object"'\: :' > "$tmpdepfile"
|
||||
) &
|
||||
proc=$!
|
||||
"$@"
|
||||
stat=$?
|
||||
wait "$proc"
|
||||
if test "$stat" != 0; then exit $stat; fi
|
||||
rm -f "$depfile"
|
||||
cat < "$tmpdepfile" > "$depfile"
|
||||
tr ' ' '
|
||||
' < "$tmpdepfile" | \
|
||||
## Some versions of the HPUX 10.20 sed can't process this invocation
|
||||
## correctly. Breaking it into two sed invocations is a workaround.
|
||||
sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
|
||||
rm -f "$tmpdepfile"
|
||||
;;
|
||||
|
||||
dashXmstdout)
|
||||
# This case only exists to satisfy depend.m4. It is never actually
|
||||
# run, as this mode is specially recognized in the preamble.
|
||||
exit 1
|
||||
;;
|
||||
|
||||
makedepend)
|
||||
# X makedepend
|
||||
(
|
||||
shift
|
||||
cleared=no
|
||||
for arg in "$@"; do
|
||||
case $cleared in no)
|
||||
set ""; shift
|
||||
cleared=yes
|
||||
esac
|
||||
case "$arg" in
|
||||
-D*|-I*)
|
||||
set fnord "$@" "$arg"; shift;;
|
||||
-*)
|
||||
;;
|
||||
*)
|
||||
set fnord "$@" "$arg"; shift;;
|
||||
esac
|
||||
done
|
||||
obj_suffix="`echo $object | sed 's/^.*\././'`"
|
||||
touch "$tmpdepfile"
|
||||
${MAKEDEPEND-makedepend} 2>/dev/null -o"$obj_suffix" -f"$tmpdepfile" "$@"
|
||||
) &
|
||||
proc=$!
|
||||
"$@"
|
||||
stat=$?
|
||||
wait "$proc"
|
||||
if test "$stat" != 0; then exit $stat; fi
|
||||
rm -f "$depfile"
|
||||
cat < "$tmpdepfile" > "$depfile"
|
||||
tail +3 "$tmpdepfile" | tr ' ' '
|
||||
' | \
|
||||
## Some versions of the HPUX 10.20 sed can't process this invocation
|
||||
## correctly. Breaking it into two sed invocations is a workaround.
|
||||
sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
|
||||
rm -f "$tmpdepfile" "$tmpdepfile".bak
|
||||
;;
|
||||
|
||||
cpp)
|
||||
# Important note: in order to support this mode, a compiler *must*
|
||||
# always write the proprocessed file to stdout, regardless of -o,
|
||||
# because we must use -o when running libtool.
|
||||
( IFS=" "
|
||||
case " $* " in
|
||||
*" --mode=compile "*)
|
||||
for arg
|
||||
do # cycle over the arguments
|
||||
case $arg in
|
||||
"--mode=compile")
|
||||
# insert --quiet before "--mode=compile"
|
||||
set fnord "$@" --quiet
|
||||
shift # fnord
|
||||
;;
|
||||
esac
|
||||
set fnord "$@" "$arg"
|
||||
shift # fnord
|
||||
shift # "$arg"
|
||||
done
|
||||
;;
|
||||
esac
|
||||
"$@" -E |
|
||||
sed -n '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' |
|
||||
sed '$ s: \\$::' > "$tmpdepfile"
|
||||
) &
|
||||
proc=$!
|
||||
"$@"
|
||||
stat=$?
|
||||
wait "$proc"
|
||||
if test "$stat" != 0; then exit $stat; fi
|
||||
rm -f "$depfile"
|
||||
echo "$object : \\" > "$depfile"
|
||||
cat < "$tmpdepfile" >> "$depfile"
|
||||
sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile"
|
||||
rm -f "$tmpdepfile"
|
||||
;;
|
||||
|
||||
msvisualcpp)
|
||||
# Important note: in order to support this mode, a compiler *must*
|
||||
# always write the proprocessed file to stdout, regardless of -o,
|
||||
# because we must use -o when running libtool.
|
||||
( IFS=" "
|
||||
case " $* " in
|
||||
*" --mode=compile "*)
|
||||
for arg
|
||||
do # cycle over the arguments
|
||||
case $arg in
|
||||
"--mode=compile")
|
||||
# insert --quiet before "--mode=compile"
|
||||
set fnord "$@" --quiet
|
||||
shift # fnord
|
||||
;;
|
||||
esac
|
||||
set fnord "$@" "$arg"
|
||||
shift # fnord
|
||||
shift # "$arg"
|
||||
done
|
||||
;;
|
||||
esac
|
||||
"$@" -E |
|
||||
sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::echo "`cygpath -u \\"\1\\"`":p' | sort | uniq > "$tmpdepfile"
|
||||
) &
|
||||
proc=$!
|
||||
"$@"
|
||||
stat=$?
|
||||
wait "$proc"
|
||||
if test "$stat" != 0; then exit $stat; fi
|
||||
rm -f "$depfile"
|
||||
echo "$object : \\" > "$depfile"
|
||||
. "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s:: \1 \\:p' >> "$depfile"
|
||||
echo " " >> "$depfile"
|
||||
. "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s::\1\::p' >> "$depfile"
|
||||
rm -f "$tmpdepfile"
|
||||
;;
|
||||
|
||||
none)
|
||||
exec "$@"
|
||||
;;
|
||||
|
||||
*)
|
||||
echo "Unknown depmode $depmode" 1>&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
exit 0
|
276
trunk/install-sh
Executable file
276
trunk/install-sh
Executable file
@ -0,0 +1,276 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# install - install a program, script, or datafile
|
||||
# This comes from X11R5 (mit/util/scripts/install.sh).
|
||||
#
|
||||
# Copyright 1991 by the Massachusetts Institute of Technology
|
||||
#
|
||||
# Permission to use, copy, modify, distribute, and sell this software and its
|
||||
# documentation for any purpose is hereby granted without fee, provided that
|
||||
# the above copyright notice appear in all copies and that both that
|
||||
# copyright notice and this permission notice appear in supporting
|
||||
# documentation, and that the name of M.I.T. not be used in advertising or
|
||||
# publicity pertaining to distribution of the software without specific,
|
||||
# written prior permission. M.I.T. makes no representations about the
|
||||
# suitability of this software for any purpose. It is provided "as is"
|
||||
# without express or implied warranty.
|
||||
#
|
||||
# Calling this script install-sh is preferred over install.sh, to prevent
|
||||
# `make' implicit rules from creating a file called install from it
|
||||
# when there is no Makefile.
|
||||
#
|
||||
# This script is compatible with the BSD install script, but was written
|
||||
# from scratch. It can only install one file at a time, a restriction
|
||||
# shared with many OS's install programs.
|
||||
|
||||
|
||||
# set DOITPROG to echo to test this script
|
||||
|
||||
# Don't use :- since 4.3BSD and earlier shells don't like it.
|
||||
doit="${DOITPROG-}"
|
||||
|
||||
|
||||
# put in absolute paths if you don't have them in your path; or use env. vars.
|
||||
|
||||
mvprog="${MVPROG-mv}"
|
||||
cpprog="${CPPROG-cp}"
|
||||
chmodprog="${CHMODPROG-chmod}"
|
||||
chownprog="${CHOWNPROG-chown}"
|
||||
chgrpprog="${CHGRPPROG-chgrp}"
|
||||
stripprog="${STRIPPROG-strip}"
|
||||
rmprog="${RMPROG-rm}"
|
||||
mkdirprog="${MKDIRPROG-mkdir}"
|
||||
|
||||
transformbasename=""
|
||||
transform_arg=""
|
||||
instcmd="$mvprog"
|
||||
chmodcmd="$chmodprog 0755"
|
||||
chowncmd=""
|
||||
chgrpcmd=""
|
||||
stripcmd=""
|
||||
rmcmd="$rmprog -f"
|
||||
mvcmd="$mvprog"
|
||||
src=""
|
||||
dst=""
|
||||
dir_arg=""
|
||||
|
||||
while [ x"$1" != x ]; do
|
||||
case $1 in
|
||||
-c) instcmd=$cpprog
|
||||
shift
|
||||
continue;;
|
||||
|
||||
-d) dir_arg=true
|
||||
shift
|
||||
continue;;
|
||||
|
||||
-m) chmodcmd="$chmodprog $2"
|
||||
shift
|
||||
shift
|
||||
continue;;
|
||||
|
||||
-o) chowncmd="$chownprog $2"
|
||||
shift
|
||||
shift
|
||||
continue;;
|
||||
|
||||
-g) chgrpcmd="$chgrpprog $2"
|
||||
shift
|
||||
shift
|
||||
continue;;
|
||||
|
||||
-s) stripcmd=$stripprog
|
||||
shift
|
||||
continue;;
|
||||
|
||||
-t=*) transformarg=`echo $1 | sed 's/-t=//'`
|
||||
shift
|
||||
continue;;
|
||||
|
||||
-b=*) transformbasename=`echo $1 | sed 's/-b=//'`
|
||||
shift
|
||||
continue;;
|
||||
|
||||
*) if [ x"$src" = x ]
|
||||
then
|
||||
src=$1
|
||||
else
|
||||
# this colon is to work around a 386BSD /bin/sh bug
|
||||
:
|
||||
dst=$1
|
||||
fi
|
||||
shift
|
||||
continue;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [ x"$src" = x ]
|
||||
then
|
||||
echo "$0: no input file specified" >&2
|
||||
exit 1
|
||||
else
|
||||
:
|
||||
fi
|
||||
|
||||
if [ x"$dir_arg" != x ]; then
|
||||
dst=$src
|
||||
src=""
|
||||
|
||||
if [ -d "$dst" ]; then
|
||||
instcmd=:
|
||||
chmodcmd=""
|
||||
else
|
||||
instcmd=$mkdirprog
|
||||
fi
|
||||
else
|
||||
|
||||
# Waiting for this to be detected by the "$instcmd $src $dsttmp" command
|
||||
# might cause directories to be created, which would be especially bad
|
||||
# if $src (and thus $dsttmp) contains '*'.
|
||||
|
||||
if [ -f "$src" ] || [ -d "$src" ]
|
||||
then
|
||||
:
|
||||
else
|
||||
echo "$0: $src does not exist" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ x"$dst" = x ]
|
||||
then
|
||||
echo "$0: no destination specified" >&2
|
||||
exit 1
|
||||
else
|
||||
:
|
||||
fi
|
||||
|
||||
# If destination is a directory, append the input filename; if your system
|
||||
# does not like double slashes in filenames, you may need to add some logic
|
||||
|
||||
if [ -d "$dst" ]
|
||||
then
|
||||
dst=$dst/`basename "$src"`
|
||||
else
|
||||
:
|
||||
fi
|
||||
fi
|
||||
|
||||
## this sed command emulates the dirname command
|
||||
dstdir=`echo "$dst" | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'`
|
||||
|
||||
# Make sure that the destination directory exists.
|
||||
# this part is taken from Noah Friedman's mkinstalldirs script
|
||||
|
||||
# Skip lots of stat calls in the usual case.
|
||||
if [ ! -d "$dstdir" ]; then
|
||||
defaultIFS='
|
||||
'
|
||||
IFS="${IFS-$defaultIFS}"
|
||||
|
||||
oIFS=$IFS
|
||||
# Some sh's can't handle IFS=/ for some reason.
|
||||
IFS='%'
|
||||
set - `echo "$dstdir" | sed -e 's@/@%@g' -e 's@^%@/@'`
|
||||
IFS=$oIFS
|
||||
|
||||
pathcomp=''
|
||||
|
||||
while [ $# -ne 0 ] ; do
|
||||
pathcomp=$pathcomp$1
|
||||
shift
|
||||
|
||||
if [ ! -d "$pathcomp" ] ;
|
||||
then
|
||||
$mkdirprog "$pathcomp"
|
||||
else
|
||||
:
|
||||
fi
|
||||
|
||||
pathcomp=$pathcomp/
|
||||
done
|
||||
fi
|
||||
|
||||
if [ x"$dir_arg" != x ]
|
||||
then
|
||||
$doit $instcmd "$dst" &&
|
||||
|
||||
if [ x"$chowncmd" != x ]; then $doit $chowncmd "$dst"; else : ; fi &&
|
||||
if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd "$dst"; else : ; fi &&
|
||||
if [ x"$stripcmd" != x ]; then $doit $stripcmd "$dst"; else : ; fi &&
|
||||
if [ x"$chmodcmd" != x ]; then $doit $chmodcmd "$dst"; else : ; fi
|
||||
else
|
||||
|
||||
# If we're going to rename the final executable, determine the name now.
|
||||
|
||||
if [ x"$transformarg" = x ]
|
||||
then
|
||||
dstfile=`basename "$dst"`
|
||||
else
|
||||
dstfile=`basename "$dst" $transformbasename |
|
||||
sed $transformarg`$transformbasename
|
||||
fi
|
||||
|
||||
# don't allow the sed command to completely eliminate the filename
|
||||
|
||||
if [ x"$dstfile" = x ]
|
||||
then
|
||||
dstfile=`basename "$dst"`
|
||||
else
|
||||
:
|
||||
fi
|
||||
|
||||
# Make a couple of temp file names in the proper directory.
|
||||
|
||||
dsttmp=$dstdir/#inst.$$#
|
||||
rmtmp=$dstdir/#rm.$$#
|
||||
|
||||
# Trap to clean up temp files at exit.
|
||||
|
||||
trap 'status=$?; rm -f "$dsttmp" "$rmtmp" && exit $status' 0
|
||||
trap '(exit $?); exit' 1 2 13 15
|
||||
|
||||
# Move or copy the file name to the temp name
|
||||
|
||||
$doit $instcmd "$src" "$dsttmp" &&
|
||||
|
||||
# and set any options; do chmod last to preserve setuid bits
|
||||
|
||||
# If any of these fail, we abort the whole thing. If we want to
|
||||
# ignore errors from any of these, just make sure not to ignore
|
||||
# errors from the above "$doit $instcmd $src $dsttmp" command.
|
||||
|
||||
if [ x"$chowncmd" != x ]; then $doit $chowncmd "$dsttmp"; else :;fi &&
|
||||
if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd "$dsttmp"; else :;fi &&
|
||||
if [ x"$stripcmd" != x ]; then $doit $stripcmd "$dsttmp"; else :;fi &&
|
||||
if [ x"$chmodcmd" != x ]; then $doit $chmodcmd "$dsttmp"; else :;fi &&
|
||||
|
||||
# Now remove or move aside any old file at destination location. We try this
|
||||
# two ways since rm can't unlink itself on some systems and the destination
|
||||
# file might be busy for other reasons. In this case, the final cleanup
|
||||
# might fail but the new file should still install successfully.
|
||||
|
||||
{
|
||||
if [ -f "$dstdir/$dstfile" ]
|
||||
then
|
||||
$doit $rmcmd -f "$dstdir/$dstfile" 2>/dev/null ||
|
||||
$doit $mvcmd -f "$dstdir/$dstfile" "$rmtmp" 2>/dev/null ||
|
||||
{
|
||||
echo "$0: cannot unlink or rename $dstdir/$dstfile" >&2
|
||||
(exit 1); exit
|
||||
}
|
||||
else
|
||||
:
|
||||
fi
|
||||
} &&
|
||||
|
||||
# Now rename the file to the real destination.
|
||||
|
||||
$doit $mvcmd "$dsttmp" "$dstdir/$dstfile"
|
||||
|
||||
fi &&
|
||||
|
||||
# The final little trick to "correctly" pass the exit status to the exit trap.
|
||||
|
||||
{
|
||||
(exit 0); exit
|
||||
}
|
674
trunk/kenlm/COPYING
Normal file
674
trunk/kenlm/COPYING
Normal 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>.
|
165
trunk/kenlm/COPYING.LESSER
Normal file
165
trunk/kenlm/COPYING.LESSER
Normal 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.
|
19
trunk/kenlm/LICENSE
Normal file
19
trunk/kenlm/LICENSE
Normal file
@ -0,0 +1,19 @@
|
||||
Most of the code here is licensed under the LGPL. There are exceptions which have their own licenses, listed below. See comments in those files for more details.
|
||||
|
||||
util/murmur_hash.cc is under the MIT license.
|
||||
util/string_piece.hh and util/string_piece.cc are Google code and contains its own license.
|
||||
|
||||
For the rest:
|
||||
|
||||
Avenue code 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 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
Avenue code 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 Avenue code. If not, see <http://www.gnu.org/licenses/>.
|
31
trunk/kenlm/Makefile.am
Normal file
31
trunk/kenlm/Makefile.am
Normal file
@ -0,0 +1,31 @@
|
||||
lib_LTLIBRARIES = libkenlm.la
|
||||
bin_PROGRAMS = query build_binary
|
||||
|
||||
AM_CPPFLAGS = -W -Wall -ffor-scope -D_FILE_OFFSET_BITS=64 -D_LARGE_FILES $(BOOST_CPPFLAGS)
|
||||
libkenlm_la_SOURCES = \
|
||||
lm/bhiksha.cc \
|
||||
lm/binary_format.cc \
|
||||
lm/config.cc \
|
||||
lm/lm_exception.cc \
|
||||
lm/model.cc \
|
||||
lm/search_hashed.cc \
|
||||
lm/search_trie.cc \
|
||||
lm/quantize.cc \
|
||||
lm/read_arpa.cc \
|
||||
lm/trie.cc \
|
||||
lm/virtual_interface.cc \
|
||||
lm/vocab.cc \
|
||||
util/scoped.cc \
|
||||
util/murmur_hash.cc \
|
||||
util/mmap.cc \
|
||||
util/file_piece.cc \
|
||||
util/ersatz_progress.cc \
|
||||
util/exception.cc \
|
||||
util/bit_packing.cc
|
||||
|
||||
query_SOURCES = lm/ngram_query.cc
|
||||
query_LDADD = libkenlm.la
|
||||
|
||||
build_binary_SOURCES = lm/build_binary.cc
|
||||
build_binary_LDADD = libkenlm.la
|
||||
|
29
trunk/kenlm/README
Normal file
29
trunk/kenlm/README
Normal file
@ -0,0 +1,29 @@
|
||||
Language model inference code by Kenneth Heafield <infer at kheafield.com>
|
||||
The official website is http://kheafield.com/code/kenlm/ . If you're a decoder developer, please download the latest version from there instead of copying from Moses.
|
||||
|
||||
While the primary means of building kenlm for use in Moses is the Moses build system, you can also compile independently using:
|
||||
./compile.sh to compile the code
|
||||
./test.sh to compile and run tests; requires Boost
|
||||
./clean.sh to clean
|
||||
|
||||
The rest of the documentation is directed at decoder developers.
|
||||
|
||||
Binary format via mmap is supported. Run ./build_binary to make one then pass the binary file name instead.
|
||||
|
||||
Currently, it assumes POSIX APIs for errno, sterror_r, open, close, mmap, munmap, ftruncate, fstat, and read. This is tested on Linux and the non-UNIX Mac OS X. I welcome submissions porting (via #ifdef) to other systems (e.g. Windows) but proudly have no machine on which to test it.
|
||||
|
||||
A brief note to Mac OS X users: your gcc is too old to recognize the pack pragma. The warning effectively means that, on 64-bit machines, the model will use 16 bytes instead of 12 bytes per n-gram of maximum order (those of lower order are already 16 bytes) in the probing and sorted models. The trie is not impacted by this.
|
||||
|
||||
It does not depend on Boost or ICU. However, if you use Boost and/or ICU in the rest of your code, you should define HAVE_BOOST and/or HAVE_ICU in util/have.hh. Defining HAVE_BOOST will let you hash StringPiece. Defining HAVE_ICU will use ICU's StringPiece to prevent a conflict with the one provided here.
|
||||
|
||||
The recommend way to use this:
|
||||
Copy the code and distribute with your decoder.
|
||||
Set HAVE_ICU and HAVE_BOOST at the top of util/have.hh as instructed above.
|
||||
Look at compile.sh and reimplement using 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 (including for lm/model.hh).
|
||||
|
||||
I recommend copying the code and distributing it with your decoder. However, please send improvements to me so that they can be integrated into the package.
|
||||
|
||||
Also included:
|
||||
A wrapper to SRI with the same interface.
|
2
trunk/kenlm/clean.sh
Executable file
2
trunk/kenlm/clean.sh
Executable file
@ -0,0 +1,2 @@
|
||||
#!/bin/bash
|
||||
rm -rf */*.o query build_binary */*_test lm/test.binary* lm/test.arpa?????? util/file_piece.cc.gz
|
14
trunk/kenlm/compile.sh
Executable file
14
trunk/kenlm/compile.sh
Executable file
@ -0,0 +1,14 @@
|
||||
#!/bin/bash
|
||||
#This is just an example compilation. You should integrate these files into your build system. I can provide boost jam if you want.
|
||||
#If your code uses ICU, edit util/string_piece.hh and uncomment #define USE_ICU
|
||||
#I use zlib by default. If you don't want to depend on zlib, remove #define USE_ZLIB from util/file_piece.hh
|
||||
|
||||
#don't need to use if compiling with moses Makefiles already
|
||||
|
||||
set -e
|
||||
|
||||
for i in util/{bit_packing,ersatz_progress,exception,file_piece,murmur_hash,scoped,mmap} lm/{bhiksha,binary_format,config,lm_exception,model,quantize,read_arpa,search_hashed,search_trie,trie,virtual_interface,vocab}; do
|
||||
g++ -I. -O3 -DNDEBUG $CXXFLAGS -c $i.cc -o $i.o
|
||||
done
|
||||
g++ -I. -O3 -DNDEBUG $CXXFLAGS lm/build_binary.cc {lm,util}/*.o -lz -o build_binary
|
||||
g++ -I. -O3 -DNDEBUG $CXXFLAGS lm/ngram_query.cc {lm,util}/*.o -lz -o query
|
447
trunk/kenlm/kenlm.xcodeproj/project.pbxproj
Normal file
447
trunk/kenlm/kenlm.xcodeproj/project.pbxproj
Normal file
@ -0,0 +1,447 @@
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 45;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
1E2B85C412555DB1000770D6 /* lm_exception.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1E2B85C112555DB1000770D6 /* lm_exception.cc */; };
|
||||
1E2B85C512555DB1000770D6 /* lm_exception.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1E2B85C212555DB1000770D6 /* lm_exception.hh */; };
|
||||
1E37EBC712496AB400C1C73A /* virtual_interface.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1E37EBC512496AB400C1C73A /* virtual_interface.cc */; };
|
||||
1E37EBC812496AB400C1C73A /* virtual_interface.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1E37EBC612496AB400C1C73A /* virtual_interface.hh */; };
|
||||
1E46B59E13BA5BE10084F898 /* blank.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1E46B59D13BA5BE10084F898 /* blank.hh */; };
|
||||
1E46B5A213BA5C050084F898 /* quantize.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1E46B5A013BA5C050084F898 /* quantize.cc */; };
|
||||
1E46B5A313BA5C050084F898 /* quantize.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1E46B5A113BA5C050084F898 /* quantize.hh */; };
|
||||
1E8A94FE1288BD570022C4EB /* build_binary.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1E8A94F41288BD570022C4EB /* build_binary.cc */; };
|
||||
1E8A94FF1288BD570022C4EB /* config.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1E8A94F51288BD570022C4EB /* config.cc */; };
|
||||
1E8A95001288BD570022C4EB /* config.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1E8A94F61288BD570022C4EB /* config.hh */; };
|
||||
1E8A95011288BD570022C4EB /* model_test.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1E8A94F71288BD570022C4EB /* model_test.cc */; };
|
||||
1E8A95021288BD570022C4EB /* model.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1E8A94F81288BD570022C4EB /* model.cc */; };
|
||||
1E8A95031288BD570022C4EB /* model.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1E8A94F91288BD570022C4EB /* model.hh */; };
|
||||
1E8A95041288BD570022C4EB /* search_hashed.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1E8A94FA1288BD570022C4EB /* search_hashed.cc */; };
|
||||
1E8A95051288BD570022C4EB /* search_hashed.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1E8A94FB1288BD570022C4EB /* search_hashed.hh */; };
|
||||
1E8A95061288BD570022C4EB /* search_trie.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1E8A94FC1288BD570022C4EB /* search_trie.cc */; };
|
||||
1E8A95071288BD570022C4EB /* search_trie.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1E8A94FD1288BD570022C4EB /* search_trie.hh */; };
|
||||
1E8BF78A1278A434009F10C1 /* binary_format.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1E8BF7871278A434009F10C1 /* binary_format.cc */; };
|
||||
1E8BF78B1278A434009F10C1 /* binary_format.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1E8BF7881278A434009F10C1 /* binary_format.hh */; };
|
||||
1E8BF78C1278A434009F10C1 /* enumerate_vocab.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1E8BF7891278A434009F10C1 /* enumerate_vocab.hh */; };
|
||||
1E8BF79D1278A443009F10C1 /* trie.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1E8BF7951278A443009F10C1 /* trie.cc */; };
|
||||
1E8BF79E1278A443009F10C1 /* trie.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1E8BF7961278A443009F10C1 /* trie.hh */; };
|
||||
1E8BF7D51278A600009F10C1 /* bit_packing.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1E8BF7D41278A600009F10C1 /* bit_packing.cc */; };
|
||||
1E91441413D065490005055B /* bhiksha.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1E91441213D065490005055B /* bhiksha.cc */; };
|
||||
1E91441513D065490005055B /* bhiksha.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1E91441313D065490005055B /* bhiksha.hh */; };
|
||||
1EBB16D7126C158600AE6102 /* ersatz_progress.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EBB16BF126C158600AE6102 /* ersatz_progress.cc */; };
|
||||
1EBB16D8126C158600AE6102 /* ersatz_progress.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EBB16C0126C158600AE6102 /* ersatz_progress.hh */; };
|
||||
1EBB16D9126C158600AE6102 /* exception.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EBB16C1126C158600AE6102 /* exception.cc */; };
|
||||
1EBB16DA126C158600AE6102 /* exception.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EBB16C2126C158600AE6102 /* exception.hh */; };
|
||||
1EBB16DC126C158600AE6102 /* file_piece.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EBB16C4126C158600AE6102 /* file_piece.cc */; };
|
||||
1EBB16DD126C158600AE6102 /* file_piece.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EBB16C5126C158600AE6102 /* file_piece.hh */; };
|
||||
1EBB16DE126C158600AE6102 /* joint_sort_test.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EBB16C6126C158600AE6102 /* joint_sort_test.cc */; };
|
||||
1EBB16DF126C158600AE6102 /* joint_sort.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EBB16C7126C158600AE6102 /* joint_sort.hh */; };
|
||||
1EBB16E0126C158600AE6102 /* key_value_packing_test.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EBB16C8126C158600AE6102 /* key_value_packing_test.cc */; };
|
||||
1EBB16E1126C158600AE6102 /* key_value_packing.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EBB16C9126C158600AE6102 /* key_value_packing.hh */; };
|
||||
1EBB16E2126C158600AE6102 /* mmap.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EBB16CA126C158600AE6102 /* mmap.cc */; };
|
||||
1EBB16E3126C158600AE6102 /* mmap.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EBB16CB126C158600AE6102 /* mmap.hh */; };
|
||||
1EBB16E4126C158600AE6102 /* murmur_hash.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EBB16CC126C158600AE6102 /* murmur_hash.cc */; };
|
||||
1EBB16E5126C158600AE6102 /* murmur_hash.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EBB16CD126C158600AE6102 /* murmur_hash.hh */; };
|
||||
1EBB16E6126C158600AE6102 /* probing_hash_table_test.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EBB16CE126C158600AE6102 /* probing_hash_table_test.cc */; };
|
||||
1EBB16E7126C158600AE6102 /* probing_hash_table.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EBB16CF126C158600AE6102 /* probing_hash_table.hh */; };
|
||||
1EBB16E8126C158600AE6102 /* proxy_iterator.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EBB16D0126C158600AE6102 /* proxy_iterator.hh */; };
|
||||
1EBB16E9126C158600AE6102 /* scoped.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EBB16D1126C158600AE6102 /* scoped.cc */; };
|
||||
1EBB16EA126C158600AE6102 /* scoped.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EBB16D2126C158600AE6102 /* scoped.hh */; };
|
||||
1EBB16EB126C158600AE6102 /* sorted_uniform_test.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EBB16D3126C158600AE6102 /* sorted_uniform_test.cc */; };
|
||||
1EBB16EC126C158600AE6102 /* sorted_uniform.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EBB16D4126C158600AE6102 /* sorted_uniform.hh */; };
|
||||
1EBB16EE126C158600AE6102 /* string_piece.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EBB16D6126C158600AE6102 /* string_piece.hh */; };
|
||||
1EBB1717126C15C500AE6102 /* facade.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EBB1708126C15C500AE6102 /* facade.hh */; };
|
||||
1EBB171A126C15C500AE6102 /* ngram_query.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EBB170B126C15C500AE6102 /* ngram_query.cc */; };
|
||||
1EBB171C126C15C500AE6102 /* read_arpa.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EBB170D126C15C500AE6102 /* read_arpa.cc */; };
|
||||
1EBB171D126C15C500AE6102 /* read_arpa.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EBB170E126C15C500AE6102 /* read_arpa.hh */; };
|
||||
1EBB171E126C15C500AE6102 /* sri_test.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EBB170F126C15C500AE6102 /* sri_test.cc */; };
|
||||
1EBB171F126C15C500AE6102 /* sri.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EBB1710126C15C500AE6102 /* sri.cc */; };
|
||||
1EBB1720126C15C500AE6102 /* sri.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EBB1711126C15C500AE6102 /* sri.hh */; };
|
||||
1EBB1721126C15C500AE6102 /* vocab.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EBB1713126C15C500AE6102 /* vocab.cc */; };
|
||||
1EBB1722126C15C500AE6102 /* vocab.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EBB1714126C15C500AE6102 /* vocab.hh */; };
|
||||
1EBB1723126C15C500AE6102 /* weights.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EBB1715126C15C500AE6102 /* weights.hh */; };
|
||||
1EBB1724126C15C500AE6102 /* word_index.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EBB1716126C15C500AE6102 /* word_index.hh */; };
|
||||
1ED9988712783457006BBB6C /* file_piece_test.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1ED9988612783457006BBB6C /* file_piece_test.cc */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
1E2B85C112555DB1000770D6 /* lm_exception.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = lm_exception.cc; path = lm/lm_exception.cc; sourceTree = "<group>"; };
|
||||
1E2B85C212555DB1000770D6 /* lm_exception.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = lm_exception.hh; path = lm/lm_exception.hh; sourceTree = "<group>"; };
|
||||
1E37EBC512496AB400C1C73A /* virtual_interface.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = virtual_interface.cc; path = lm/virtual_interface.cc; sourceTree = "<group>"; };
|
||||
1E37EBC612496AB400C1C73A /* virtual_interface.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = virtual_interface.hh; path = lm/virtual_interface.hh; sourceTree = "<group>"; };
|
||||
1E46B59D13BA5BE10084F898 /* blank.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = blank.hh; path = lm/blank.hh; sourceTree = "<group>"; };
|
||||
1E46B5A013BA5C050084F898 /* quantize.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = quantize.cc; path = lm/quantize.cc; sourceTree = "<group>"; };
|
||||
1E46B5A113BA5C050084F898 /* quantize.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = quantize.hh; path = lm/quantize.hh; sourceTree = "<group>"; };
|
||||
1E8A94F41288BD570022C4EB /* build_binary.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = build_binary.cc; path = lm/build_binary.cc; sourceTree = "<group>"; };
|
||||
1E8A94F51288BD570022C4EB /* config.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = config.cc; path = lm/config.cc; sourceTree = "<group>"; };
|
||||
1E8A94F61288BD570022C4EB /* config.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = config.hh; path = lm/config.hh; sourceTree = "<group>"; };
|
||||
1E8A94F71288BD570022C4EB /* model_test.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = model_test.cc; path = lm/model_test.cc; sourceTree = "<group>"; };
|
||||
1E8A94F81288BD570022C4EB /* model.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = model.cc; path = lm/model.cc; sourceTree = "<group>"; };
|
||||
1E8A94F91288BD570022C4EB /* model.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = model.hh; path = lm/model.hh; sourceTree = "<group>"; };
|
||||
1E8A94FA1288BD570022C4EB /* search_hashed.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = search_hashed.cc; path = lm/search_hashed.cc; sourceTree = "<group>"; };
|
||||
1E8A94FB1288BD570022C4EB /* search_hashed.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = search_hashed.hh; path = lm/search_hashed.hh; sourceTree = "<group>"; };
|
||||
1E8A94FC1288BD570022C4EB /* search_trie.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = search_trie.cc; path = lm/search_trie.cc; sourceTree = "<group>"; };
|
||||
1E8A94FD1288BD570022C4EB /* search_trie.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = search_trie.hh; path = lm/search_trie.hh; sourceTree = "<group>"; };
|
||||
1E8BF7871278A434009F10C1 /* binary_format.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = binary_format.cc; path = lm/binary_format.cc; sourceTree = "<group>"; };
|
||||
1E8BF7881278A434009F10C1 /* binary_format.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = binary_format.hh; path = lm/binary_format.hh; sourceTree = "<group>"; };
|
||||
1E8BF7891278A434009F10C1 /* enumerate_vocab.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = enumerate_vocab.hh; path = lm/enumerate_vocab.hh; sourceTree = "<group>"; };
|
||||
1E8BF7951278A443009F10C1 /* trie.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = trie.cc; path = lm/trie.cc; sourceTree = "<group>"; };
|
||||
1E8BF7961278A443009F10C1 /* trie.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = trie.hh; path = lm/trie.hh; sourceTree = "<group>"; };
|
||||
1E8BF7D41278A600009F10C1 /* bit_packing.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = bit_packing.cc; path = util/bit_packing.cc; sourceTree = "<group>"; };
|
||||
1E91441213D065490005055B /* bhiksha.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = bhiksha.cc; path = lm/bhiksha.cc; sourceTree = "<group>"; };
|
||||
1E91441313D065490005055B /* bhiksha.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = bhiksha.hh; path = lm/bhiksha.hh; sourceTree = "<group>"; };
|
||||
1EBB16BF126C158600AE6102 /* ersatz_progress.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ersatz_progress.cc; path = util/ersatz_progress.cc; sourceTree = "<group>"; };
|
||||
1EBB16C0126C158600AE6102 /* ersatz_progress.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = ersatz_progress.hh; path = util/ersatz_progress.hh; sourceTree = "<group>"; };
|
||||
1EBB16C1126C158600AE6102 /* exception.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = exception.cc; path = util/exception.cc; sourceTree = "<group>"; };
|
||||
1EBB16C2126C158600AE6102 /* exception.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = exception.hh; path = util/exception.hh; sourceTree = "<group>"; };
|
||||
1EBB16C4126C158600AE6102 /* file_piece.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = file_piece.cc; path = util/file_piece.cc; sourceTree = "<group>"; };
|
||||
1EBB16C5126C158600AE6102 /* file_piece.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = file_piece.hh; path = util/file_piece.hh; sourceTree = "<group>"; };
|
||||
1EBB16C6126C158600AE6102 /* joint_sort_test.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = joint_sort_test.cc; path = util/joint_sort_test.cc; sourceTree = "<group>"; };
|
||||
1EBB16C7126C158600AE6102 /* joint_sort.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = joint_sort.hh; path = util/joint_sort.hh; sourceTree = "<group>"; };
|
||||
1EBB16C8126C158600AE6102 /* key_value_packing_test.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = key_value_packing_test.cc; path = util/key_value_packing_test.cc; sourceTree = "<group>"; };
|
||||
1EBB16C9126C158600AE6102 /* key_value_packing.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = key_value_packing.hh; path = util/key_value_packing.hh; sourceTree = "<group>"; };
|
||||
1EBB16CA126C158600AE6102 /* mmap.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = mmap.cc; path = util/mmap.cc; sourceTree = "<group>"; };
|
||||
1EBB16CB126C158600AE6102 /* mmap.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = mmap.hh; path = util/mmap.hh; sourceTree = "<group>"; };
|
||||
1EBB16CC126C158600AE6102 /* murmur_hash.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = murmur_hash.cc; path = util/murmur_hash.cc; sourceTree = "<group>"; };
|
||||
1EBB16CD126C158600AE6102 /* murmur_hash.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = murmur_hash.hh; path = util/murmur_hash.hh; sourceTree = "<group>"; };
|
||||
1EBB16CE126C158600AE6102 /* probing_hash_table_test.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = probing_hash_table_test.cc; path = util/probing_hash_table_test.cc; sourceTree = "<group>"; };
|
||||
1EBB16CF126C158600AE6102 /* probing_hash_table.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = probing_hash_table.hh; path = util/probing_hash_table.hh; sourceTree = "<group>"; };
|
||||
1EBB16D0126C158600AE6102 /* proxy_iterator.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = proxy_iterator.hh; path = util/proxy_iterator.hh; sourceTree = "<group>"; };
|
||||
1EBB16D1126C158600AE6102 /* scoped.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = scoped.cc; path = util/scoped.cc; sourceTree = "<group>"; };
|
||||
1EBB16D2126C158600AE6102 /* scoped.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = scoped.hh; path = util/scoped.hh; sourceTree = "<group>"; };
|
||||
1EBB16D3126C158600AE6102 /* sorted_uniform_test.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = sorted_uniform_test.cc; path = util/sorted_uniform_test.cc; sourceTree = "<group>"; };
|
||||
1EBB16D4126C158600AE6102 /* sorted_uniform.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = sorted_uniform.hh; path = util/sorted_uniform.hh; sourceTree = "<group>"; };
|
||||
1EBB16D6126C158600AE6102 /* string_piece.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = string_piece.hh; path = util/string_piece.hh; sourceTree = "<group>"; };
|
||||
1EBB1708126C15C500AE6102 /* facade.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = facade.hh; path = lm/facade.hh; sourceTree = "<group>"; };
|
||||
1EBB170B126C15C500AE6102 /* ngram_query.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ngram_query.cc; path = lm/ngram_query.cc; sourceTree = "<group>"; };
|
||||
1EBB170D126C15C500AE6102 /* read_arpa.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = read_arpa.cc; path = lm/read_arpa.cc; sourceTree = "<group>"; };
|
||||
1EBB170E126C15C500AE6102 /* read_arpa.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = read_arpa.hh; path = lm/read_arpa.hh; sourceTree = "<group>"; };
|
||||
1EBB170F126C15C500AE6102 /* sri_test.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = sri_test.cc; path = lm/sri_test.cc; sourceTree = "<group>"; };
|
||||
1EBB1710126C15C500AE6102 /* sri.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = sri.cc; path = lm/sri.cc; sourceTree = "<group>"; };
|
||||
1EBB1711126C15C500AE6102 /* sri.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = sri.hh; path = lm/sri.hh; sourceTree = "<group>"; };
|
||||
1EBB1712126C15C500AE6102 /* test.arpa */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = test.arpa; path = lm/test.arpa; sourceTree = "<group>"; };
|
||||
1EBB1713126C15C500AE6102 /* vocab.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = vocab.cc; path = lm/vocab.cc; sourceTree = "<group>"; };
|
||||
1EBB1714126C15C500AE6102 /* vocab.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = vocab.hh; path = lm/vocab.hh; sourceTree = "<group>"; };
|
||||
1EBB1715126C15C500AE6102 /* weights.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = weights.hh; path = lm/weights.hh; sourceTree = "<group>"; };
|
||||
1EBB1716126C15C500AE6102 /* word_index.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = word_index.hh; path = lm/word_index.hh; sourceTree = "<group>"; };
|
||||
1ED9988612783457006BBB6C /* file_piece_test.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = file_piece_test.cc; path = util/file_piece_test.cc; sourceTree = "<group>"; };
|
||||
D2AAC046055464E500DB518D /* libkenlm.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libkenlm.a; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
D289987405E68DCB004EDB86 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
08FB7794FE84155DC02AAC07 /* kenlm */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
08FB7795FE84155DC02AAC07 /* Source */,
|
||||
C6A0FF2B0290797F04C91782 /* Documentation */,
|
||||
1AB674ADFE9D54B511CA2CBB /* Products */,
|
||||
);
|
||||
name = kenlm;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
08FB7795FE84155DC02AAC07 /* Source */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1E91441213D065490005055B /* bhiksha.cc */,
|
||||
1E91441313D065490005055B /* bhiksha.hh */,
|
||||
1E46B5A013BA5C050084F898 /* quantize.cc */,
|
||||
1E46B5A113BA5C050084F898 /* quantize.hh */,
|
||||
1E46B59D13BA5BE10084F898 /* blank.hh */,
|
||||
1E8A94F41288BD570022C4EB /* build_binary.cc */,
|
||||
1E8A94F51288BD570022C4EB /* config.cc */,
|
||||
1E8A94F61288BD570022C4EB /* config.hh */,
|
||||
1E8A94F71288BD570022C4EB /* model_test.cc */,
|
||||
1E8A94F81288BD570022C4EB /* model.cc */,
|
||||
1E8A94F91288BD570022C4EB /* model.hh */,
|
||||
1E8A94FA1288BD570022C4EB /* search_hashed.cc */,
|
||||
1E8A94FB1288BD570022C4EB /* search_hashed.hh */,
|
||||
1E8A94FC1288BD570022C4EB /* search_trie.cc */,
|
||||
1E8A94FD1288BD570022C4EB /* search_trie.hh */,
|
||||
1E8BF7D41278A600009F10C1 /* bit_packing.cc */,
|
||||
1E8BF7951278A443009F10C1 /* trie.cc */,
|
||||
1E8BF7961278A443009F10C1 /* trie.hh */,
|
||||
1E8BF7871278A434009F10C1 /* binary_format.cc */,
|
||||
1E8BF7881278A434009F10C1 /* binary_format.hh */,
|
||||
1E8BF7891278A434009F10C1 /* enumerate_vocab.hh */,
|
||||
1ED9988612783457006BBB6C /* file_piece_test.cc */,
|
||||
1EBB1708126C15C500AE6102 /* facade.hh */,
|
||||
1EBB170B126C15C500AE6102 /* ngram_query.cc */,
|
||||
1EBB170D126C15C500AE6102 /* read_arpa.cc */,
|
||||
1EBB170E126C15C500AE6102 /* read_arpa.hh */,
|
||||
1EBB170F126C15C500AE6102 /* sri_test.cc */,
|
||||
1EBB1710126C15C500AE6102 /* sri.cc */,
|
||||
1EBB1711126C15C500AE6102 /* sri.hh */,
|
||||
1EBB1712126C15C500AE6102 /* test.arpa */,
|
||||
1EBB1713126C15C500AE6102 /* vocab.cc */,
|
||||
1EBB1714126C15C500AE6102 /* vocab.hh */,
|
||||
1EBB1715126C15C500AE6102 /* weights.hh */,
|
||||
1EBB1716126C15C500AE6102 /* word_index.hh */,
|
||||
1EBB16BF126C158600AE6102 /* ersatz_progress.cc */,
|
||||
1EBB16C0126C158600AE6102 /* ersatz_progress.hh */,
|
||||
1EBB16C1126C158600AE6102 /* exception.cc */,
|
||||
1EBB16C2126C158600AE6102 /* exception.hh */,
|
||||
1EBB16C4126C158600AE6102 /* file_piece.cc */,
|
||||
1EBB16C5126C158600AE6102 /* file_piece.hh */,
|
||||
1EBB16C6126C158600AE6102 /* joint_sort_test.cc */,
|
||||
1EBB16C7126C158600AE6102 /* joint_sort.hh */,
|
||||
1EBB16C8126C158600AE6102 /* key_value_packing_test.cc */,
|
||||
1EBB16C9126C158600AE6102 /* key_value_packing.hh */,
|
||||
1EBB16CA126C158600AE6102 /* mmap.cc */,
|
||||
1EBB16CB126C158600AE6102 /* mmap.hh */,
|
||||
1EBB16CC126C158600AE6102 /* murmur_hash.cc */,
|
||||
1EBB16CD126C158600AE6102 /* murmur_hash.hh */,
|
||||
1EBB16CE126C158600AE6102 /* probing_hash_table_test.cc */,
|
||||
1EBB16CF126C158600AE6102 /* probing_hash_table.hh */,
|
||||
1EBB16D0126C158600AE6102 /* proxy_iterator.hh */,
|
||||
1EBB16D1126C158600AE6102 /* scoped.cc */,
|
||||
1EBB16D2126C158600AE6102 /* scoped.hh */,
|
||||
1EBB16D3126C158600AE6102 /* sorted_uniform_test.cc */,
|
||||
1EBB16D4126C158600AE6102 /* sorted_uniform.hh */,
|
||||
1EBB16D6126C158600AE6102 /* string_piece.hh */,
|
||||
1E2B85C112555DB1000770D6 /* lm_exception.cc */,
|
||||
1E2B85C212555DB1000770D6 /* lm_exception.hh */,
|
||||
1E37EBC512496AB400C1C73A /* virtual_interface.cc */,
|
||||
1E37EBC612496AB400C1C73A /* virtual_interface.hh */,
|
||||
);
|
||||
name = Source;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
1AB674ADFE9D54B511CA2CBB /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
D2AAC046055464E500DB518D /* libkenlm.a */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
C6A0FF2B0290797F04C91782 /* Documentation */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
);
|
||||
name = Documentation;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXHeadersBuildPhase section */
|
||||
D2AAC043055464E500DB518D /* Headers */ = {
|
||||
isa = PBXHeadersBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
1E37EBC812496AB400C1C73A /* virtual_interface.hh in Headers */,
|
||||
1E2B85C512555DB1000770D6 /* lm_exception.hh in Headers */,
|
||||
1EBB16D8126C158600AE6102 /* ersatz_progress.hh in Headers */,
|
||||
1EBB16DA126C158600AE6102 /* exception.hh in Headers */,
|
||||
1EBB16DD126C158600AE6102 /* file_piece.hh in Headers */,
|
||||
1EBB16DF126C158600AE6102 /* joint_sort.hh in Headers */,
|
||||
1EBB16E1126C158600AE6102 /* key_value_packing.hh in Headers */,
|
||||
1EBB16E3126C158600AE6102 /* mmap.hh in Headers */,
|
||||
1EBB16E5126C158600AE6102 /* murmur_hash.hh in Headers */,
|
||||
1EBB16E7126C158600AE6102 /* probing_hash_table.hh in Headers */,
|
||||
1EBB16E8126C158600AE6102 /* proxy_iterator.hh in Headers */,
|
||||
1EBB16EA126C158600AE6102 /* scoped.hh in Headers */,
|
||||
1EBB16EC126C158600AE6102 /* sorted_uniform.hh in Headers */,
|
||||
1EBB16EE126C158600AE6102 /* string_piece.hh in Headers */,
|
||||
1EBB1717126C15C500AE6102 /* facade.hh in Headers */,
|
||||
1EBB171D126C15C500AE6102 /* read_arpa.hh in Headers */,
|
||||
1EBB1720126C15C500AE6102 /* sri.hh in Headers */,
|
||||
1EBB1722126C15C500AE6102 /* vocab.hh in Headers */,
|
||||
1EBB1723126C15C500AE6102 /* weights.hh in Headers */,
|
||||
1EBB1724126C15C500AE6102 /* word_index.hh in Headers */,
|
||||
1E8BF78B1278A434009F10C1 /* binary_format.hh in Headers */,
|
||||
1E8BF78C1278A434009F10C1 /* enumerate_vocab.hh in Headers */,
|
||||
1E8BF79E1278A443009F10C1 /* trie.hh in Headers */,
|
||||
1E8A95001288BD570022C4EB /* config.hh in Headers */,
|
||||
1E8A95031288BD570022C4EB /* model.hh in Headers */,
|
||||
1E8A95051288BD570022C4EB /* search_hashed.hh in Headers */,
|
||||
1E8A95071288BD570022C4EB /* search_trie.hh in Headers */,
|
||||
1E46B59E13BA5BE10084F898 /* blank.hh in Headers */,
|
||||
1E46B5A313BA5C050084F898 /* quantize.hh in Headers */,
|
||||
1E91441513D065490005055B /* bhiksha.hh in Headers */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXHeadersBuildPhase section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
D2AAC045055464E500DB518D /* kenlm */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 1DEB91EB08733DB70010E9CD /* Build configuration list for PBXNativeTarget "kenlm" */;
|
||||
buildPhases = (
|
||||
D2AAC043055464E500DB518D /* Headers */,
|
||||
D2AAC044055464E500DB518D /* Sources */,
|
||||
D289987405E68DCB004EDB86 /* Frameworks */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = kenlm;
|
||||
productName = kenlm;
|
||||
productReference = D2AAC046055464E500DB518D /* libkenlm.a */;
|
||||
productType = "com.apple.product-type.library.static";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
08FB7793FE84155DC02AAC07 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
buildConfigurationList = 1DEB91EF08733DB70010E9CD /* Build configuration list for PBXProject "kenlm" */;
|
||||
compatibilityVersion = "Xcode 3.1";
|
||||
developmentRegion = English;
|
||||
hasScannedForEncodings = 1;
|
||||
knownRegions = (
|
||||
English,
|
||||
Japanese,
|
||||
French,
|
||||
German,
|
||||
);
|
||||
mainGroup = 08FB7794FE84155DC02AAC07 /* kenlm */;
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
D2AAC045055464E500DB518D /* kenlm */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
D2AAC044055464E500DB518D /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
1E37EBC712496AB400C1C73A /* virtual_interface.cc in Sources */,
|
||||
1E2B85C412555DB1000770D6 /* lm_exception.cc in Sources */,
|
||||
1EBB16D7126C158600AE6102 /* ersatz_progress.cc in Sources */,
|
||||
1EBB16D9126C158600AE6102 /* exception.cc in Sources */,
|
||||
1EBB16DC126C158600AE6102 /* file_piece.cc in Sources */,
|
||||
1EBB16DE126C158600AE6102 /* joint_sort_test.cc in Sources */,
|
||||
1EBB16E0126C158600AE6102 /* key_value_packing_test.cc in Sources */,
|
||||
1EBB16E2126C158600AE6102 /* mmap.cc in Sources */,
|
||||
1EBB16E4126C158600AE6102 /* murmur_hash.cc in Sources */,
|
||||
1EBB16E6126C158600AE6102 /* probing_hash_table_test.cc in Sources */,
|
||||
1EBB16E9126C158600AE6102 /* scoped.cc in Sources */,
|
||||
1EBB16EB126C158600AE6102 /* sorted_uniform_test.cc in Sources */,
|
||||
1EBB171A126C15C500AE6102 /* ngram_query.cc in Sources */,
|
||||
1EBB171C126C15C500AE6102 /* read_arpa.cc in Sources */,
|
||||
1EBB171E126C15C500AE6102 /* sri_test.cc in Sources */,
|
||||
1EBB171F126C15C500AE6102 /* sri.cc in Sources */,
|
||||
1EBB1721126C15C500AE6102 /* vocab.cc in Sources */,
|
||||
1ED9988712783457006BBB6C /* file_piece_test.cc in Sources */,
|
||||
1E8BF78A1278A434009F10C1 /* binary_format.cc in Sources */,
|
||||
1E8BF79D1278A443009F10C1 /* trie.cc in Sources */,
|
||||
1E8BF7D51278A600009F10C1 /* bit_packing.cc in Sources */,
|
||||
1E8A94FE1288BD570022C4EB /* build_binary.cc in Sources */,
|
||||
1E8A94FF1288BD570022C4EB /* config.cc in Sources */,
|
||||
1E8A95011288BD570022C4EB /* model_test.cc in Sources */,
|
||||
1E8A95021288BD570022C4EB /* model.cc in Sources */,
|
||||
1E8A95041288BD570022C4EB /* search_hashed.cc in Sources */,
|
||||
1E8A95061288BD570022C4EB /* search_trie.cc in Sources */,
|
||||
1E46B5A213BA5C050084F898 /* quantize.cc in Sources */,
|
||||
1E91441413D065490005055B /* bhiksha.cc in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
1DEB91EC08733DB70010E9CD /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
GCC_DYNAMIC_NO_PIC = NO;
|
||||
GCC_ENABLE_FIX_AND_CONTINUE = YES;
|
||||
GCC_MODEL_TUNING = G5;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
INSTALL_PATH = /usr/local/lib;
|
||||
PRODUCT_NAME = kenlm;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
1DEB91ED08733DB70010E9CD /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
GCC_MODEL_TUNING = G5;
|
||||
INSTALL_PATH = /usr/local/lib;
|
||||
PRODUCT_NAME = kenlm;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
1DEB91F008733DB70010E9CD /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
|
||||
GCC_C_LANGUAGE_STANDARD = gnu99;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
HEADER_SEARCH_PATHS = (
|
||||
/Users/hieuhoang/workspace/sourceforge/trunk/kenlm,
|
||||
/usr/local/include,
|
||||
../srilm/include,
|
||||
);
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
PREBINDING = NO;
|
||||
SDKROOT = macosx10.6;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
1DEB91F108733DB70010E9CD /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
|
||||
GCC_C_LANGUAGE_STANDARD = gnu99;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
HEADER_SEARCH_PATHS = (
|
||||
/Users/hieuhoang/workspace/sourceforge/trunk/kenlm,
|
||||
/usr/local/include,
|
||||
../srilm/include,
|
||||
);
|
||||
PREBINDING = NO;
|
||||
SDKROOT = macosx10.6;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
1DEB91EB08733DB70010E9CD /* Build configuration list for PBXNativeTarget "kenlm" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
1DEB91EC08733DB70010E9CD /* Debug */,
|
||||
1DEB91ED08733DB70010E9CD /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
1DEB91EF08733DB70010E9CD /* Build configuration list for PBXProject "kenlm" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
1DEB91F008733DB70010E9CD /* Debug */,
|
||||
1DEB91F108733DB70010E9CD /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
};
|
||||
rootObject = 08FB7793FE84155DC02AAC07 /* Project object */;
|
||||
}
|
96
trunk/kenlm/lm/bhiksha.cc
Normal file
96
trunk/kenlm/lm/bhiksha.cc
Normal file
@ -0,0 +1,96 @@
|
||||
#include "lm/bhiksha.hh"
|
||||
#include "lm/config.hh"
|
||||
|
||||
#include <iostream>
|
||||
#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;
|
||||
|
||||
void ArrayBhiksha::UpdateConfigFromBinary(int fd, Config &config) {
|
||||
uint8_t version;
|
||||
uint8_t configured_bits;
|
||||
if (read(fd, &version, 1) != 1 || read(fd, &configured_bits, 1) != 1) {
|
||||
UTIL_THROW(util::ErrnoException, "Could not read from binary file");
|
||||
}
|
||||
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
|
||||
|
||||
std::size_t ArrayBhiksha::Size(uint64_t max_offset, uint64_t max_next, const Config &config) {
|
||||
std::size_t ret = sizeof(uint64_t) * (1 /* header */ + ArrayCount(max_offset, max_next, config)) + 7 /* 8-byte alignment */;
|
||||
std::cout << ret << std::endl;
|
||||
return ret;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
void ArrayBhiksha::LoadedBinary() {
|
||||
}
|
||||
|
||||
} // namespace trie
|
||||
} // namespace ngram
|
||||
} // namespace lm
|
108
trunk/kenlm/lm/bhiksha.hh
Normal file
108
trunk/kenlm/lm/bhiksha.hh
Normal file
@ -0,0 +1,108 @@
|
||||
/* 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.
|
||||
*/
|
||||
|
||||
#include <inttypes.h>
|
||||
|
||||
#include "lm/binary_format.hh"
|
||||
#include "lm/trie.hh"
|
||||
#include "util/bit_packing.hh"
|
||||
#include "util/sorted_uniform.hh"
|
||||
|
||||
namespace lm {
|
||||
namespace ngram {
|
||||
class Config;
|
||||
|
||||
namespace trie {
|
||||
|
||||
class DontBhiksha {
|
||||
public:
|
||||
static const ModelType kModelTypeAdd = static_cast<ModelType>(0);
|
||||
|
||||
static void UpdateConfigFromBinary(int /*fd*/, Config &/*config*/) {}
|
||||
|
||||
static std::size_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*/) {}
|
||||
|
||||
void LoadedBinary() {}
|
||||
|
||||
uint8_t InlineBits() const { return next_.bits; }
|
||||
|
||||
private:
|
||||
util::BitsMask next_;
|
||||
};
|
||||
|
||||
class ArrayBhiksha {
|
||||
public:
|
||||
static const ModelType kModelTypeAdd = kArrayAdd;
|
||||
|
||||
static void UpdateConfigFromBinary(int fd, Config &config);
|
||||
|
||||
static std::size_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 {
|
||||
const uint64_t *begin_it = util::BinaryBelow(util::IdentityAccessor<uint64_t>(), offset_begin_, offset_end_, index);
|
||||
const uint64_t *end_it;
|
||||
for (end_it = begin_it; (end_it < offset_end_) && (*end_it <= index + 1); ++end_it) {}
|
||||
--end_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);
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
void LoadedBinary();
|
||||
|
||||
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
|
227
trunk/kenlm/lm/binary_format.cc
Normal file
227
trunk/kenlm/lm/binary_format.cc
Normal file
@ -0,0 +1,227 @@
|
||||
#include "lm/binary_format.hh"
|
||||
|
||||
#include "lm/lm_exception.hh"
|
||||
#include "util/file_piece.hh"
|
||||
|
||||
#include <limits>
|
||||
#include <string>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <errno.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace lm {
|
||||
namespace ngram {
|
||||
namespace {
|
||||
const char kMagicBeforeVersion[] = "mmap lm http://kheafield.com/code format version";
|
||||
const char kMagicBytes[] = "mmap lm http://kheafield.com/code format version 4\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 = 4;
|
||||
|
||||
// Test values.
|
||||
struct Sanity {
|
||||
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::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;
|
||||
}
|
||||
};
|
||||
|
||||
const char *kModelNames[6] = {"hashed n-grams with probing", "hashed n-grams with sorted uniform find", "trie", "trie with quantization", "trie with array-compressed pointers", "trie with quantization and array-compressed pointers"};
|
||||
|
||||
std::size_t Align8(std::size_t in) {
|
||||
std::size_t off = in % 8;
|
||||
if (!off) return in;
|
||||
return in + 8 - off;
|
||||
}
|
||||
|
||||
std::size_t TotalHeaderSize(unsigned char order) {
|
||||
return Align8(sizeof(Sanity) + sizeof(FixedWidthParameters) + sizeof(uint64_t) * order);
|
||||
}
|
||||
|
||||
void ReadLoop(int fd, void *to_void, std::size_t size) {
|
||||
uint8_t *to = static_cast<uint8_t*>(to_void);
|
||||
while (size) {
|
||||
ssize_t ret = read(fd, to, size);
|
||||
if (ret == -1) UTIL_THROW(util::ErrnoException, "Failed to read from binary file");
|
||||
if (ret == 0) UTIL_THROW(util::ErrnoException, "Binary file too short");
|
||||
to += ret;
|
||||
size -= ret;
|
||||
}
|
||||
}
|
||||
|
||||
void WriteHeader(void *to, const Parameters ¶ms) {
|
||||
Sanity header = Sanity();
|
||||
header.SetToReference();
|
||||
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
|
||||
|
||||
void SeekOrThrow(int fd, off_t off) {
|
||||
if ((off_t)-1 == lseek(fd, off, SEEK_SET)) UTIL_THROW(util::ErrnoException, "Seek failed");
|
||||
}
|
||||
|
||||
void AdvanceOrThrow(int fd, off_t off) {
|
||||
if ((off_t)-1 == lseek(fd, off, SEEK_CUR)) UTIL_THROW(util::ErrnoException, "Seek failed");
|
||||
}
|
||||
|
||||
uint8_t *SetupJustVocab(const Config &config, uint8_t order, std::size_t memory_size, Backing &backing) {
|
||||
if (config.write_mmap) {
|
||||
std::size_t total = TotalHeaderSize(order) + memory_size;
|
||||
backing.vocab.reset(util::MapZeroedWrite(config.write_mmap, total, backing.file), total, util::scoped_memory::MMAP_ALLOCATED);
|
||||
strncpy(reinterpret_cast<char*>(backing.vocab.get()), kMagicIncomplete, TotalHeaderSize(order));
|
||||
return reinterpret_cast<uint8_t*>(backing.vocab.get()) + TotalHeaderSize(order);
|
||||
} else {
|
||||
backing.vocab.reset(util::MapAnonymous(memory_size), memory_size, util::scoped_memory::MMAP_ALLOCATED);
|
||||
return reinterpret_cast<uint8_t*>(backing.vocab.get());
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t *GrowForSearch(const Config &config, std::size_t memory_size, Backing &backing) {
|
||||
if (config.write_mmap) {
|
||||
// Grow the file to accomodate the search, using zeros.
|
||||
if (-1 == ftruncate(backing.file.get(), backing.vocab.size() + memory_size))
|
||||
UTIL_THROW(util::ErrnoException, "ftruncate on " << config.write_mmap << " to " << (backing.vocab.size() + memory_size) << " failed");
|
||||
|
||||
// We're skipping over the header and vocab for the search space mmap. mmap likes page aligned offsets, so some arithmetic to round the offset down.
|
||||
off_t page_size = sysconf(_SC_PAGE_SIZE);
|
||||
off_t alignment_cruft = backing.vocab.size() % page_size;
|
||||
backing.search.reset(util::MapOrThrow(alignment_cruft + memory_size, true, util::kFileFlags, false, backing.file.get(), backing.vocab.size() - alignment_cruft), alignment_cruft + memory_size, util::scoped_memory::MMAP_ALLOCATED);
|
||||
|
||||
return reinterpret_cast<uint8_t*>(backing.search.get()) + alignment_cruft;
|
||||
} else {
|
||||
backing.search.reset(util::MapAnonymous(memory_size), memory_size, util::scoped_memory::MMAP_ALLOCATED);
|
||||
return reinterpret_cast<uint8_t*>(backing.search.get());
|
||||
}
|
||||
}
|
||||
|
||||
void FinishFile(const Config &config, ModelType model_type, const std::vector<uint64_t> &counts, Backing &backing) {
|
||||
if (config.write_mmap) {
|
||||
if (msync(backing.search.get(), backing.search.size(), MS_SYNC) || msync(backing.vocab.get(), backing.vocab.size(), MS_SYNC))
|
||||
UTIL_THROW(util::ErrnoException, "msync failed for " << config.write_mmap);
|
||||
// header and vocab share the same mmap. The header is written here because we know the counts.
|
||||
Parameters params;
|
||||
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;
|
||||
WriteHeader(backing.vocab.get(), params);
|
||||
}
|
||||
}
|
||||
|
||||
namespace detail {
|
||||
|
||||
bool IsBinaryFormat(int fd) {
|
||||
const off_t size = util::SizeFile(fd);
|
||||
if (size == util::kBadSize || (size <= static_cast<off_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 (!memcmp(memory.get(), &reference_header, sizeof(Sanity))) return true;
|
||||
if (!memcmp(memory.get(), kMagicIncomplete, strlen(kMagicIncomplete))) {
|
||||
UTIL_THROW(FormatLoadException, "This binary file did not finish building");
|
||||
}
|
||||
if (!memcmp(memory.get(), kMagicBeforeVersion, strlen(kMagicBeforeVersion))) {
|
||||
char *end_ptr;
|
||||
const char *begin_version = static_cast<const char*>(memory.get()) + strlen(kMagicBeforeVersion);
|
||||
long int version = 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");
|
||||
}
|
||||
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) {
|
||||
SeekOrThrow(fd, sizeof(Sanity));
|
||||
ReadLoop(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));
|
||||
ReadLoop(fd, &*out.counts.begin(), sizeof(uint64_t) * out.fixed.order);
|
||||
}
|
||||
|
||||
void MatchCheck(ModelType model_type, const Parameters ¶ms) {
|
||||
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]);
|
||||
}
|
||||
}
|
||||
|
||||
void SeekPastHeader(int fd, const Parameters ¶ms) {
|
||||
SeekOrThrow(fd, TotalHeaderSize(params.counts.size()));
|
||||
}
|
||||
|
||||
uint8_t *SetupBinary(const Config &config, const Parameters ¶ms, std::size_t memory_size, Backing &backing) {
|
||||
const off_t file_size = util::SizeFile(backing.file.get());
|
||||
// The header is smaller than a page, so we have to map the whole header as well.
|
||||
std::size_t total_map = TotalHeaderSize(params.counts.size()) + memory_size;
|
||||
if (file_size != util::kBadSize && static_cast<uint64_t>(file_size) < total_map)
|
||||
UTIL_THROW(FormatLoadException, "Binary file has size " << file_size << " but the headers say it should be at least " << total_map);
|
||||
|
||||
util::MapRead(config.load_method, backing.file.get(), 0, total_map, backing.search);
|
||||
|
||||
if (config.enumerate_vocab && !params.fixed.has_vocabulary)
|
||||
UTIL_THROW(FormatLoadException, "The decoder requested all the vocabulary strings, but this binary file does not have them. You may need to rebuild the binary file with an updated version of build_binary.");
|
||||
|
||||
if (config.enumerate_vocab) {
|
||||
SeekOrThrow(backing.file.get(), total_map);
|
||||
}
|
||||
return reinterpret_cast<uint8_t*>(backing.search.get()) + TotalHeaderSize(params.counts.size());
|
||||
}
|
||||
|
||||
void ComplainAboutARPA(const Config &config, ModelType model_type) {
|
||||
if (config.write_mmap || !config.messages) return;
|
||||
if (config.arpa_complain == Config::ALL) {
|
||||
*config.messages << "Loading the LM will be faster if you build a binary file." << std::endl;
|
||||
} else if (config.arpa_complain == Config::EXPENSIVE && model_type == TRIE_SORTED) {
|
||||
*config.messages << "Building " << kModelNames[model_type] << " from ARPA is expensive. Save time by building a binary format." << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace detail
|
||||
|
||||
bool RecognizeBinary(const char *file, ModelType &recognized) {
|
||||
util::scoped_fd fd(util::OpenReadOrThrow(file));
|
||||
if (!detail::IsBinaryFormat(fd.get())) return false;
|
||||
Parameters params;
|
||||
detail::ReadHeader(fd.get(), params);
|
||||
recognized = params.fixed.model_type;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace ngram
|
||||
} // namespace lm
|
114
trunk/kenlm/lm/binary_format.hh
Normal file
114
trunk/kenlm/lm/binary_format.hh
Normal file
@ -0,0 +1,114 @@
|
||||
#ifndef LM_BINARY_FORMAT__
|
||||
#define LM_BINARY_FORMAT__
|
||||
|
||||
#include "lm/config.hh"
|
||||
#include "lm/read_arpa.hh"
|
||||
|
||||
#include "util/file_piece.hh"
|
||||
#include "util/mmap.hh"
|
||||
#include "util/scoped.hh"
|
||||
|
||||
#include <cstddef>
|
||||
#include <vector>
|
||||
|
||||
#include <inttypes.h>
|
||||
|
||||
namespace lm {
|
||||
namespace ngram {
|
||||
|
||||
/* Not the best numbering system, but it grew this way for historical reasons
|
||||
* and I want to preserve existing binary files. */
|
||||
typedef enum {HASH_PROBING=0, HASH_SORTED=1, TRIE_SORTED=2, QUANT_TRIE_SORTED=3, ARRAY_TRIE_SORTED=4, QUANT_ARRAY_TRIE_SORTED=5} ModelType;
|
||||
|
||||
const static ModelType kQuantAdd = static_cast<ModelType>(QUANT_TRIE_SORTED - TRIE_SORTED);
|
||||
const static ModelType kArrayAdd = static_cast<ModelType>(ARRAY_TRIE_SORTED - TRIE_SORTED);
|
||||
|
||||
/*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;
|
||||
};
|
||||
|
||||
// Parameters stored in the header of a binary file.
|
||||
struct Parameters {
|
||||
FixedWidthParameters fixed;
|
||||
std::vector<uint64_t> counts;
|
||||
};
|
||||
|
||||
struct Backing {
|
||||
// File behind memory, if any.
|
||||
util::scoped_fd file;
|
||||
// Vocabulary lookup table. Not to be confused with the vocab words themselves.
|
||||
util::scoped_memory vocab;
|
||||
// Raw block of memory backing the language model data structures
|
||||
util::scoped_memory search;
|
||||
};
|
||||
|
||||
void SeekOrThrow(int fd, off_t off);
|
||||
// Seek forward
|
||||
void AdvanceOrThrow(int fd, off_t off);
|
||||
|
||||
// Create just enough of a binary file to write vocabulary to it.
|
||||
uint8_t *SetupJustVocab(const Config &config, uint8_t order, std::size_t memory_size, Backing &backing);
|
||||
// Grow the binary file for the search data structure and set backing.search, returning the memory address where the search data structure should begin.
|
||||
uint8_t *GrowForSearch(const Config &config, std::size_t memory_size, Backing &backing);
|
||||
|
||||
// Write header to binary file. This is done last to prevent incomplete files
|
||||
// from loading.
|
||||
void FinishFile(const Config &config, ModelType model_type, const std::vector<uint64_t> &counts, Backing &backing);
|
||||
|
||||
namespace detail {
|
||||
|
||||
bool IsBinaryFormat(int fd);
|
||||
|
||||
void ReadHeader(int fd, Parameters ¶ms);
|
||||
|
||||
void MatchCheck(ModelType model_type, const Parameters ¶ms);
|
||||
|
||||
void SeekPastHeader(int fd, const Parameters ¶ms);
|
||||
|
||||
uint8_t *SetupBinary(const Config &config, const Parameters ¶ms, std::size_t memory_size, Backing &backing);
|
||||
|
||||
void ComplainAboutARPA(const Config &config, ModelType model_type);
|
||||
|
||||
} // namespace detail
|
||||
|
||||
template <class To> void LoadLM(const char *file, const Config &config, To &to) {
|
||||
Backing &backing = to.MutableBacking();
|
||||
backing.file.reset(util::OpenReadOrThrow(file));
|
||||
|
||||
try {
|
||||
if (detail::IsBinaryFormat(backing.file.get())) {
|
||||
Parameters params;
|
||||
detail::ReadHeader(backing.file.get(), params);
|
||||
detail::MatchCheck(To::kModelType, params);
|
||||
// Replace the run-time configured probing_multiplier with the one in the file.
|
||||
Config new_config(config);
|
||||
new_config.probing_multiplier = params.fixed.probing_multiplier;
|
||||
detail::SeekPastHeader(backing.file.get(), params);
|
||||
To::UpdateConfigFromBinary(backing.file.get(), params.counts, new_config);
|
||||
std::size_t memory_size = To::Size(params.counts, new_config);
|
||||
uint8_t *start = detail::SetupBinary(new_config, params, memory_size, backing);
|
||||
to.InitializeFromBinary(start, params, new_config, backing.file.get());
|
||||
} else {
|
||||
detail::ComplainAboutARPA(config, To::kModelType);
|
||||
to.InitializeFromARPA(file, config);
|
||||
}
|
||||
} catch (util::Exception &e) {
|
||||
e << " File: " << file;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace ngram
|
||||
} // namespace lm
|
||||
#endif // LM_BINARY_FORMAT__
|
57
trunk/kenlm/lm/blank.hh
Normal file
57
trunk/kenlm/lm/blank.hh
Normal file
@ -0,0 +1,57 @@
|
||||
#ifndef LM_BLANK__
|
||||
#define LM_BLANK__
|
||||
|
||||
#include <limits>
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <math.h>
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/* Suppose "foo bar baz quux" appears in the ARPA but not "bar baz quux" or
|
||||
* "baz quux" (because they were pruned). 1.2% of n-grams generated by SRI
|
||||
* with default settings on the benchmark data set are like this. Since search
|
||||
* proceeds by finding "quux", "baz quux", "bar baz quux", and finally
|
||||
* "foo bar baz quux" and the trie needs pointer nodes anyway, blanks are
|
||||
* inserted. The blanks have probability kBlankProb and backoff kBlankBackoff.
|
||||
* A blank is recognized by kBlankProb in the probability field; kBlankBackoff
|
||||
* must be 0 so that inference asseses zero backoff from these blanks.
|
||||
*/
|
||||
const float kBlankProb = -std::numeric_limits<float>::infinity();
|
||||
const float kBlankBackoff = kNoExtensionBackoff;
|
||||
const uint32_t kBlankProbQuant = 0;
|
||||
const uint32_t kBlankBackoffQuant = 0;
|
||||
|
||||
} // namespace ngram
|
||||
} // namespace lm
|
||||
#endif // LM_BLANK__
|
197
trunk/kenlm/lm/build_binary.cc
Normal file
197
trunk/kenlm/lm/build_binary.cc
Normal file
@ -0,0 +1,197 @@
|
||||
#include "lm/model.hh"
|
||||
#include "util/file_piece.hh"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <exception>
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
|
||||
#include <math.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace lm {
|
||||
namespace ngram {
|
||||
namespace {
|
||||
|
||||
void Usage(const char *name) {
|
||||
std::cerr << "Usage: " << name << " [-u log10_unknown_probability] [-s] [-i] [-p probing_multiplier] [-t trie_temporary] [-m trie_building_megabytes] [-q bits] [-b bits] [-c 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\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"
|
||||
"-m limits memory use for sorting. Measured in MB. Default is 1024MB.\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"
|
||||
"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 256.";
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
void ShowSizes(const char *file, const lm::ngram::Config &config) {
|
||||
std::vector<uint64_t> counts;
|
||||
util::FilePiece f(file);
|
||||
lm::ReadARPACounts(f, counts);
|
||||
std::size_t sizes[5];
|
||||
sizes[0] = ProbingModel::Size(counts, config);
|
||||
sizes[1] = TrieModel::Size(counts, config);
|
||||
sizes[2] = QuantTrieModel::Size(counts, config);
|
||||
sizes[3] = ArrayTrieModel::Size(counts, config);
|
||||
sizes[4] = QuantArrayTrieModel::Size(counts, config);
|
||||
std::size_t max_length = *std::max_element(sizes, sizes + sizeof(sizes) / sizeof(size_t));
|
||||
std::size_t min_length = *std::min_element(sizes, sizes + sizeof(sizes) / sizeof(size_t));
|
||||
std::size_t divide;
|
||||
char prefix;
|
||||
if (min_length < (1 << 10) * 10) {
|
||||
prefix = ' ';
|
||||
divide = 1;
|
||||
} else if (min_length < (1 << 20) * 10) {
|
||||
prefix = 'k';
|
||||
divide = 1 << 10;
|
||||
} else if (min_length < (1ULL << 30) * 10) {
|
||||
prefix = 'M';
|
||||
divide = 1 << 20;
|
||||
} else {
|
||||
prefix = 'G';
|
||||
divide = 1 << 30;
|
||||
}
|
||||
long int length = std::max<long int>(2, lrint(ceil(log10(max_length / divide))));
|
||||
std::cout << "Memory estimate:\ntype ";
|
||||
// right align bytes.
|
||||
for (long int i = 0; i < length - 2; ++i) std::cout << ' ';
|
||||
std::cout << prefix << "B\n"
|
||||
"probing " << std::setw(length) << (sizes[0] / divide) << " assuming -p " << config.probing_multiplier << "\n"
|
||||
"trie " << std::setw(length) << (sizes[1] / divide) << " without quantization\n"
|
||||
"trie " << std::setw(length) << (sizes[2] / divide) << " assuming -q " << (unsigned)config.prob_bits << " -b " << (unsigned)config.backoff_bits << " quantization \n"
|
||||
"trie " << std::setw(length) << (sizes[3] / divide) << " assuming -a " << (unsigned)config.pointer_bhiksha_bits << " array pointer compression\n"
|
||||
"trie " << std::setw(length) << (sizes[4] / divide) << " assuming -a " << (unsigned)config.pointer_bhiksha_bits << " -q " << (unsigned)config.prob_bits << " -b " << (unsigned)config.backoff_bits<< " array pointer compression and quantization\n";
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
try {
|
||||
bool quantize = false, set_backoff_bits = false, bhiksha = false;
|
||||
lm::ngram::Config config;
|
||||
int opt;
|
||||
while ((opt = getopt(argc, argv, "siu:p:t:m:q:b:a:")) != -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;
|
||||
case 'u':
|
||||
config.unknown_missing_logprob = ParseFloat(optarg);
|
||||
break;
|
||||
case 'p':
|
||||
config.probing_multiplier = ParseFloat(optarg);
|
||||
break;
|
||||
case 't':
|
||||
config.temporary_directory_prefix = optarg;
|
||||
break;
|
||||
case 'm':
|
||||
config.building_memory = ParseUInt(optarg) * 1048576;
|
||||
break;
|
||||
case 's':
|
||||
config.sentence_marker_missing = lm::SILENT;
|
||||
break;
|
||||
case 'i':
|
||||
config.positive_log_probability = lm::SILENT;
|
||||
break;
|
||||
default:
|
||||
Usage(argv[0]);
|
||||
}
|
||||
}
|
||||
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);
|
||||
} else if (optind + 2 == argc) {
|
||||
config.write_mmap = argv[optind + 1];
|
||||
if (quantize || set_backoff_bits) ProbingQuantizationUnsupported();
|
||||
ProbingModel(argv[optind], config);
|
||||
} else if (optind + 3 == argc) {
|
||||
const char *model_type = argv[optind];
|
||||
const char *from_file = argv[optind + 1];
|
||||
config.write_mmap = argv[optind + 2];
|
||||
if (!strcmp(model_type, "probing")) {
|
||||
if (quantize || set_backoff_bits) ProbingQuantizationUnsupported();
|
||||
ProbingModel(from_file, config);
|
||||
} else if (!strcmp(model_type, "trie")) {
|
||||
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]);
|
||||
}
|
||||
} else {
|
||||
Usage(argv[0]);
|
||||
}
|
||||
}
|
||||
catch (const std::exception &e) {
|
||||
std::cerr << e.what() << std::endl;
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
27
trunk/kenlm/lm/config.cc
Normal file
27
trunk/kenlm/lm/config.cc
Normal file
@ -0,0 +1,27 @@
|
||||
#include "lm/config.hh"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
namespace lm {
|
||||
namespace ngram {
|
||||
|
||||
Config::Config() :
|
||||
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(NULL),
|
||||
arpa_complain(ALL),
|
||||
write_mmap(NULL),
|
||||
include_vocab(true),
|
||||
prob_bits(8),
|
||||
backoff_bits(8),
|
||||
pointer_bhiksha_bits(22),
|
||||
load_method(util::POPULATE_OR_READ) {}
|
||||
|
||||
} // namespace ngram
|
||||
} // namespace lm
|
98
trunk/kenlm/lm/config.hh
Normal file
98
trunk/kenlm/lm/config.hh
Normal file
@ -0,0 +1,98 @@
|
||||
#ifndef LM_CONFIG__
|
||||
#define LM_CONFIG__
|
||||
|
||||
#include <iosfwd>
|
||||
|
||||
#include "lm/lm_exception.hh"
|
||||
#include "util/mmap.hh"
|
||||
|
||||
/* Configuration for ngram model. Separate header to reduce pollution. */
|
||||
|
||||
namespace lm { namespace ngram {
|
||||
|
||||
class EnumerateVocab;
|
||||
|
||||
struct Config {
|
||||
// EFFECTIVE FOR BOTH ARPA AND BINARY READS
|
||||
|
||||
// Where to log messages including the progress bar. Set to NULL for
|
||||
// silence.
|
||||
std::ostream *messages;
|
||||
|
||||
// This will be called with every string in the vocabulary. See
|
||||
// enumerate_vocab.hh for more detail. Config does not take ownership; you
|
||||
// are still responsible for deleting it (or stack allocating).
|
||||
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 NULL, defaults to write_mmap. If that's NULL,
|
||||
// defaults to input file name.
|
||||
const char *temporary_directory_prefix;
|
||||
|
||||
// Level of complaining to do when loading from ARPA instead of binary format.
|
||||
typedef enum {ALL, EXPENSIVE, NONE} ARPALoadComplain;
|
||||
ARPALoadComplain arpa_complain;
|
||||
|
||||
// While loading an ARPA file, also write out this binary format file. Set
|
||||
// to NULL to disable.
|
||||
const char *write_mmap;
|
||||
|
||||
// Include the vocab in the binary file? Only effective if write_mmap != NULL.
|
||||
bool include_vocab;
|
||||
|
||||
// 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__
|
30
trunk/kenlm/lm/enumerate_vocab.hh
Normal file
30
trunk/kenlm/lm/enumerate_vocab.hh
Normal file
@ -0,0 +1,30 @@
|
||||
#ifndef LM_ENUMERATE_VOCAB__
|
||||
#define LM_ENUMERATE_VOCAB__
|
||||
|
||||
#include "lm/word_index.hh"
|
||||
#include "util/string_piece.hh"
|
||||
|
||||
namespace lm {
|
||||
namespace ngram {
|
||||
|
||||
/* 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 ngram
|
||||
} // namespace lm
|
||||
|
||||
#endif // LM_ENUMERATE_VOCAB__
|
||||
|
64
trunk/kenlm/lm/facade.hh
Normal file
64
trunk/kenlm/lm/facade.hh
Normal file
@ -0,0 +1,64 @@
|
||||
#ifndef LM_FACADE__
|
||||
#define LM_FACADE__
|
||||
|
||||
#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;
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
/* Translate from void* to State */
|
||||
FullScoreReturn FullScore(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));
|
||||
}
|
||||
float Score(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__
|
23
trunk/kenlm/lm/lm_exception.cc
Normal file
23
trunk/kenlm/lm/lm_exception.cc
Normal file
@ -0,0 +1,23 @@
|
||||
#include "lm/lm_exception.hh"
|
||||
|
||||
#include<errno.h>
|
||||
#include<stdio.h>
|
||||
|
||||
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
|
50
trunk/kenlm/lm/lm_exception.hh
Normal file
50
trunk/kenlm/lm/lm_exception.hh
Normal file
@ -0,0 +1,50 @@
|
||||
#ifndef LM_LM_EXCEPTION__
|
||||
#define LM_LM_EXCEPTION__
|
||||
|
||||
// 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
|
14
trunk/kenlm/lm/max_order.hh
Normal file
14
trunk/kenlm/lm/max_order.hh
Normal file
@ -0,0 +1,14 @@
|
||||
#ifndef LM_MAX_ORDER__
|
||||
#define LM_MAX_ORDER__
|
||||
namespace lm {
|
||||
namespace ngram {
|
||||
// If you need higher order, change this and recompile.
|
||||
// Having this limit means that State can be
|
||||
// (kMaxOrder - 1) * sizeof(float) bytes instead of
|
||||
// sizeof(float*) + (kMaxOrder - 1) * sizeof(float) + malloc overhead
|
||||
const unsigned char kMaxOrder = 6;
|
||||
|
||||
} // namespace ngram
|
||||
} // namespace lm
|
||||
|
||||
#endif // LM_MAX_ORDER__
|
237
trunk/kenlm/lm/model.cc
Normal file
237
trunk/kenlm/lm/model.cc
Normal file
@ -0,0 +1,237 @@
|
||||
#include "lm/model.hh"
|
||||
|
||||
#include "lm/blank.hh"
|
||||
#include "lm/lm_exception.hh"
|
||||
#include "lm/search_hashed.hh"
|
||||
#include "lm/search_trie.hh"
|
||||
#include "lm/read_arpa.hh"
|
||||
#include "util/murmur_hash.hh"
|
||||
|
||||
#include <algorithm>
|
||||
#include <functional>
|
||||
#include <numeric>
|
||||
#include <cmath>
|
||||
|
||||
namespace lm {
|
||||
namespace ngram {
|
||||
|
||||
size_t hash_value(const State &state) {
|
||||
return util::MurmurHashNative(state.history_, sizeof(WordIndex) * state.valid_length_);
|
||||
}
|
||||
|
||||
namespace detail {
|
||||
|
||||
template <class Search, class VocabularyT> const ModelType GenericModel<Search, VocabularyT>::kModelType = Search::kModelType;
|
||||
|
||||
template <class Search, class VocabularyT> size_t GenericModel<Search, VocabularyT>::Size(const std::vector<uint64_t> &counts, const Config &config) {
|
||||
return VocabularyT::Size(counts[0], config) + Search::Size(counts, config);
|
||||
}
|
||||
|
||||
template <class Search, class VocabularyT> void GenericModel<Search, VocabularyT>::SetupMemory(void *base, const std::vector<uint64_t> &counts, const Config &config) {
|
||||
uint8_t *start = static_cast<uint8_t*>(base);
|
||||
size_t allocated = VocabularyT::Size(counts[0], config);
|
||||
vocab_.SetupMemory(start, allocated, counts[0], config);
|
||||
start += allocated;
|
||||
start = search_.SetupMemory(start, counts, config);
|
||||
if (static_cast<std::size_t>(start - static_cast<uint8_t*>(base)) != Size(counts, config)) UTIL_THROW(FormatLoadException, "The data structures took " << (start - static_cast<uint8_t*>(base)) << " but Size says they should take " << Size(counts, config));
|
||||
}
|
||||
|
||||
template <class Search, class VocabularyT> GenericModel<Search, VocabularyT>::GenericModel(const char *file, const Config &config) {
|
||||
LoadLM(file, config, *this);
|
||||
|
||||
// g++ prints warnings unless these are fully initialized.
|
||||
State begin_sentence = State();
|
||||
begin_sentence.valid_length_ = 1;
|
||||
begin_sentence.history_[0] = vocab_.BeginSentence();
|
||||
begin_sentence.backoff_[0] = search_.unigram.Lookup(begin_sentence.history_[0]).backoff;
|
||||
State null_context = State();
|
||||
null_context.valid_length_ = 0;
|
||||
P::Init(begin_sentence, null_context, vocab_, search_.MiddleEnd() - search_.MiddleBegin() + 2);
|
||||
}
|
||||
|
||||
template <class Search, class VocabularyT> void GenericModel<Search, VocabularyT>::InitializeFromBinary(void *start, const Parameters ¶ms, const Config &config, int fd) {
|
||||
SetupMemory(start, params.counts, config);
|
||||
vocab_.LoadedBinary(fd, config.enumerate_vocab);
|
||||
search_.LoadedBinary();
|
||||
}
|
||||
|
||||
template <class Search, class VocabularyT> void GenericModel<Search, VocabularyT>::InitializeFromARPA(const char *file, const Config &config) {
|
||||
// Backing file is the ARPA. Steal it so we can make the backing file the mmap output if any.
|
||||
util::FilePiece f(backing_.file.release(), file, config.messages);
|
||||
std::vector<uint64_t> counts;
|
||||
// File counts do not include pruned trigrams that extend to quadgrams etc. These will be fixed by search_.
|
||||
ReadARPACounts(f, counts);
|
||||
|
||||
if (counts.size() > kMaxOrder) UTIL_THROW(FormatLoadException, "This model has order " << counts.size() << ". Edit lm/max_order.hh, set kMaxOrder to at least this value, and recompile.");
|
||||
if (counts.size() < 2) UTIL_THROW(FormatLoadException, "This ngram implementation assumes at least a bigram model.");
|
||||
if (config.probing_multiplier <= 1.0) UTIL_THROW(ConfigException, "probing multiplier must be > 1.0");
|
||||
|
||||
std::size_t vocab_size = VocabularyT::Size(counts[0], config);
|
||||
// Setup the binary file for writing the vocab lookup table. The search_ is responsible for growing the binary file to its needs.
|
||||
vocab_.SetupMemory(SetupJustVocab(config, counts.size(), vocab_size, backing_), vocab_size, counts[0], config);
|
||||
|
||||
if (config.write_mmap) {
|
||||
WriteWordsWrapper wrap(config.enumerate_vocab);
|
||||
vocab_.ConfigureEnumerate(&wrap, counts[0]);
|
||||
search_.InitializeFromARPA(file, f, counts, config, vocab_, backing_);
|
||||
wrap.Write(backing_.file.get());
|
||||
} else {
|
||||
vocab_.ConfigureEnumerate(config.enumerate_vocab, counts[0]);
|
||||
search_.InitializeFromARPA(file, f, counts, config, vocab_, backing_);
|
||||
}
|
||||
|
||||
if (!vocab_.SawUnk()) {
|
||||
assert(config.unknown_missing != THROW_UP);
|
||||
// Default probabilities for unknown.
|
||||
search_.unigram.Unknown().backoff = 0.0;
|
||||
search_.unigram.Unknown().prob = config.unknown_missing_logprob;
|
||||
}
|
||||
FinishFile(config, kModelType, counts, backing_);
|
||||
}
|
||||
|
||||
template <class Search, class VocabularyT> FullScoreReturn GenericModel<Search, VocabularyT>::FullScore(const State &in_state, const WordIndex new_word, State &out_state) const {
|
||||
FullScoreReturn ret = ScoreExceptBackoff(in_state.history_, in_state.history_ + in_state.valid_length_, new_word, out_state);
|
||||
if (ret.ngram_length - 1 < in_state.valid_length_) {
|
||||
ret.prob = std::accumulate(in_state.backoff_ + ret.ngram_length - 1, in_state.backoff_ + in_state.valid_length_, ret.prob);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
template <class Search, class VocabularyT> FullScoreReturn GenericModel<Search, VocabularyT>::FullScoreForgotState(const WordIndex *context_rbegin, const WordIndex *context_rend, const WordIndex new_word, State &out_state) const {
|
||||
context_rend = std::min(context_rend, context_rbegin + P::Order() - 1);
|
||||
FullScoreReturn ret = ScoreExceptBackoff(context_rbegin, context_rend, new_word, out_state);
|
||||
|
||||
// Add the backoff weights for n-grams of order start to (context_rend - context_rbegin).
|
||||
unsigned char start = ret.ngram_length;
|
||||
if (context_rend - context_rbegin < static_cast<std::ptrdiff_t>(start)) return ret;
|
||||
if (start <= 1) {
|
||||
ret.prob += search_.unigram.Lookup(*context_rbegin).backoff;
|
||||
start = 2;
|
||||
}
|
||||
typename Search::Node node;
|
||||
if (!search_.FastMakeNode(context_rbegin, context_rbegin + start - 1, node)) {
|
||||
return ret;
|
||||
}
|
||||
float backoff;
|
||||
// i is the order of the backoff we're looking for.
|
||||
const Middle *mid_iter = search_.MiddleBegin() + start - 2;
|
||||
for (const WordIndex *i = context_rbegin + start - 1; i < context_rend; ++i, ++mid_iter) {
|
||||
if (!search_.LookupMiddleNoProb(*mid_iter, *i, backoff, node)) break;
|
||||
ret.prob += backoff;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
template <class Search, class VocabularyT> void GenericModel<Search, VocabularyT>::GetState(const WordIndex *context_rbegin, const WordIndex *context_rend, State &out_state) const {
|
||||
// Generate a state from context.
|
||||
context_rend = std::min(context_rend, context_rbegin + P::Order() - 1);
|
||||
if (context_rend == context_rbegin) {
|
||||
out_state.valid_length_ = 0;
|
||||
return;
|
||||
}
|
||||
float ignored_prob;
|
||||
typename Search::Node node;
|
||||
search_.LookupUnigram(*context_rbegin, ignored_prob, out_state.backoff_[0], node);
|
||||
out_state.valid_length_ = HasExtension(out_state.backoff_[0]) ? 1 : 0;
|
||||
float *backoff_out = out_state.backoff_ + 1;
|
||||
const typename Search::Middle *mid = search_.MiddleBegin();
|
||||
for (const WordIndex *i = context_rbegin + 1; i < context_rend; ++i, ++backoff_out, ++mid) {
|
||||
if (!search_.LookupMiddleNoProb(*mid, *i, *backoff_out, node)) {
|
||||
std::copy(context_rbegin, context_rbegin + out_state.valid_length_, out_state.history_);
|
||||
return;
|
||||
}
|
||||
if (HasExtension(*backoff_out)) out_state.valid_length_ = i - context_rbegin + 1;
|
||||
}
|
||||
std::copy(context_rbegin, context_rbegin + out_state.valid_length_, out_state.history_);
|
||||
}
|
||||
|
||||
namespace {
|
||||
// Do a paraonoid copy of history, assuming new_word has already been copied
|
||||
// (hence the -1). out_state.valid_length_ could be zero so I avoided using
|
||||
// std::copy.
|
||||
void CopyRemainingHistory(const WordIndex *from, State &out_state) {
|
||||
WordIndex *out = out_state.history_ + 1;
|
||||
const WordIndex *in_end = from + static_cast<ptrdiff_t>(out_state.valid_length_) - 1;
|
||||
for (const WordIndex *in = from; in < in_end; ++in, ++out) *out = *in;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
/* Ugly optimized function. Produce a score excluding backoff.
|
||||
* The search goes in increasing order of ngram length.
|
||||
* Context goes backward, so context_begin is the word immediately preceeding
|
||||
* new_word.
|
||||
*/
|
||||
template <class Search, class VocabularyT> FullScoreReturn GenericModel<Search, VocabularyT>::ScoreExceptBackoff(
|
||||
const WordIndex *context_rbegin,
|
||||
const WordIndex *context_rend,
|
||||
const WordIndex new_word,
|
||||
State &out_state) const {
|
||||
FullScoreReturn ret;
|
||||
// ret.ngram_length contains the last known non-blank ngram length.
|
||||
ret.ngram_length = 1;
|
||||
|
||||
typename Search::Node node;
|
||||
float *backoff_out(out_state.backoff_);
|
||||
search_.LookupUnigram(new_word, ret.prob, *backoff_out, node);
|
||||
// This is the length of the context that should be used for continuation.
|
||||
out_state.valid_length_ = HasExtension(*backoff_out) ? 1 : 0;
|
||||
// We'll write the word anyway since it will probably be used and does no harm being there.
|
||||
out_state.history_[0] = new_word;
|
||||
if (context_rbegin == context_rend) return ret;
|
||||
++backoff_out;
|
||||
|
||||
// Ok now we now that the bigram contains known words. Start by looking it up.
|
||||
const WordIndex *hist_iter = context_rbegin;
|
||||
const typename Search::Middle *mid_iter = search_.MiddleBegin();
|
||||
for (; ; ++mid_iter, ++hist_iter, ++backoff_out) {
|
||||
if (hist_iter == context_rend) {
|
||||
// Ran out of history. Typically no backoff, but this could be a blank.
|
||||
CopyRemainingHistory(context_rbegin, out_state);
|
||||
// ret.prob was already set.
|
||||
return ret;
|
||||
}
|
||||
|
||||
if (mid_iter == search_.MiddleEnd()) break;
|
||||
|
||||
float revert = ret.prob;
|
||||
if (!search_.LookupMiddle(*mid_iter, *hist_iter, ret.prob, *backoff_out, node)) {
|
||||
// Didn't find an ngram using hist_iter.
|
||||
CopyRemainingHistory(context_rbegin, out_state);
|
||||
// ret.prob was already set.
|
||||
return ret;
|
||||
}
|
||||
if (ret.prob == kBlankProb) {
|
||||
// It's a blank. Go back to the old probability.
|
||||
ret.prob = revert;
|
||||
} else {
|
||||
ret.ngram_length = hist_iter - context_rbegin + 2;
|
||||
if (HasExtension(*backoff_out)) {
|
||||
out_state.valid_length_ = ret.ngram_length;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// It passed every lookup in search_.middle. All that's left is to check search_.longest.
|
||||
|
||||
if (!search_.LookupLongest(*hist_iter, ret.prob, node)) {
|
||||
// Failed to find a longest n-gram. Fall back to the most recent non-blank.
|
||||
CopyRemainingHistory(context_rbegin, out_state);
|
||||
// ret.prob was already set.
|
||||
return ret;
|
||||
}
|
||||
// It's an P::Order()-gram.
|
||||
CopyRemainingHistory(context_rbegin, out_state);
|
||||
// There is no blank in longest_.
|
||||
ret.ngram_length = P::Order();
|
||||
return ret;
|
||||
}
|
||||
|
||||
template class GenericModel<ProbingHashedSearch, ProbingVocabulary>; // HASH_PROBING
|
||||
template class GenericModel<trie::TrieSearch<DontQuantize, trie::DontBhiksha>, SortedVocabulary>; // TRIE_SORTED
|
||||
template class GenericModel<trie::TrieSearch<DontQuantize, trie::ArrayBhiksha>, SortedVocabulary>;
|
||||
template class GenericModel<trie::TrieSearch<SeparatelyQuantize, trie::DontBhiksha>, SortedVocabulary>; // TRIE_SORTED_QUANT
|
||||
template class GenericModel<trie::TrieSearch<SeparatelyQuantize, trie::ArrayBhiksha>, SortedVocabulary>;
|
||||
|
||||
} // namespace detail
|
||||
} // namespace ngram
|
||||
} // namespace lm
|
166
trunk/kenlm/lm/model.hh
Normal file
166
trunk/kenlm/lm/model.hh
Normal file
@ -0,0 +1,166 @@
|
||||
#ifndef LM_MODEL__
|
||||
#define LM_MODEL__
|
||||
|
||||
#include "lm/bhiksha.hh"
|
||||
#include "lm/binary_format.hh"
|
||||
#include "lm/config.hh"
|
||||
#include "lm/facade.hh"
|
||||
#include "lm/max_order.hh"
|
||||
#include "lm/quantize.hh"
|
||||
#include "lm/search_hashed.hh"
|
||||
#include "lm/search_trie.hh"
|
||||
#include "lm/vocab.hh"
|
||||
#include "lm/weights.hh"
|
||||
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
|
||||
#include <string.h>
|
||||
|
||||
namespace util { class FilePiece; }
|
||||
|
||||
namespace lm {
|
||||
namespace ngram {
|
||||
|
||||
// This is a POD but if you want memcmp to return the same as operator==, call
|
||||
// ZeroRemaining first.
|
||||
class State {
|
||||
public:
|
||||
bool operator==(const State &other) const {
|
||||
if (valid_length_ != other.valid_length_) return false;
|
||||
const WordIndex *end = history_ + valid_length_;
|
||||
for (const WordIndex *first = history_, *second = other.history_;
|
||||
first != end; ++first, ++second) {
|
||||
if (*first != *second) return false;
|
||||
}
|
||||
// If the histories are equal, so are the backoffs.
|
||||
return true;
|
||||
}
|
||||
|
||||
// Three way comparison function.
|
||||
int Compare(const State &other) const {
|
||||
if (valid_length_ == other.valid_length_) {
|
||||
return memcmp(history_, other.history_, valid_length_ * sizeof(WordIndex));
|
||||
}
|
||||
return (valid_length_ < other.valid_length_) ? -1 : 1;
|
||||
}
|
||||
|
||||
// Call this before using raw memcmp.
|
||||
void ZeroRemaining() {
|
||||
for (unsigned char i = valid_length_; i < kMaxOrder - 1; ++i) {
|
||||
history_[i] = 0;
|
||||
backoff_[i] = 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
unsigned char ValidLength() const { return valid_length_; }
|
||||
|
||||
// You shouldn't need to touch anything below this line, but the members are public so FullState will qualify as a POD.
|
||||
// This order minimizes total size of the struct if WordIndex is 64 bit, float is 32 bit, and alignment of 64 bit integers is 64 bit.
|
||||
WordIndex history_[kMaxOrder - 1];
|
||||
float backoff_[kMaxOrder - 1];
|
||||
unsigned char valid_length_;
|
||||
};
|
||||
|
||||
size_t hash_value(const State &state);
|
||||
|
||||
namespace detail {
|
||||
|
||||
// Should return the same results as SRI.
|
||||
// ModelFacade typedefs Vocabulary so we use VocabularyT to avoid naming conflicts.
|
||||
template <class Search, class VocabularyT> class GenericModel : public base::ModelFacade<GenericModel<Search, VocabularyT>, State, VocabularyT> {
|
||||
private:
|
||||
typedef base::ModelFacade<GenericModel<Search, VocabularyT>, State, VocabularyT> P;
|
||||
public:
|
||||
// This is the model type returned by RecognizeBinary.
|
||||
static const ModelType kModelType;
|
||||
|
||||
/* Get the size of memory that will be mapped given ngram counts. This
|
||||
* does not include small non-mapped control structures, such as this class
|
||||
* itself.
|
||||
*/
|
||||
static size_t Size(const std::vector<uint64_t> &counts, const Config &config = Config());
|
||||
|
||||
/* Load the model from a file. It may be an ARPA or binary file. Binary
|
||||
* files must have the format expected by this class or you'll get an
|
||||
* exception. So TrieModel can only load ARPA or binary created by
|
||||
* TrieModel. To classify binary files, call RecognizeBinary in
|
||||
* lm/binary_format.hh.
|
||||
*/
|
||||
GenericModel(const char *file, const Config &config = Config());
|
||||
|
||||
/* Score p(new_word | in_state) and incorporate new_word into out_state.
|
||||
* Note that in_state and out_state must be different references:
|
||||
* &in_state != &out_state.
|
||||
*/
|
||||
FullScoreReturn FullScore(const State &in_state, const WordIndex new_word, State &out_state) const;
|
||||
|
||||
/* Slower call without in_state. Try to remember state, but sometimes it
|
||||
* would cost too much memory or your decoder isn't setup properly.
|
||||
* To use this function, make an array of WordIndex containing the context
|
||||
* vocabulary ids in reverse order. Then, pass the bounds of the array:
|
||||
* [context_rbegin, context_rend). The new_word is not part of the context
|
||||
* array unless you intend to repeat words.
|
||||
*/
|
||||
FullScoreReturn FullScoreForgotState(const WordIndex *context_rbegin, const WordIndex *context_rend, const WordIndex new_word, State &out_state) const;
|
||||
|
||||
/* Get the state for a context. Don't use this if you can avoid it. Use
|
||||
* BeginSentenceState or EmptyContextState and extend from those. If
|
||||
* you're only going to use this state to call FullScore once, use
|
||||
* FullScoreForgotState.
|
||||
* To use this function, make an array of WordIndex containing the context
|
||||
* vocabulary ids in reverse order. Then, pass the bounds of the array:
|
||||
* [context_rbegin, context_rend).
|
||||
*/
|
||||
void GetState(const WordIndex *context_rbegin, const WordIndex *context_rend, State &out_state) const;
|
||||
|
||||
private:
|
||||
friend void LoadLM<>(const char *file, const Config &config, GenericModel<Search, VocabularyT> &to);
|
||||
|
||||
static void UpdateConfigFromBinary(int fd, const std::vector<uint64_t> &counts, Config &config) {
|
||||
AdvanceOrThrow(fd, VocabularyT::Size(counts[0], config));
|
||||
Search::UpdateConfigFromBinary(fd, counts, config);
|
||||
}
|
||||
|
||||
float SlowBackoffLookup(const WordIndex *const context_rbegin, const WordIndex *const context_rend, unsigned char start) const;
|
||||
|
||||
FullScoreReturn ScoreExceptBackoff(const WordIndex *context_rbegin, const WordIndex *context_rend, const WordIndex new_word, State &out_state) const;
|
||||
|
||||
// Appears after Size in the cc file.
|
||||
void SetupMemory(void *start, const std::vector<uint64_t> &counts, const Config &config);
|
||||
|
||||
void InitializeFromBinary(void *start, const Parameters ¶ms, const Config &config, int fd);
|
||||
|
||||
void InitializeFromARPA(const char *file, const Config &config);
|
||||
|
||||
Backing &MutableBacking() { return backing_; }
|
||||
|
||||
Backing backing_;
|
||||
|
||||
VocabularyT vocab_;
|
||||
|
||||
typedef typename Search::Middle Middle;
|
||||
|
||||
Search search_;
|
||||
};
|
||||
|
||||
} // namespace detail
|
||||
|
||||
// These must also be instantiated in the cc file.
|
||||
typedef ::lm::ngram::ProbingVocabulary Vocabulary;
|
||||
typedef detail::GenericModel<detail::ProbingHashedSearch, Vocabulary> ProbingModel; // HASH_PROBING
|
||||
// Default implementation. No real reason for it to be the default.
|
||||
typedef ProbingModel Model;
|
||||
|
||||
// Smaller implementation.
|
||||
typedef ::lm::ngram::SortedVocabulary SortedVocabulary;
|
||||
typedef detail::GenericModel<trie::TrieSearch<DontQuantize, trie::DontBhiksha>, SortedVocabulary> TrieModel; // TRIE_SORTED
|
||||
typedef detail::GenericModel<trie::TrieSearch<DontQuantize, trie::ArrayBhiksha>, SortedVocabulary> ArrayTrieModel;
|
||||
|
||||
typedef detail::GenericModel<trie::TrieSearch<SeparatelyQuantize, trie::DontBhiksha>, SortedVocabulary> QuantTrieModel; // QUANT_TRIE_SORTED
|
||||
typedef detail::GenericModel<trie::TrieSearch<SeparatelyQuantize, trie::ArrayBhiksha>, SortedVocabulary> QuantArrayTrieModel;
|
||||
|
||||
} // namespace ngram
|
||||
} // namespace lm
|
||||
|
||||
#endif // LM_MODEL__
|
302
trunk/kenlm/lm/model_test.cc
Normal file
302
trunk/kenlm/lm/model_test.cc
Normal file
@ -0,0 +1,302 @@
|
||||
#include "lm/model.hh"
|
||||
|
||||
#include <stdlib.h>
|
||||
|
||||
#define BOOST_TEST_MODULE ModelTest
|
||||
#include <boost/test/unit_test.hpp>
|
||||
#include <boost/test/floating_point_comparison.hpp>
|
||||
|
||||
namespace lm {
|
||||
namespace ngram {
|
||||
|
||||
std::ostream &operator<<(std::ostream &o, const State &state) {
|
||||
o << "State length " << static_cast<unsigned int>(state.valid_length_) << ':';
|
||||
for (const WordIndex *i = state.history_; i < state.history_ + state.valid_length_; ++i) {
|
||||
o << ' ' << *i;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
#define StartTest(word, ngram, score) \
|
||||
ret = model.FullScore( \
|
||||
state, \
|
||||
model.GetVocabulary().Index(word), \
|
||||
out);\
|
||||
BOOST_CHECK_CLOSE(score, ret.prob, 0.001); \
|
||||
BOOST_CHECK_EQUAL(static_cast<unsigned int>(ngram), ret.ngram_length); \
|
||||
BOOST_CHECK_GE(std::min<unsigned char>(ngram, 5 - 1), out.valid_length_); \
|
||||
{\
|
||||
WordIndex context[state.valid_length_ + 1]; \
|
||||
context[0] = model.GetVocabulary().Index(word); \
|
||||
std::copy(state.history_, state.history_ + state.valid_length_, context + 1); \
|
||||
State get_state; \
|
||||
model.GetState(context, context + state.valid_length_ + 1, get_state); \
|
||||
BOOST_CHECK_EQUAL(out, get_state); \
|
||||
}
|
||||
|
||||
#define AppendTest(word, ngram, score) \
|
||||
StartTest(word, ngram, score) \
|
||||
state = out;
|
||||
|
||||
template <class M> void Starters(const M &model) {
|
||||
FullScoreReturn ret;
|
||||
Model::State state(model.BeginSentenceState());
|
||||
Model::State out;
|
||||
|
||||
StartTest("looking", 2, -0.4846522);
|
||||
|
||||
// , probability plus <s> backoff
|
||||
StartTest(",", 1, -1.383514 + -0.4149733);
|
||||
// <unk> probability plus <s> backoff
|
||||
StartTest("this_is_not_found", 1, -1.995635 + -0.4149733);
|
||||
}
|
||||
|
||||
template <class M> void Continuation(const M &model) {
|
||||
FullScoreReturn ret;
|
||||
Model::State state(model.BeginSentenceState());
|
||||
Model::State out;
|
||||
|
||||
AppendTest("looking", 2, -0.484652);
|
||||
AppendTest("on", 3, -0.348837);
|
||||
AppendTest("a", 4, -0.0155266);
|
||||
AppendTest("little", 5, -0.00306122);
|
||||
State preserve = state;
|
||||
AppendTest("the", 1, -4.04005);
|
||||
AppendTest("biarritz", 1, -1.9889);
|
||||
AppendTest("not_found", 1, -2.29666);
|
||||
AppendTest("more", 1, -1.20632 - 20.0);
|
||||
AppendTest(".", 2, -0.51363);
|
||||
AppendTest("</s>", 3, -0.0191651);
|
||||
BOOST_CHECK_EQUAL(0, state.valid_length_);
|
||||
|
||||
state = preserve;
|
||||
AppendTest("more", 5, -0.00181395);
|
||||
BOOST_CHECK_EQUAL(4, state.valid_length_);
|
||||
AppendTest("loin", 5, -0.0432557);
|
||||
BOOST_CHECK_EQUAL(1, state.valid_length_);
|
||||
}
|
||||
|
||||
template <class M> void Blanks(const M &model) {
|
||||
FullScoreReturn ret;
|
||||
State state(model.NullContextState());
|
||||
State out;
|
||||
AppendTest("also", 1, -1.687872);
|
||||
AppendTest("would", 2, -2);
|
||||
AppendTest("consider", 3, -3);
|
||||
State preserve = state;
|
||||
AppendTest("higher", 4, -4);
|
||||
AppendTest("looking", 5, -5);
|
||||
BOOST_CHECK_EQUAL(1, state.valid_length_);
|
||||
|
||||
state = preserve;
|
||||
AppendTest("not_found", 1, -1.995635 - 7.0 - 0.30103);
|
||||
|
||||
state = model.NullContextState();
|
||||
// higher looking is a blank.
|
||||
AppendTest("higher", 1, -1.509559);
|
||||
AppendTest("looking", 1, -1.285941 - 0.30103);
|
||||
AppendTest("not_found", 1, -1.995635 - 0.4771212);
|
||||
}
|
||||
|
||||
template <class M> void Unknowns(const M &model) {
|
||||
FullScoreReturn ret;
|
||||
State state(model.NullContextState());
|
||||
State out;
|
||||
|
||||
AppendTest("not_found", 1, -1.995635);
|
||||
State preserve = state;
|
||||
AppendTest("not_found2", 2, -15.0);
|
||||
AppendTest("not_found3", 2, -15.0 - 2.0);
|
||||
|
||||
state = preserve;
|
||||
AppendTest("however", 2, -4);
|
||||
AppendTest("not_found3", 3, -6);
|
||||
}
|
||||
|
||||
template <class M> void MinimalState(const M &model) {
|
||||
FullScoreReturn ret;
|
||||
State state(model.NullContextState());
|
||||
State out;
|
||||
|
||||
AppendTest("baz", 1, -6.535897);
|
||||
BOOST_CHECK_EQUAL(0, state.valid_length_);
|
||||
state = model.NullContextState();
|
||||
AppendTest("foo", 1, -3.141592);
|
||||
BOOST_CHECK_EQUAL(1, state.valid_length_);
|
||||
AppendTest("bar", 2, -6.0);
|
||||
// Has to include the backoff weight.
|
||||
BOOST_CHECK_EQUAL(1, state.valid_length_);
|
||||
AppendTest("bar", 1, -2.718281 + 3.0);
|
||||
BOOST_CHECK_EQUAL(1, state.valid_length_);
|
||||
|
||||
state = model.NullContextState();
|
||||
AppendTest("to", 1, -1.687872);
|
||||
AppendTest("look", 2, -0.2922095);
|
||||
BOOST_CHECK_EQUAL(2, state.valid_length_);
|
||||
AppendTest("good", 3, -7);
|
||||
}
|
||||
|
||||
#define StatelessTest(word, provide, ngram, score) \
|
||||
ret = model.FullScoreForgotState(indices + num_words - word, indices + num_words - word + provide, indices[num_words - word - 1], state); \
|
||||
BOOST_CHECK_CLOSE(score, ret.prob, 0.001); \
|
||||
BOOST_CHECK_EQUAL(static_cast<unsigned int>(ngram), ret.ngram_length); \
|
||||
model.GetState(indices + num_words - word, indices + num_words - word + provide, before); \
|
||||
ret = model.FullScore(before, indices[num_words - word - 1], out); \
|
||||
BOOST_CHECK(state == out); \
|
||||
BOOST_CHECK_CLOSE(score, ret.prob, 0.001); \
|
||||
BOOST_CHECK_EQUAL(static_cast<unsigned int>(ngram), ret.ngram_length);
|
||||
|
||||
template <class M> void Stateless(const M &model) {
|
||||
const char *words[] = {"<s>", "looking", "on", "a", "little", "the", "biarritz", "not_found", "more", ".", "</s>"};
|
||||
const size_t num_words = sizeof(words) / sizeof(const char*);
|
||||
// Silience "array subscript is above array bounds" when extracting end pointer.
|
||||
WordIndex indices[num_words + 1];
|
||||
for (unsigned int i = 0; i < num_words; ++i) {
|
||||
indices[num_words - 1 - i] = model.GetVocabulary().Index(words[i]);
|
||||
}
|
||||
FullScoreReturn ret;
|
||||
State state, out, before;
|
||||
|
||||
ret = model.FullScoreForgotState(indices + num_words - 1, indices + num_words, indices[num_words - 2], state);
|
||||
BOOST_CHECK_CLOSE(-0.484652, ret.prob, 0.001);
|
||||
StatelessTest(1, 1, 2, -0.484652);
|
||||
|
||||
// looking
|
||||
StatelessTest(1, 2, 2, -0.484652);
|
||||
// on
|
||||
AppendTest("on", 3, -0.348837);
|
||||
StatelessTest(2, 3, 3, -0.348837);
|
||||
StatelessTest(2, 2, 3, -0.348837);
|
||||
StatelessTest(2, 1, 2, -0.4638903);
|
||||
// a
|
||||
StatelessTest(3, 4, 4, -0.0155266);
|
||||
// little
|
||||
AppendTest("little", 5, -0.00306122);
|
||||
StatelessTest(4, 5, 5, -0.00306122);
|
||||
// the
|
||||
AppendTest("the", 1, -4.04005);
|
||||
StatelessTest(5, 5, 1, -4.04005);
|
||||
// No context of the.
|
||||
StatelessTest(5, 0, 1, -1.687872);
|
||||
// biarritz
|
||||
StatelessTest(6, 1, 1, -1.9889);
|
||||
// not found
|
||||
StatelessTest(7, 1, 1, -2.29666);
|
||||
StatelessTest(7, 0, 1, -1.995635);
|
||||
|
||||
WordIndex unk[1];
|
||||
unk[0] = 0;
|
||||
model.GetState(unk, unk + 1, state);
|
||||
BOOST_CHECK_EQUAL(1, state.valid_length_);
|
||||
BOOST_CHECK_EQUAL(static_cast<WordIndex>(0), state.history_[0]);
|
||||
}
|
||||
|
||||
template <class M> void Everything(const M &m) {
|
||||
Starters(m);
|
||||
Continuation(m);
|
||||
Blanks(m);
|
||||
Unknowns(m);
|
||||
MinimalState(m);
|
||||
Stateless(m);
|
||||
}
|
||||
|
||||
class ExpectEnumerateVocab : public EnumerateVocab {
|
||||
public:
|
||||
ExpectEnumerateVocab() {}
|
||||
|
||||
void Add(WordIndex index, const StringPiece &str) {
|
||||
BOOST_CHECK_EQUAL(seen.size(), index);
|
||||
seen.push_back(std::string(str.data(), str.length()));
|
||||
}
|
||||
|
||||
void Check(const base::Vocabulary &vocab) {
|
||||
BOOST_CHECK_EQUAL(37ULL, seen.size());
|
||||
BOOST_REQUIRE(!seen.empty());
|
||||
BOOST_CHECK_EQUAL("<unk>", seen[0]);
|
||||
for (WordIndex i = 0; i < seen.size(); ++i) {
|
||||
BOOST_CHECK_EQUAL(i, vocab.Index(seen[i]));
|
||||
}
|
||||
}
|
||||
|
||||
void Clear() {
|
||||
seen.clear();
|
||||
}
|
||||
|
||||
std::vector<std::string> seen;
|
||||
};
|
||||
|
||||
template <class ModelT> void LoadingTest() {
|
||||
Config config;
|
||||
config.arpa_complain = Config::NONE;
|
||||
config.messages = NULL;
|
||||
ExpectEnumerateVocab enumerate;
|
||||
config.enumerate_vocab = &enumerate;
|
||||
config.probing_multiplier = 2.0;
|
||||
ModelT m("test.arpa", config);
|
||||
enumerate.Check(m.GetVocabulary());
|
||||
Everything(m);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(probing) {
|
||||
LoadingTest<Model>();
|
||||
}
|
||||
BOOST_AUTO_TEST_CASE(trie) {
|
||||
LoadingTest<TrieModel>();
|
||||
}
|
||||
BOOST_AUTO_TEST_CASE(quant_trie) {
|
||||
LoadingTest<QuantTrieModel>();
|
||||
}
|
||||
BOOST_AUTO_TEST_CASE(bhiksha_trie) {
|
||||
LoadingTest<ArrayTrieModel>();
|
||||
}
|
||||
BOOST_AUTO_TEST_CASE(quant_bhiksha_trie) {
|
||||
LoadingTest<QuantArrayTrieModel>();
|
||||
}
|
||||
|
||||
template <class ModelT> void BinaryTest() {
|
||||
Config config;
|
||||
config.write_mmap = "test.binary";
|
||||
config.messages = NULL;
|
||||
ExpectEnumerateVocab enumerate;
|
||||
config.enumerate_vocab = &enumerate;
|
||||
|
||||
{
|
||||
ModelT copy_model("test.arpa", config);
|
||||
enumerate.Check(copy_model.GetVocabulary());
|
||||
enumerate.Clear();
|
||||
Everything(copy_model);
|
||||
}
|
||||
|
||||
config.write_mmap = NULL;
|
||||
|
||||
ModelType type;
|
||||
BOOST_REQUIRE(RecognizeBinary("test.binary", type));
|
||||
BOOST_CHECK_EQUAL(ModelT::kModelType, type);
|
||||
|
||||
ModelT binary("test.binary", config);
|
||||
enumerate.Check(binary.GetVocabulary());
|
||||
Everything(binary);
|
||||
unlink("test.binary");
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(write_and_read_probing) {
|
||||
BinaryTest<Model>();
|
||||
}
|
||||
BOOST_AUTO_TEST_CASE(write_and_read_trie) {
|
||||
BinaryTest<TrieModel>();
|
||||
}
|
||||
BOOST_AUTO_TEST_CASE(write_and_read_quant_trie) {
|
||||
BinaryTest<QuantTrieModel>();
|
||||
}
|
||||
BOOST_AUTO_TEST_CASE(write_and_read_array_trie) {
|
||||
BinaryTest<ArrayTrieModel>();
|
||||
}
|
||||
BOOST_AUTO_TEST_CASE(write_and_read_quant_array_trie) {
|
||||
BinaryTest<QuantArrayTrieModel>();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace ngram
|
||||
} // namespace lm
|
122
trunk/kenlm/lm/ngram_query.cc
Normal file
122
trunk/kenlm/lm/ngram_query.cc
Normal file
@ -0,0 +1,122 @@
|
||||
#include "lm/enumerate_vocab.hh"
|
||||
#include "lm/model.hh"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
#include <ctype.h>
|
||||
|
||||
#include <sys/resource.h>
|
||||
#include <sys/time.h>
|
||||
|
||||
float FloatSec(const struct timeval &tv) {
|
||||
return static_cast<float>(tv.tv_sec) + (static_cast<float>(tv.tv_usec) / 1000000000.0);
|
||||
}
|
||||
|
||||
void PrintUsage(const char *message) {
|
||||
struct rusage usage;
|
||||
if (getrusage(RUSAGE_SELF, &usage)) {
|
||||
perror("getrusage");
|
||||
return;
|
||||
}
|
||||
std::cerr << message;
|
||||
std::cerr << "user\t" << FloatSec(usage.ru_utime) << "\nsys\t" << FloatSec(usage.ru_stime) << '\n';
|
||||
|
||||
// Linux doesn't set memory usage :-(.
|
||||
std::ifstream status("/proc/self/status", std::ios::in);
|
||||
std::string line;
|
||||
while (getline(status, line)) {
|
||||
if (!strncmp(line.c_str(), "VmRSS:\t", 7)) {
|
||||
std::cerr << "rss " << (line.c_str() + 7) << '\n';
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <class Model> void Query(const Model &model, bool sentence_context) {
|
||||
PrintUsage("Loading statistics:\n");
|
||||
typename Model::State state, out;
|
||||
lm::FullScoreReturn ret;
|
||||
std::string word;
|
||||
|
||||
while (std::cin) {
|
||||
state = sentence_context ? model.BeginSentenceState() : model.NullContextState();
|
||||
float total = 0.0;
|
||||
bool got = false;
|
||||
unsigned int oov = 0;
|
||||
while (std::cin >> word) {
|
||||
got = true;
|
||||
lm::WordIndex vocab = model.GetVocabulary().Index(word);
|
||||
if (vocab == 0) ++oov;
|
||||
ret = model.FullScore(state, vocab, out);
|
||||
total += ret.prob;
|
||||
std::cout << word << '=' << vocab << ' ' << static_cast<unsigned int>(ret.ngram_length) << ' ' << ret.prob << '\t';
|
||||
state = out;
|
||||
char c;
|
||||
while (true) {
|
||||
c = std::cin.get();
|
||||
if (!std::cin) break;
|
||||
if (c == '\n') break;
|
||||
if (!isspace(c)) {
|
||||
std::cin.unget();
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (c == '\n') break;
|
||||
}
|
||||
if (!got && !std::cin) break;
|
||||
if (sentence_context) {
|
||||
ret = model.FullScore(state, model.GetVocabulary().EndSentence(), out);
|
||||
total += ret.prob;
|
||||
std::cout << "</s>=" << model.GetVocabulary().EndSentence() << ' ' << static_cast<unsigned int>(ret.ngram_length) << ' ' << ret.prob << '\t';
|
||||
}
|
||||
std::cout << "Total: " << total << " OOV: " << oov << '\n';
|
||||
}
|
||||
PrintUsage("After queries:\n");
|
||||
}
|
||||
|
||||
template <class Model> void Query(const char *name) {
|
||||
lm::ngram::Config config;
|
||||
Model model(name, config);
|
||||
Query(model);
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
if (!(argc == 2 || (argc == 3 && !strcmp(argv[2], "null")))) {
|
||||
std::cerr << "Usage: " << argv[0] << " lm_file [null]" << std::endl;
|
||||
std::cerr << "Input is wrapped in <s> and </s> unless null is passed." << std::endl;
|
||||
return 1;
|
||||
}
|
||||
bool sentence_context = (argc == 2);
|
||||
lm::ngram::ModelType model_type;
|
||||
if (lm::ngram::RecognizeBinary(argv[1], model_type)) {
|
||||
switch(model_type) {
|
||||
case lm::ngram::HASH_PROBING:
|
||||
Query<lm::ngram::ProbingModel>(argv[1], sentence_context);
|
||||
break;
|
||||
case lm::ngram::TRIE_SORTED:
|
||||
Query<lm::ngram::TrieModel>(argv[1], sentence_context);
|
||||
break;
|
||||
case lm::ngram::QUANT_TRIE_SORTED:
|
||||
Query<lm::ngram::QuantTrieModel>(argv[1], sentence_context);
|
||||
break;
|
||||
case lm::ngram::ARRAY_TRIE_SORTED:
|
||||
Query<lm::ngram::ArrayTrieModel>(argv[1], sentence_context);
|
||||
break;
|
||||
case lm::ngram::QUANT_ARRAY_TRIE_SORTED:
|
||||
Query<lm::ngram::QuantArrayTrieModel>(argv[1], sentence_context);
|
||||
break;
|
||||
case lm::ngram::HASH_SORTED:
|
||||
default:
|
||||
std::cerr << "Unrecognized kenlm model type " << model_type << std::endl;
|
||||
abort();
|
||||
}
|
||||
} else {
|
||||
Query<lm::ngram::ProbingModel>(argv[1], sentence_context);
|
||||
}
|
||||
|
||||
PrintUsage("Total time including destruction:\n");
|
||||
return 0;
|
||||
}
|
85
trunk/kenlm/lm/quantize.cc
Normal file
85
trunk/kenlm/lm/quantize.cc
Normal file
@ -0,0 +1,85 @@
|
||||
#include "lm/quantize.hh"
|
||||
|
||||
#include "lm/lm_exception.hh"
|
||||
|
||||
#include <algorithm>
|
||||
#include <numeric>
|
||||
|
||||
#include <unistd.h>
|
||||
|
||||
namespace lm {
|
||||
namespace ngram {
|
||||
|
||||
/* Quantize into bins of equal size as described in
|
||||
* M. Federico and N. Bertoldi. 2006. How many bits are needed
|
||||
* to store probabilities for phrase-based translation? In Proc.
|
||||
* of the Workshop on Statistical Machine Translation, pages
|
||||
* 94–101, New York City, June. Association for Computa-
|
||||
* tional Linguistics.
|
||||
*/
|
||||
|
||||
namespace {
|
||||
|
||||
void MakeBins(float *values, float *values_end, float *centers, uint32_t bins) {
|
||||
std::sort(values, values_end);
|
||||
const float *start = values, *finish;
|
||||
for (uint32_t i = 0; i < bins; ++i, ++centers, start = finish) {
|
||||
finish = values + (((values_end - values) * static_cast<uint64_t>(i + 1)) / bins);
|
||||
if (finish == start) {
|
||||
// zero length bucket.
|
||||
*centers = i ? *(centers - 1) : -std::numeric_limits<float>::infinity();
|
||||
} else {
|
||||
*centers = std::accumulate(start, finish, 0.0) / static_cast<float>(finish - start);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const char kSeparatelyQuantizeVersion = 2;
|
||||
|
||||
} // namespace
|
||||
|
||||
void SeparatelyQuantize::UpdateConfigFromBinary(int fd, const std::vector<uint64_t> &/*counts*/, Config &config) {
|
||||
char version;
|
||||
if (read(fd, &version, 1) != 1 || read(fd, &config.prob_bits, 1) != 1 || read(fd, &config.backoff_bits, 1) != 1)
|
||||
UTIL_THROW(util::ErrnoException, "Failed to read header for quantization.");
|
||||
if (version != kSeparatelyQuantizeVersion) UTIL_THROW(FormatLoadException, "This file has quantization version " << (unsigned)version << " but the code expects version " << (unsigned)kSeparatelyQuantizeVersion);
|
||||
AdvanceOrThrow(fd, -3);
|
||||
}
|
||||
|
||||
void SeparatelyQuantize::SetupMemory(void *start, const Config &config) {
|
||||
// Reserve 8 byte header for bit counts.
|
||||
start_ = reinterpret_cast<float*>(static_cast<uint8_t*>(start) + 8);
|
||||
prob_bits_ = config.prob_bits;
|
||||
backoff_bits_ = config.backoff_bits;
|
||||
// We need the reserved values.
|
||||
if (config.prob_bits == 0) UTIL_THROW(ConfigException, "You can't quantize probability to zero");
|
||||
if (config.backoff_bits == 0) UTIL_THROW(ConfigException, "You can't quantize backoff to zero");
|
||||
if (config.prob_bits > 25) UTIL_THROW(ConfigException, "For efficiency reasons, quantizing probability supports at most 25 bits. Currently you have requested " << static_cast<unsigned>(config.prob_bits) << " bits.");
|
||||
if (config.backoff_bits > 25) UTIL_THROW(ConfigException, "For efficiency reasons, quantizing backoff supports at most 25 bits. Currently you have requested " << static_cast<unsigned>(config.backoff_bits) << " bits.");
|
||||
}
|
||||
|
||||
void SeparatelyQuantize::Train(uint8_t order, std::vector<float> &prob, std::vector<float> &backoff) {
|
||||
TrainProb(order, prob);
|
||||
|
||||
// Backoff
|
||||
float *centers = start_ + TableStart(order) + ProbTableLength();
|
||||
*(centers++) = kNoExtensionBackoff;
|
||||
*(centers++) = kExtensionBackoff;
|
||||
MakeBins(&*backoff.begin(), &*backoff.end(), centers, (1ULL << backoff_bits_) - 2);
|
||||
}
|
||||
|
||||
void SeparatelyQuantize::TrainProb(uint8_t order, std::vector<float> &prob) {
|
||||
float *centers = start_ + TableStart(order);
|
||||
*(centers++) = kBlankProb;
|
||||
MakeBins(&*prob.begin(), &*prob.end(), centers, (1ULL << prob_bits_) - 1);
|
||||
}
|
||||
|
||||
void SeparatelyQuantize::FinishedLoading(const Config &config) {
|
||||
uint8_t *actual_base = reinterpret_cast<uint8_t*>(start_) - 8;
|
||||
*(actual_base++) = kSeparatelyQuantizeVersion; // version
|
||||
*(actual_base++) = config.prob_bits;
|
||||
*(actual_base++) = config.backoff_bits;
|
||||
}
|
||||
|
||||
} // namespace ngram
|
||||
} // namespace lm
|
207
trunk/kenlm/lm/quantize.hh
Normal file
207
trunk/kenlm/lm/quantize.hh
Normal file
@ -0,0 +1,207 @@
|
||||
#ifndef LM_QUANTIZE_H__
|
||||
#define LM_QUANTIZE_H__
|
||||
|
||||
#include "lm/binary_format.hh" // for ModelType
|
||||
#include "lm/blank.hh"
|
||||
#include "lm/config.hh"
|
||||
#include "util/bit_packing.hh"
|
||||
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
|
||||
#include <inttypes.h>
|
||||
|
||||
#include <iostream>
|
||||
|
||||
namespace lm {
|
||||
namespace ngram {
|
||||
|
||||
class Config;
|
||||
|
||||
/* Store values directly and don't quantize. */
|
||||
class DontQuantize {
|
||||
public:
|
||||
static const ModelType kModelTypeAdd = static_cast<ModelType>(0);
|
||||
static void UpdateConfigFromBinary(int, const std::vector<uint64_t> &, Config &) {}
|
||||
static std::size_t Size(uint8_t /*order*/, const Config &/*config*/) { return 0; }
|
||||
static uint8_t MiddleBits(const Config &/*config*/) { return 63; }
|
||||
static uint8_t LongestBits(const Config &/*config*/) { return 31; }
|
||||
|
||||
struct Middle {
|
||||
void Write(void *base, uint64_t bit_offset, float prob, float backoff) const {
|
||||
util::WriteNonPositiveFloat31(base, bit_offset, prob);
|
||||
util::WriteFloat32(base, bit_offset + 31, backoff);
|
||||
}
|
||||
void Read(const void *base, uint64_t bit_offset, float &prob, float &backoff) const {
|
||||
prob = util::ReadNonPositiveFloat31(base, bit_offset);
|
||||
backoff = util::ReadFloat32(base, bit_offset + 31);
|
||||
}
|
||||
void ReadBackoff(const void *base, uint64_t bit_offset, float &backoff) const {
|
||||
backoff = util::ReadFloat32(base, bit_offset + 31);
|
||||
}
|
||||
uint8_t TotalBits() const { return 63; }
|
||||
};
|
||||
|
||||
struct Longest {
|
||||
void Write(void *base, uint64_t bit_offset, float prob) const {
|
||||
util::WriteNonPositiveFloat31(base, bit_offset, prob);
|
||||
}
|
||||
void Read(const void *base, uint64_t bit_offset, float &prob) const {
|
||||
prob = util::ReadNonPositiveFloat31(base, bit_offset);
|
||||
}
|
||||
uint8_t TotalBits() const { return 31; }
|
||||
};
|
||||
|
||||
DontQuantize() {}
|
||||
|
||||
void SetupMemory(void * /*start*/, const Config & /*config*/) {}
|
||||
|
||||
static const bool kTrain = false;
|
||||
// These should never be called because kTrain is false.
|
||||
void Train(uint8_t /*order*/, std::vector<float> &/*prob*/, std::vector<float> &/*backoff*/) {}
|
||||
void TrainProb(uint8_t, std::vector<float> &/*prob*/) {}
|
||||
|
||||
void FinishedLoading(const Config &) {}
|
||||
|
||||
Middle Mid(uint8_t /*order*/) const { return Middle(); }
|
||||
Longest Long(uint8_t /*order*/) const { return Longest(); }
|
||||
};
|
||||
|
||||
class SeparatelyQuantize {
|
||||
private:
|
||||
class Bins {
|
||||
public:
|
||||
// Sigh C++ default constructor
|
||||
Bins() {}
|
||||
|
||||
Bins(uint8_t bits, const float *const begin) : begin_(begin), end_(begin_ + (1ULL << bits)), bits_(bits), mask_((1ULL << bits) - 1) {}
|
||||
|
||||
uint64_t EncodeProb(float value) const {
|
||||
return(value == kBlankProb ? kBlankProbQuant : Encode(value, 1));
|
||||
}
|
||||
|
||||
uint64_t EncodeBackoff(float value) const {
|
||||
if (value == 0.0) {
|
||||
return HasExtension(value) ? kExtensionQuant : kNoExtensionQuant;
|
||||
}
|
||||
return Encode(value, 2);
|
||||
}
|
||||
|
||||
float Decode(std::size_t off) const { return begin_[off]; }
|
||||
|
||||
uint8_t Bits() const { return bits_; }
|
||||
|
||||
uint64_t Mask() const { return mask_; }
|
||||
|
||||
private:
|
||||
uint64_t Encode(float value, size_t reserved) const {
|
||||
const float *above = std::lower_bound(begin_ + reserved, end_, value);
|
||||
if (above == begin_ + reserved) return reserved;
|
||||
if (above == end_) return end_ - begin_ - 1;
|
||||
return above - begin_ - (value - *(above - 1) < *above - value);
|
||||
}
|
||||
|
||||
const float *begin_;
|
||||
const float *end_;
|
||||
uint8_t bits_;
|
||||
uint64_t mask_;
|
||||
};
|
||||
|
||||
public:
|
||||
static const ModelType kModelTypeAdd = kQuantAdd;
|
||||
|
||||
static void UpdateConfigFromBinary(int fd, const std::vector<uint64_t> &counts, Config &config);
|
||||
|
||||
static std::size_t Size(uint8_t order, const Config &config) {
|
||||
size_t longest_table = (static_cast<size_t>(1) << static_cast<size_t>(config.prob_bits)) * sizeof(float);
|
||||
size_t middle_table = (static_cast<size_t>(1) << static_cast<size_t>(config.backoff_bits)) * sizeof(float) + longest_table;
|
||||
// unigrams are currently not quantized so no need for a table.
|
||||
return (order - 2) * middle_table + longest_table + /* for the bit counts and alignment padding) */ 8;
|
||||
}
|
||||
|
||||
static uint8_t MiddleBits(const Config &config) { return config.prob_bits + config.backoff_bits; }
|
||||
static uint8_t LongestBits(const Config &config) { return config.prob_bits; }
|
||||
|
||||
class Middle {
|
||||
public:
|
||||
Middle(uint8_t prob_bits, const float *prob_begin, uint8_t backoff_bits, const float *backoff_begin) :
|
||||
total_bits_(prob_bits + backoff_bits), total_mask_((1ULL << total_bits_) - 1), prob_(prob_bits, prob_begin), backoff_(backoff_bits, backoff_begin) {}
|
||||
|
||||
void Write(void *base, uint64_t bit_offset, float prob, float backoff) const {
|
||||
util::WriteInt57(base, bit_offset, total_bits_,
|
||||
(prob_.EncodeProb(prob) << backoff_.Bits()) | backoff_.EncodeBackoff(backoff));
|
||||
}
|
||||
|
||||
void Read(const void *base, uint64_t bit_offset, float &prob, float &backoff) const {
|
||||
uint64_t both = util::ReadInt57(base, bit_offset, total_bits_, total_mask_);
|
||||
prob = prob_.Decode(both >> backoff_.Bits());
|
||||
backoff = backoff_.Decode(both & backoff_.Mask());
|
||||
}
|
||||
|
||||
void ReadBackoff(const void *base, uint64_t bit_offset, float &backoff) const {
|
||||
backoff = backoff_.Decode(util::ReadInt25(base, bit_offset, backoff_.Bits(), backoff_.Mask()));
|
||||
}
|
||||
|
||||
uint8_t TotalBits() const {
|
||||
return total_bits_;
|
||||
}
|
||||
|
||||
private:
|
||||
const uint8_t total_bits_;
|
||||
const uint64_t total_mask_;
|
||||
const Bins prob_;
|
||||
const Bins backoff_;
|
||||
};
|
||||
|
||||
class Longest {
|
||||
public:
|
||||
// Sigh C++ default constructor
|
||||
Longest() {}
|
||||
|
||||
Longest(uint8_t prob_bits, const float *prob_begin) : prob_(prob_bits, prob_begin) {}
|
||||
|
||||
void Write(void *base, uint64_t bit_offset, float prob) const {
|
||||
util::WriteInt25(base, bit_offset, prob_.Bits(), prob_.EncodeProb(prob));
|
||||
}
|
||||
|
||||
void Read(const void *base, uint64_t bit_offset, float &prob) const {
|
||||
prob = prob_.Decode(util::ReadInt25(base, bit_offset, prob_.Bits(), prob_.Mask()));
|
||||
}
|
||||
|
||||
uint8_t TotalBits() const { return prob_.Bits(); }
|
||||
|
||||
private:
|
||||
Bins prob_;
|
||||
};
|
||||
|
||||
SeparatelyQuantize() {}
|
||||
|
||||
void SetupMemory(void *start, const Config &config);
|
||||
|
||||
static const bool kTrain = true;
|
||||
// Assumes kBlankProb is removed from prob and 0.0 is removed from backoff.
|
||||
void Train(uint8_t order, std::vector<float> &prob, std::vector<float> &backoff);
|
||||
// Train just probabilities (for longest order).
|
||||
void TrainProb(uint8_t order, std::vector<float> &prob);
|
||||
|
||||
void FinishedLoading(const Config &config);
|
||||
|
||||
Middle Mid(uint8_t order) const {
|
||||
const float *table = start_ + TableStart(order);
|
||||
return Middle(prob_bits_, table, backoff_bits_, table + ProbTableLength());
|
||||
}
|
||||
|
||||
Longest Long(uint8_t order) const { return Longest(prob_bits_, start_ + TableStart(order)); }
|
||||
|
||||
private:
|
||||
size_t TableStart(uint8_t order) const { return ((1ULL << prob_bits_) + (1ULL << backoff_bits_)) * static_cast<uint64_t>(order - 2); }
|
||||
size_t ProbTableLength() const { return (1ULL << prob_bits_); }
|
||||
|
||||
float *start_;
|
||||
uint8_t prob_bits_, backoff_bits_;
|
||||
};
|
||||
|
||||
} // namespace ngram
|
||||
} // namespace lm
|
||||
|
||||
#endif // LM_QUANTIZE_H__
|
132
trunk/kenlm/lm/read_arpa.cc
Normal file
132
trunk/kenlm/lm/read_arpa.cc
Normal file
@ -0,0 +1,132 @@
|
||||
#include "lm/read_arpa.hh"
|
||||
|
||||
#include "lm/blank.hh"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
#include <ctype.h>
|
||||
#include <string.h>
|
||||
#include <inttypes.h>
|
||||
|
||||
namespace lm {
|
||||
|
||||
// 1 for '\t', '\n', and ' '. This is stricter than isspace.
|
||||
const bool kARPASpaces[256] = {0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
|
||||
|
||||
namespace {
|
||||
|
||||
bool IsEntirelyWhiteSpace(const StringPiece &line) {
|
||||
for (size_t i = 0; i < static_cast<size_t>(line.size()); ++i) {
|
||||
if (!isspace(line.data()[i])) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const char kBinaryMagic[] = "mmap lm http://kheafield.com/code";
|
||||
|
||||
} // namespace
|
||||
|
||||
void ReadARPACounts(util::FilePiece &in, std::vector<uint64_t> &number) {
|
||||
number.clear();
|
||||
StringPiece line;
|
||||
while (IsEntirelyWhiteSpace(line = in.ReadLine())) {}
|
||||
if (line != "\\data\\") {
|
||||
if ((line.size() >= 2) && (line.data()[0] == 0x1f) && (static_cast<unsigned char>(line.data()[1]) == 0x8b)) {
|
||||
UTIL_THROW(FormatLoadException, "Looks like a gzip file. If this is an ARPA file, pipe " << in.FileName() << " through zcat. If this already in binary format, you need to decompress it because mmap doesn't work on top of gzip.");
|
||||
}
|
||||
if (static_cast<size_t>(line.size()) >= strlen(kBinaryMagic) && StringPiece(line.data(), strlen(kBinaryMagic)) == kBinaryMagic)
|
||||
UTIL_THROW(FormatLoadException, "This looks like a binary file but got sent to the ARPA parser. Did you compress the binary file or pass a binary file where only ARPA files are accepted?");
|
||||
UTIL_THROW(FormatLoadException, "first non-empty line was \"" << line << "\" not \\data\\.");
|
||||
}
|
||||
while (!IsEntirelyWhiteSpace(line = in.ReadLine())) {
|
||||
if (line.size() < 6 || strncmp(line.data(), "ngram ", 6)) UTIL_THROW(FormatLoadException, "count line \"" << line << "\"doesn't begin with \"ngram \"");
|
||||
// So strtol doesn't go off the end of line.
|
||||
std::string remaining(line.data() + 6, line.size() - 6);
|
||||
char *end_ptr;
|
||||
unsigned long int length = std::strtol(remaining.c_str(), &end_ptr, 10);
|
||||
if ((end_ptr == remaining.c_str()) || (length - 1 != number.size())) UTIL_THROW(FormatLoadException, "ngram count lengths should be consecutive starting with 1: " << line);
|
||||
if (*end_ptr != '=') UTIL_THROW(FormatLoadException, "Expected = immediately following the first number in the count line " << line);
|
||||
++end_ptr;
|
||||
const char *start = end_ptr;
|
||||
long int count = std::strtol(start, &end_ptr, 10);
|
||||
if (count < 0) UTIL_THROW(FormatLoadException, "Negative n-gram count " << count);
|
||||
if (start == end_ptr) UTIL_THROW(FormatLoadException, "Couldn't parse n-gram count from " << line);
|
||||
number.push_back(count);
|
||||
}
|
||||
}
|
||||
|
||||
void ReadNGramHeader(util::FilePiece &in, unsigned int length) {
|
||||
StringPiece line;
|
||||
while (IsEntirelyWhiteSpace(line = in.ReadLine())) {}
|
||||
std::stringstream expected;
|
||||
expected << '\\' << length << "-grams:";
|
||||
if (line != expected.str()) UTIL_THROW(FormatLoadException, "Was expecting n-gram header " << expected.str() << " but got " << line << " instead");
|
||||
}
|
||||
|
||||
void ReadBackoff(util::FilePiece &in, Prob &/*weights*/) {
|
||||
switch (in.get()) {
|
||||
case '\t':
|
||||
{
|
||||
float got = in.ReadFloat();
|
||||
if (got != 0.0)
|
||||
UTIL_THROW(FormatLoadException, "Non-zero backoff " << got << " provided for an n-gram that should have no backoff");
|
||||
}
|
||||
break;
|
||||
case '\n':
|
||||
break;
|
||||
default:
|
||||
UTIL_THROW(FormatLoadException, "Expected tab or newline for backoff");
|
||||
}
|
||||
}
|
||||
|
||||
void ReadBackoff(util::FilePiece &in, ProbBackoff &weights) {
|
||||
// Always make zero negative.
|
||||
// Negative zero means that no (n+1)-gram has this n-gram as context.
|
||||
// Therefore the hypothesis state can be shorter. Of course, many n-grams
|
||||
// are context for (n+1)-grams. An algorithm in the data structure will go
|
||||
// back and set the backoff to positive zero in these cases.
|
||||
switch (in.get()) {
|
||||
case '\t':
|
||||
weights.backoff = in.ReadFloat();
|
||||
if (weights.backoff == ngram::kExtensionBackoff) weights.backoff = ngram::kNoExtensionBackoff;
|
||||
if ((in.get() != '\n')) UTIL_THROW(FormatLoadException, "Expected newline after backoff");
|
||||
break;
|
||||
case '\n':
|
||||
weights.backoff = ngram::kNoExtensionBackoff;
|
||||
break;
|
||||
default:
|
||||
UTIL_THROW(FormatLoadException, "Expected tab or newline for backoff");
|
||||
}
|
||||
}
|
||||
|
||||
void ReadEnd(util::FilePiece &in) {
|
||||
StringPiece line;
|
||||
do {
|
||||
line = in.ReadLine();
|
||||
} while (IsEntirelyWhiteSpace(line));
|
||||
if (line != "\\end\\") UTIL_THROW(FormatLoadException, "Expected \\end\\ but the ARPA file has " << line);
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
line = in.ReadLine();
|
||||
if (!IsEntirelyWhiteSpace(line)) UTIL_THROW(FormatLoadException, "Trailing line " << line);
|
||||
}
|
||||
} catch (const util::EndOfFileException &e) {}
|
||||
}
|
||||
|
||||
void PositiveProbWarn::Warn(float prob) {
|
||||
switch (action_) {
|
||||
case THROW_UP:
|
||||
UTIL_THROW(FormatLoadException, "Positive log probability " << prob << " in the model. This is a bug in IRSTLM; you can set config.positive_log_probability = SILENT or pass -i to build_binary to substitute 0.0 for the log probability. Error");
|
||||
case COMPLAIN:
|
||||
std::cerr << "There's a positive log probability " << prob << " in the APRA file, probably because of a bug in IRSTLM. This and subsequent entires will be mapepd to 0 log probability." << std::endl;
|
||||
action_ = SILENT;
|
||||
break;
|
||||
case SILENT:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace lm
|
84
trunk/kenlm/lm/read_arpa.hh
Normal file
84
trunk/kenlm/lm/read_arpa.hh
Normal file
@ -0,0 +1,84 @@
|
||||
#ifndef LM_READ_ARPA__
|
||||
#define LM_READ_ARPA__
|
||||
|
||||
#include "lm/lm_exception.hh"
|
||||
#include "lm/word_index.hh"
|
||||
#include "lm/weights.hh"
|
||||
#include "util/file_piece.hh"
|
||||
|
||||
#include <cstddef>
|
||||
#include <iosfwd>
|
||||
#include <vector>
|
||||
|
||||
namespace lm {
|
||||
|
||||
void ReadARPACounts(util::FilePiece &in, std::vector<uint64_t> &number);
|
||||
void ReadNGramHeader(util::FilePiece &in, unsigned int length);
|
||||
|
||||
void ReadBackoff(util::FilePiece &in, Prob &weights);
|
||||
void ReadBackoff(util::FilePiece &in, ProbBackoff &weights);
|
||||
|
||||
void ReadEnd(util::FilePiece &in);
|
||||
|
||||
extern const bool kARPASpaces[256];
|
||||
|
||||
// Positive log probability warning.
|
||||
class PositiveProbWarn {
|
||||
public:
|
||||
PositiveProbWarn() : action_(THROW_UP) {}
|
||||
|
||||
explicit PositiveProbWarn(WarningAction action) : action_(action) {}
|
||||
|
||||
void Warn(float prob);
|
||||
|
||||
private:
|
||||
WarningAction action_;
|
||||
};
|
||||
|
||||
template <class Voc> void Read1Gram(util::FilePiece &f, Voc &vocab, ProbBackoff *unigrams, PositiveProbWarn &warn) {
|
||||
try {
|
||||
float prob = f.ReadFloat();
|
||||
if (prob > 0.0) {
|
||||
warn.Warn(prob);
|
||||
prob = 0.0;
|
||||
}
|
||||
if (f.get() != '\t') UTIL_THROW(FormatLoadException, "Expected tab after probability");
|
||||
ProbBackoff &value = unigrams[vocab.Insert(f.ReadDelimited(kARPASpaces))];
|
||||
value.prob = prob;
|
||||
ReadBackoff(f, value);
|
||||
} catch(util::Exception &e) {
|
||||
e << " in the 1-gram at byte " << f.Offset();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
// Return true if a positive log probability came out.
|
||||
template <class Voc> void Read1Grams(util::FilePiece &f, std::size_t count, Voc &vocab, ProbBackoff *unigrams, PositiveProbWarn &warn) {
|
||||
ReadNGramHeader(f, 1);
|
||||
for (std::size_t i = 0; i < count; ++i) {
|
||||
Read1Gram(f, vocab, unigrams, warn);
|
||||
}
|
||||
vocab.FinishedLoading(unigrams);
|
||||
}
|
||||
|
||||
// Return true if a positive log probability came out.
|
||||
template <class Voc, class Weights> void ReadNGram(util::FilePiece &f, const unsigned char n, const Voc &vocab, WordIndex *const reverse_indices, Weights &weights, PositiveProbWarn &warn) {
|
||||
try {
|
||||
weights.prob = f.ReadFloat();
|
||||
if (weights.prob > 0.0) {
|
||||
warn.Warn(weights.prob);
|
||||
weights.prob = 0.0;
|
||||
}
|
||||
for (WordIndex *vocab_out = reverse_indices + n - 1; vocab_out >= reverse_indices; --vocab_out) {
|
||||
*vocab_out = vocab.Index(f.ReadDelimited(kARPASpaces));
|
||||
}
|
||||
ReadBackoff(f, weights);
|
||||
} catch(util::Exception &e) {
|
||||
e << " in the " << static_cast<unsigned int>(n) << "-gram at byte " << f.Offset();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace lm
|
||||
|
||||
#endif // LM_READ_ARPA__
|
140
trunk/kenlm/lm/search_hashed.cc
Normal file
140
trunk/kenlm/lm/search_hashed.cc
Normal file
@ -0,0 +1,140 @@
|
||||
#include "lm/search_hashed.hh"
|
||||
|
||||
#include "lm/blank.hh"
|
||||
#include "lm/lm_exception.hh"
|
||||
#include "lm/read_arpa.hh"
|
||||
#include "lm/vocab.hh"
|
||||
|
||||
#include "util/file_piece.hh"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace lm {
|
||||
namespace ngram {
|
||||
|
||||
namespace {
|
||||
|
||||
/* These are passed to ReadNGrams so that n-grams with zero backoff that appear as context will still be used in state. */
|
||||
template <class Middle> class ActivateLowerMiddle {
|
||||
public:
|
||||
explicit ActivateLowerMiddle(Middle &middle) : modify_(middle) {}
|
||||
|
||||
void operator()(const WordIndex *vocab_ids, const unsigned int n) {
|
||||
uint64_t hash = static_cast<WordIndex>(vocab_ids[1]);
|
||||
for (const WordIndex *i = vocab_ids + 2; i < vocab_ids + n; ++i) {
|
||||
hash = detail::CombineWordHash(hash, *i);
|
||||
}
|
||||
typename Middle::MutableIterator i;
|
||||
// TODO: somehow get text of n-gram for this error message.
|
||||
if (!modify_.UnsafeMutableFind(hash, i))
|
||||
UTIL_THROW(FormatLoadException, "The context of every " << n << "-gram should appear as a " << (n-1) << "-gram");
|
||||
SetExtension(i->MutableValue().backoff);
|
||||
}
|
||||
|
||||
private:
|
||||
Middle &modify_;
|
||||
};
|
||||
|
||||
class ActivateUnigram {
|
||||
public:
|
||||
explicit ActivateUnigram(ProbBackoff *unigram) : modify_(unigram) {}
|
||||
|
||||
void operator()(const WordIndex *vocab_ids, const unsigned int /*n*/) {
|
||||
// assert(n == 2);
|
||||
SetExtension(modify_[vocab_ids[1]].backoff);
|
||||
}
|
||||
|
||||
private:
|
||||
ProbBackoff *modify_;
|
||||
};
|
||||
|
||||
template <class Voc, class Store, class Middle, class Activate> void ReadNGrams(util::FilePiece &f, const unsigned int n, const size_t count, const Voc &vocab, std::vector<Middle> &middle, Activate activate, Store &store, PositiveProbWarn &warn) {
|
||||
|
||||
ReadNGramHeader(f, n);
|
||||
ProbBackoff blank;
|
||||
blank.prob = kBlankProb;
|
||||
blank.backoff = kBlankBackoff;
|
||||
|
||||
// vocab ids of words in reverse order
|
||||
WordIndex vocab_ids[n];
|
||||
uint64_t keys[n - 1];
|
||||
typename Store::Packing::Value value;
|
||||
typename Middle::ConstIterator found;
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
ReadNGram(f, n, vocab, vocab_ids, value, warn);
|
||||
keys[0] = detail::CombineWordHash(static_cast<uint64_t>(*vocab_ids), vocab_ids[1]);
|
||||
for (unsigned int h = 1; h < n - 1; ++h) {
|
||||
keys[h] = detail::CombineWordHash(keys[h-1], vocab_ids[h+1]);
|
||||
}
|
||||
store.Insert(Store::Packing::Make(keys[n-2], value));
|
||||
// Go back and insert blanks.
|
||||
for (int lower = n - 3; lower >= 0; --lower) {
|
||||
if (middle[lower].Find(keys[lower], found)) break;
|
||||
middle[lower].Insert(Middle::Packing::Make(keys[lower], blank));
|
||||
}
|
||||
activate(vocab_ids, n);
|
||||
}
|
||||
|
||||
store.FinishedInserting();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
namespace detail {
|
||||
|
||||
template <class MiddleT, class LongestT> uint8_t *TemplateHashedSearch<MiddleT, LongestT>::SetupMemory(uint8_t *start, const std::vector<uint64_t> &counts, const Config &config) {
|
||||
std::size_t allocated = Unigram::Size(counts[0]);
|
||||
unigram = Unigram(start, allocated);
|
||||
start += allocated;
|
||||
for (unsigned int n = 2; n < counts.size(); ++n) {
|
||||
allocated = Middle::Size(counts[n - 1], config.probing_multiplier);
|
||||
middle_.push_back(Middle(start, allocated));
|
||||
start += allocated;
|
||||
}
|
||||
allocated = Longest::Size(counts.back(), config.probing_multiplier);
|
||||
longest = Longest(start, allocated);
|
||||
start += allocated;
|
||||
return start;
|
||||
}
|
||||
|
||||
template <class MiddleT, class LongestT> template <class Voc> void TemplateHashedSearch<MiddleT, LongestT>::InitializeFromARPA(const char * /*file*/, util::FilePiece &f, const std::vector<uint64_t> &counts, const Config &config, Voc &vocab, Backing &backing) {
|
||||
// TODO: fix sorted.
|
||||
SetupMemory(GrowForSearch(config, Size(counts, config), backing), counts, config);
|
||||
|
||||
PositiveProbWarn warn(config.positive_log_probability);
|
||||
|
||||
Read1Grams(f, counts[0], vocab, unigram.Raw(), warn);
|
||||
CheckSpecials(config, vocab);
|
||||
|
||||
try {
|
||||
if (counts.size() > 2) {
|
||||
ReadNGrams(f, 2, counts[1], vocab, middle_, ActivateUnigram(unigram.Raw()), middle_[0], warn);
|
||||
}
|
||||
for (unsigned int n = 3; n < counts.size(); ++n) {
|
||||
ReadNGrams(f, n, counts[n-1], vocab, middle_, ActivateLowerMiddle<Middle>(middle_[n-3]), middle_[n-2], warn);
|
||||
}
|
||||
if (counts.size() > 2) {
|
||||
ReadNGrams(f, counts.size(), counts[counts.size() - 1], vocab, middle_, ActivateLowerMiddle<Middle>(middle_.back()), longest, warn);
|
||||
} else {
|
||||
ReadNGrams(f, counts.size(), counts[counts.size() - 1], vocab, middle_, ActivateUnigram(unigram.Raw()), longest, warn);
|
||||
}
|
||||
} catch (util::ProbingSizeException &e) {
|
||||
UTIL_THROW(util::ProbingSizeException, "Avoid pruning n-grams like \"bar baz quux\" when \"foo bar baz quux\" is still in the model. KenLM will work when this pruning happens, but the probing model assumes these events are rare enough that using blank space in the probing hash table will cover all of them. Increase probing_multiplier (-p to build_binary) to add more blank spaces.\n");
|
||||
}
|
||||
ReadEnd(f);
|
||||
}
|
||||
|
||||
template <class MiddleT, class LongestT> void TemplateHashedSearch<MiddleT, LongestT>::LoadedBinary() {
|
||||
unigram.LoadedBinary();
|
||||
for (typename std::vector<Middle>::iterator i = middle_.begin(); i != middle_.end(); ++i) {
|
||||
i->LoadedBinary();
|
||||
}
|
||||
longest.LoadedBinary();
|
||||
}
|
||||
|
||||
template class TemplateHashedSearch<ProbingHashedSearch::Middle, ProbingHashedSearch::Longest>;
|
||||
|
||||
template void TemplateHashedSearch<ProbingHashedSearch::Middle, ProbingHashedSearch::Longest>::InitializeFromARPA(const char *, util::FilePiece &f, const std::vector<uint64_t> &counts, const Config &, ProbingVocabulary &vocab, Backing &backing);
|
||||
|
||||
} // namespace detail
|
||||
} // namespace ngram
|
||||
} // namespace lm
|
147
trunk/kenlm/lm/search_hashed.hh
Normal file
147
trunk/kenlm/lm/search_hashed.hh
Normal file
@ -0,0 +1,147 @@
|
||||
#ifndef LM_SEARCH_HASHED__
|
||||
#define LM_SEARCH_HASHED__
|
||||
|
||||
#include "lm/binary_format.hh"
|
||||
#include "lm/config.hh"
|
||||
#include "lm/read_arpa.hh"
|
||||
#include "lm/weights.hh"
|
||||
|
||||
#include "util/key_value_packing.hh"
|
||||
#include "util/probing_hash_table.hh"
|
||||
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
|
||||
namespace util { class FilePiece; }
|
||||
|
||||
namespace lm {
|
||||
namespace ngram {
|
||||
struct Backing;
|
||||
namespace detail {
|
||||
|
||||
inline uint64_t CombineWordHash(uint64_t current, const WordIndex next) {
|
||||
uint64_t ret = (current * 8978948897894561157ULL) ^ (static_cast<uint64_t>(1 + next) * 17894857484156487943ULL);
|
||||
return ret;
|
||||
}
|
||||
|
||||
struct HashedSearch {
|
||||
typedef uint64_t Node;
|
||||
|
||||
class Unigram {
|
||||
public:
|
||||
Unigram() {}
|
||||
|
||||
Unigram(void *start, std::size_t /*allocated*/) : unigram_(static_cast<ProbBackoff*>(start)) {}
|
||||
|
||||
static std::size_t Size(uint64_t count) {
|
||||
return (count + 1) * sizeof(ProbBackoff); // +1 for hallucinate <unk>
|
||||
}
|
||||
|
||||
const ProbBackoff &Lookup(WordIndex index) const { return unigram_[index]; }
|
||||
|
||||
ProbBackoff &Unknown() { return unigram_[0]; }
|
||||
|
||||
void LoadedBinary() {}
|
||||
|
||||
// For building.
|
||||
ProbBackoff *Raw() { return unigram_; }
|
||||
|
||||
private:
|
||||
ProbBackoff *unigram_;
|
||||
};
|
||||
|
||||
Unigram unigram;
|
||||
|
||||
bool LookupUnigram(WordIndex word, float &prob, float &backoff, Node &next) const {
|
||||
const ProbBackoff &entry = unigram.Lookup(word);
|
||||
prob = entry.prob;
|
||||
backoff = entry.backoff;
|
||||
next = static_cast<Node>(word);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
template <class MiddleT, class LongestT> class TemplateHashedSearch : public HashedSearch {
|
||||
public:
|
||||
typedef MiddleT Middle;
|
||||
|
||||
typedef LongestT Longest;
|
||||
Longest longest;
|
||||
|
||||
// TODO: move probing_multiplier here with next binary file format update.
|
||||
static void UpdateConfigFromBinary(int, const std::vector<uint64_t> &, Config &) {}
|
||||
|
||||
static std::size_t Size(const std::vector<uint64_t> &counts, const Config &config) {
|
||||
std::size_t ret = Unigram::Size(counts[0]);
|
||||
for (unsigned char n = 1; n < counts.size() - 1; ++n) {
|
||||
ret += Middle::Size(counts[n], config.probing_multiplier);
|
||||
}
|
||||
return ret + Longest::Size(counts.back(), config.probing_multiplier);
|
||||
}
|
||||
|
||||
uint8_t *SetupMemory(uint8_t *start, const std::vector<uint64_t> &counts, const Config &config);
|
||||
|
||||
template <class Voc> void InitializeFromARPA(const char *file, util::FilePiece &f, const std::vector<uint64_t> &counts, const Config &config, Voc &vocab, Backing &backing);
|
||||
|
||||
const Middle *MiddleBegin() const { return &*middle_.begin(); }
|
||||
const Middle *MiddleEnd() const { return &*middle_.end(); }
|
||||
|
||||
bool LookupMiddle(const Middle &middle, WordIndex word, float &prob, float &backoff, Node &node) const {
|
||||
node = CombineWordHash(node, word);
|
||||
typename Middle::ConstIterator found;
|
||||
if (!middle.Find(node, found)) return false;
|
||||
prob = found->GetValue().prob;
|
||||
backoff = found->GetValue().backoff;
|
||||
return true;
|
||||
}
|
||||
|
||||
void LoadedBinary();
|
||||
|
||||
bool LookupMiddleNoProb(const Middle &middle, WordIndex word, float &backoff, Node &node) const {
|
||||
node = CombineWordHash(node, word);
|
||||
typename Middle::ConstIterator found;
|
||||
if (!middle.Find(node, found)) return false;
|
||||
backoff = found->GetValue().backoff;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool LookupLongest(WordIndex word, float &prob, Node &node) const {
|
||||
node = CombineWordHash(node, word);
|
||||
typename Longest::ConstIterator found;
|
||||
if (!longest.Find(node, found)) return false;
|
||||
prob = found->GetValue().prob;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Geenrate a node without necessarily checking that it actually exists.
|
||||
// Optionally return false if it's know to not exist.
|
||||
bool FastMakeNode(const WordIndex *begin, const WordIndex *end, Node &node) const {
|
||||
assert(begin != end);
|
||||
node = static_cast<Node>(*begin);
|
||||
for (const WordIndex *i = begin + 1; i < end; ++i) {
|
||||
node = CombineWordHash(node, *i);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<Middle> middle_;
|
||||
};
|
||||
|
||||
// std::identity is an SGI extension :-(
|
||||
struct IdentityHash : public std::unary_function<uint64_t, size_t> {
|
||||
size_t operator()(uint64_t arg) const { return static_cast<size_t>(arg); }
|
||||
};
|
||||
|
||||
struct ProbingHashedSearch : public TemplateHashedSearch<
|
||||
util::ProbingHashTable<util::ByteAlignedPacking<uint64_t, ProbBackoff>, IdentityHash>,
|
||||
util::ProbingHashTable<util::ByteAlignedPacking<uint64_t, Prob>, IdentityHash> > {
|
||||
|
||||
static const ModelType kModelType = HASH_PROBING;
|
||||
};
|
||||
|
||||
} // namespace detail
|
||||
} // namespace ngram
|
||||
} // namespace lm
|
||||
|
||||
#endif // LM_SEARCH_HASHED__
|
985
trunk/kenlm/lm/search_trie.cc
Normal file
985
trunk/kenlm/lm/search_trie.cc
Normal file
@ -0,0 +1,985 @@
|
||||
/* This is where the trie is built. It's on-disk. */
|
||||
#include "lm/search_trie.hh"
|
||||
|
||||
#include "lm/bhiksha.hh"
|
||||
#include "lm/blank.hh"
|
||||
#include "lm/lm_exception.hh"
|
||||
#include "lm/max_order.hh"
|
||||
#include "lm/quantize.hh"
|
||||
#include "lm/read_arpa.hh"
|
||||
#include "lm/trie.hh"
|
||||
#include "lm/vocab.hh"
|
||||
#include "lm/weights.hh"
|
||||
#include "lm/word_index.hh"
|
||||
#include "util/ersatz_progress.hh"
|
||||
#include "util/file_piece.hh"
|
||||
#include "util/have.hh"
|
||||
#include "util/proxy_iterator.hh"
|
||||
#include "util/scoped.hh"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <cstdio>
|
||||
#include <deque>
|
||||
#include <limits>
|
||||
#include <numeric>
|
||||
#include <vector>
|
||||
|
||||
#include <sys/mman.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace lm {
|
||||
namespace ngram {
|
||||
namespace trie {
|
||||
namespace {
|
||||
|
||||
/* An entry is a n-gram with probability. It consists of:
|
||||
* WordIndex[order]
|
||||
* float probability
|
||||
* backoff probability (omitted for highest order n-gram)
|
||||
* These are stored consecutively in memory. We want to sort them.
|
||||
*
|
||||
* The problem is the length depends on order (but all n-grams being compared
|
||||
* have the same order). Allocating each entry on the heap (i.e. std::vector
|
||||
* or std::string) then sorting pointers is the normal solution. But that's
|
||||
* too memory inefficient. A lot of this code is just here to force std::sort
|
||||
* to work with records where length is specified at runtime (and avoid using
|
||||
* Boost for LM code). I could have used qsort, but the point is to also
|
||||
* support __gnu_cxx:parallel_sort which doesn't have a qsort version.
|
||||
*/
|
||||
|
||||
class EntryIterator {
|
||||
public:
|
||||
EntryIterator() {}
|
||||
|
||||
EntryIterator(void *ptr, std::size_t size) : ptr_(static_cast<uint8_t*>(ptr)), size_(size) {}
|
||||
|
||||
bool operator==(const EntryIterator &other) const {
|
||||
return ptr_ == other.ptr_;
|
||||
}
|
||||
bool operator<(const EntryIterator &other) const {
|
||||
return ptr_ < other.ptr_;
|
||||
}
|
||||
EntryIterator &operator+=(std::ptrdiff_t amount) {
|
||||
ptr_ += amount * size_;
|
||||
return *this;
|
||||
}
|
||||
std::ptrdiff_t operator-(const EntryIterator &other) const {
|
||||
return (ptr_ - other.ptr_) / size_;
|
||||
}
|
||||
|
||||
const void *Data() const { return ptr_; }
|
||||
void *Data() { return ptr_; }
|
||||
std::size_t EntrySize() const { return size_; }
|
||||
|
||||
private:
|
||||
uint8_t *ptr_;
|
||||
std::size_t size_;
|
||||
};
|
||||
|
||||
class EntryProxy {
|
||||
public:
|
||||
EntryProxy() {}
|
||||
|
||||
EntryProxy(void *ptr, std::size_t size) : inner_(ptr, size) {}
|
||||
|
||||
operator std::string() const {
|
||||
return std::string(reinterpret_cast<const char*>(inner_.Data()), inner_.EntrySize());
|
||||
}
|
||||
|
||||
EntryProxy &operator=(const EntryProxy &from) {
|
||||
memcpy(inner_.Data(), from.inner_.Data(), inner_.EntrySize());
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntryProxy &operator=(const std::string &from) {
|
||||
memcpy(inner_.Data(), from.data(), inner_.EntrySize());
|
||||
return *this;
|
||||
}
|
||||
|
||||
const WordIndex *Indices() const {
|
||||
return reinterpret_cast<const WordIndex*>(inner_.Data());
|
||||
}
|
||||
|
||||
private:
|
||||
friend class util::ProxyIterator<EntryProxy>;
|
||||
|
||||
typedef std::string value_type;
|
||||
|
||||
typedef EntryIterator InnerIterator;
|
||||
InnerIterator &Inner() { return inner_; }
|
||||
const InnerIterator &Inner() const { return inner_; }
|
||||
InnerIterator inner_;
|
||||
};
|
||||
|
||||
typedef util::ProxyIterator<EntryProxy> NGramIter;
|
||||
|
||||
// Proxy for an entry except there is some extra cruft between the entries. This is used to sort (n-1)-grams using the same memory as the sorted n-grams.
|
||||
class PartialViewProxy {
|
||||
public:
|
||||
PartialViewProxy() : attention_size_(0), inner_() {}
|
||||
|
||||
PartialViewProxy(void *ptr, std::size_t block_size, std::size_t attention_size) : attention_size_(attention_size), inner_(ptr, block_size) {}
|
||||
|
||||
operator std::string() const {
|
||||
return std::string(reinterpret_cast<const char*>(inner_.Data()), attention_size_);
|
||||
}
|
||||
|
||||
PartialViewProxy &operator=(const PartialViewProxy &from) {
|
||||
memcpy(inner_.Data(), from.inner_.Data(), attention_size_);
|
||||
return *this;
|
||||
}
|
||||
|
||||
PartialViewProxy &operator=(const std::string &from) {
|
||||
memcpy(inner_.Data(), from.data(), attention_size_);
|
||||
return *this;
|
||||
}
|
||||
|
||||
const WordIndex *Indices() const {
|
||||
return reinterpret_cast<const WordIndex*>(inner_.Data());
|
||||
}
|
||||
|
||||
private:
|
||||
friend class util::ProxyIterator<PartialViewProxy>;
|
||||
|
||||
typedef std::string value_type;
|
||||
|
||||
const std::size_t attention_size_;
|
||||
|
||||
typedef EntryIterator InnerIterator;
|
||||
InnerIterator &Inner() { return inner_; }
|
||||
const InnerIterator &Inner() const { return inner_; }
|
||||
InnerIterator inner_;
|
||||
};
|
||||
|
||||
typedef util::ProxyIterator<PartialViewProxy> PartialIter;
|
||||
|
||||
template <class Proxy> class CompareRecords : public std::binary_function<const Proxy &, const Proxy &, bool> {
|
||||
public:
|
||||
explicit CompareRecords(unsigned char order) : order_(order) {}
|
||||
|
||||
bool operator()(const Proxy &first, const Proxy &second) const {
|
||||
return Compare(first.Indices(), second.Indices());
|
||||
}
|
||||
bool operator()(const Proxy &first, const std::string &second) const {
|
||||
return Compare(first.Indices(), reinterpret_cast<const WordIndex*>(second.data()));
|
||||
}
|
||||
bool operator()(const std::string &first, const Proxy &second) const {
|
||||
return Compare(reinterpret_cast<const WordIndex*>(first.data()), second.Indices());
|
||||
}
|
||||
bool operator()(const std::string &first, const std::string &second) const {
|
||||
return Compare(reinterpret_cast<const WordIndex*>(first.data()), reinterpret_cast<const WordIndex*>(second.data()));
|
||||
}
|
||||
|
||||
private:
|
||||
bool Compare(const WordIndex *first, const WordIndex *second) const {
|
||||
const WordIndex *end = first + order_;
|
||||
for (; first != end; ++first, ++second) {
|
||||
if (*first < *second) return true;
|
||||
if (*first > *second) return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
unsigned char order_;
|
||||
};
|
||||
|
||||
FILE *OpenOrThrow(const char *name, const char *mode) {
|
||||
FILE *ret = fopen(name, mode);
|
||||
if (!ret) UTIL_THROW(util::ErrnoException, "Could not open " << name << " for " << mode);
|
||||
return ret;
|
||||
}
|
||||
|
||||
void WriteOrThrow(FILE *to, const void *data, size_t size) {
|
||||
assert(size);
|
||||
if (1 != std::fwrite(data, size, 1, to)) UTIL_THROW(util::ErrnoException, "Short write; requested size " << size);
|
||||
}
|
||||
|
||||
void ReadOrThrow(FILE *from, void *data, size_t size) {
|
||||
if (1 != std::fread(data, size, 1, from)) UTIL_THROW(util::ErrnoException, "Short read; requested size " << size);
|
||||
}
|
||||
|
||||
const std::size_t kCopyBufSize = 512;
|
||||
void CopyOrThrow(FILE *from, FILE *to, size_t size) {
|
||||
char buf[std::min<size_t>(size, kCopyBufSize)];
|
||||
for (size_t i = 0; i < size; i += kCopyBufSize) {
|
||||
std::size_t amount = std::min(size - i, kCopyBufSize);
|
||||
ReadOrThrow(from, buf, amount);
|
||||
WriteOrThrow(to, buf, amount);
|
||||
}
|
||||
}
|
||||
|
||||
void CopyRestOrThrow(FILE *from, FILE *to) {
|
||||
char buf[kCopyBufSize];
|
||||
size_t amount;
|
||||
while ((amount = fread(buf, 1, kCopyBufSize, from))) {
|
||||
WriteOrThrow(to, buf, amount);
|
||||
}
|
||||
if (!feof(from)) UTIL_THROW(util::ErrnoException, "Short read");
|
||||
}
|
||||
|
||||
void RemoveOrThrow(const char *name) {
|
||||
if (std::remove(name)) UTIL_THROW(util::ErrnoException, "Could not remove " << name);
|
||||
}
|
||||
|
||||
std::string DiskFlush(const void *mem_begin, const void *mem_end, const std::string &file_prefix, std::size_t batch, unsigned char order, std::size_t weights_size) {
|
||||
const std::size_t entry_size = sizeof(WordIndex) * order + weights_size;
|
||||
const std::size_t prefix_size = sizeof(WordIndex) * (order - 1);
|
||||
std::stringstream assembled;
|
||||
assembled << file_prefix << static_cast<unsigned int>(order) << '_' << batch;
|
||||
std::string ret(assembled.str());
|
||||
util::scoped_FILE out(OpenOrThrow(ret.c_str(), "w"));
|
||||
// Compress entries that being with the same (order-1) words.
|
||||
for (const uint8_t *group_begin = static_cast<const uint8_t*>(mem_begin); group_begin != static_cast<const uint8_t*>(mem_end);) {
|
||||
const uint8_t *group_end;
|
||||
for (group_end = group_begin + entry_size;
|
||||
(group_end != static_cast<const uint8_t*>(mem_end)) && !memcmp(group_begin, group_end, prefix_size);
|
||||
group_end += entry_size) {}
|
||||
WriteOrThrow(out.get(), group_begin, prefix_size);
|
||||
WordIndex group_size = (group_end - group_begin) / entry_size;
|
||||
WriteOrThrow(out.get(), &group_size, sizeof(group_size));
|
||||
for (const uint8_t *i = group_begin; i != group_end; i += entry_size) {
|
||||
WriteOrThrow(out.get(), i + prefix_size, sizeof(WordIndex));
|
||||
WriteOrThrow(out.get(), i + sizeof(WordIndex) * order, weights_size);
|
||||
}
|
||||
group_begin = group_end;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
class SortedFileReader {
|
||||
public:
|
||||
SortedFileReader() : ended_(false) {}
|
||||
|
||||
void Init(const std::string &name, unsigned char order) {
|
||||
file_.reset(OpenOrThrow(name.c_str(), "r"));
|
||||
header_.resize(order - 1);
|
||||
NextHeader();
|
||||
}
|
||||
|
||||
// Preceding words.
|
||||
const WordIndex *Header() const {
|
||||
return &*header_.begin();
|
||||
}
|
||||
const std::vector<WordIndex> &HeaderVector() const { return header_;}
|
||||
|
||||
std::size_t HeaderBytes() const { return header_.size() * sizeof(WordIndex); }
|
||||
|
||||
void NextHeader() {
|
||||
if (1 != fread(&*header_.begin(), HeaderBytes(), 1, file_.get())) {
|
||||
if (feof(file_.get())) {
|
||||
ended_ = true;
|
||||
} else {
|
||||
UTIL_THROW(util::ErrnoException, "Short read of counts");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
WordIndex ReadCount() {
|
||||
WordIndex ret;
|
||||
ReadOrThrow(file_.get(), &ret, sizeof(WordIndex));
|
||||
return ret;
|
||||
}
|
||||
|
||||
WordIndex ReadWord() {
|
||||
WordIndex ret;
|
||||
ReadOrThrow(file_.get(), &ret, sizeof(WordIndex));
|
||||
return ret;
|
||||
}
|
||||
|
||||
template <class Weights> void ReadWeights(Weights &weights) {
|
||||
ReadOrThrow(file_.get(), &weights, sizeof(Weights));
|
||||
}
|
||||
|
||||
bool Ended() const {
|
||||
return ended_;
|
||||
}
|
||||
|
||||
void Rewind() {
|
||||
rewind(file_.get());
|
||||
ended_ = false;
|
||||
NextHeader();
|
||||
}
|
||||
|
||||
FILE *File() { return file_.get(); }
|
||||
|
||||
private:
|
||||
util::scoped_FILE file_;
|
||||
|
||||
std::vector<WordIndex> header_;
|
||||
|
||||
bool ended_;
|
||||
};
|
||||
|
||||
void CopyFullRecord(SortedFileReader &from, FILE *to, std::size_t weights_size) {
|
||||
WriteOrThrow(to, from.Header(), from.HeaderBytes());
|
||||
WordIndex count = from.ReadCount();
|
||||
WriteOrThrow(to, &count, sizeof(WordIndex));
|
||||
|
||||
CopyOrThrow(from.File(), to, (weights_size + sizeof(WordIndex)) * count);
|
||||
}
|
||||
|
||||
void MergeSortedFiles(const std::string &first_name, const std::string &second_name, const std::string &out, std::size_t weights_size, unsigned char order) {
|
||||
SortedFileReader first, second;
|
||||
first.Init(first_name.c_str(), order);
|
||||
RemoveOrThrow(first_name.c_str());
|
||||
second.Init(second_name.c_str(), order);
|
||||
RemoveOrThrow(second_name.c_str());
|
||||
util::scoped_FILE out_file(OpenOrThrow(out.c_str(), "w"));
|
||||
while (!first.Ended() && !second.Ended()) {
|
||||
if (first.HeaderVector() < second.HeaderVector()) {
|
||||
CopyFullRecord(first, out_file.get(), weights_size);
|
||||
first.NextHeader();
|
||||
continue;
|
||||
}
|
||||
if (first.HeaderVector() > second.HeaderVector()) {
|
||||
CopyFullRecord(second, out_file.get(), weights_size);
|
||||
second.NextHeader();
|
||||
continue;
|
||||
}
|
||||
// Merge at the entry level.
|
||||
WriteOrThrow(out_file.get(), first.Header(), first.HeaderBytes());
|
||||
WordIndex first_count = first.ReadCount(), second_count = second.ReadCount();
|
||||
WordIndex total_count = first_count + second_count;
|
||||
WriteOrThrow(out_file.get(), &total_count, sizeof(WordIndex));
|
||||
|
||||
WordIndex first_word = first.ReadWord(), second_word = second.ReadWord();
|
||||
WordIndex first_index = 0, second_index = 0;
|
||||
while (true) {
|
||||
if (first_word < second_word) {
|
||||
WriteOrThrow(out_file.get(), &first_word, sizeof(WordIndex));
|
||||
CopyOrThrow(first.File(), out_file.get(), weights_size);
|
||||
if (++first_index == first_count) break;
|
||||
first_word = first.ReadWord();
|
||||
} else {
|
||||
WriteOrThrow(out_file.get(), &second_word, sizeof(WordIndex));
|
||||
CopyOrThrow(second.File(), out_file.get(), weights_size);
|
||||
if (++second_index == second_count) break;
|
||||
second_word = second.ReadWord();
|
||||
}
|
||||
}
|
||||
if (first_index == first_count) {
|
||||
WriteOrThrow(out_file.get(), &second_word, sizeof(WordIndex));
|
||||
CopyOrThrow(second.File(), out_file.get(), (second_count - second_index) * (weights_size + sizeof(WordIndex)) - sizeof(WordIndex));
|
||||
} else {
|
||||
WriteOrThrow(out_file.get(), &first_word, sizeof(WordIndex));
|
||||
CopyOrThrow(first.File(), out_file.get(), (first_count - first_index) * (weights_size + sizeof(WordIndex)) - sizeof(WordIndex));
|
||||
}
|
||||
first.NextHeader();
|
||||
second.NextHeader();
|
||||
}
|
||||
|
||||
for (SortedFileReader &remaining = first.Ended() ? second : first; !remaining.Ended(); remaining.NextHeader()) {
|
||||
CopyFullRecord(remaining, out_file.get(), weights_size);
|
||||
}
|
||||
}
|
||||
|
||||
const char *kContextSuffix = "_contexts";
|
||||
|
||||
void WriteContextFile(uint8_t *begin, uint8_t *end, const std::string &ngram_file_name, std::size_t entry_size, unsigned char order) {
|
||||
const size_t context_size = sizeof(WordIndex) * (order - 1);
|
||||
// Sort just the contexts using the same memory.
|
||||
PartialIter context_begin(PartialViewProxy(begin + sizeof(WordIndex), entry_size, context_size));
|
||||
PartialIter context_end(PartialViewProxy(end + sizeof(WordIndex), entry_size, context_size));
|
||||
|
||||
std::sort(context_begin, context_end, CompareRecords<PartialViewProxy>(order - 1));
|
||||
|
||||
std::string name(ngram_file_name + kContextSuffix);
|
||||
util::scoped_FILE out(OpenOrThrow(name.c_str(), "w"));
|
||||
|
||||
// Write out to file and uniqueify at the same time. Could have used unique_copy if there was an appropriate OutputIterator.
|
||||
if (context_begin == context_end) return;
|
||||
PartialIter i(context_begin);
|
||||
WriteOrThrow(out.get(), i->Indices(), context_size);
|
||||
const WordIndex *previous = i->Indices();
|
||||
++i;
|
||||
for (; i != context_end; ++i) {
|
||||
if (memcmp(previous, i->Indices(), context_size)) {
|
||||
WriteOrThrow(out.get(), i->Indices(), context_size);
|
||||
previous = i->Indices();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class ContextReader {
|
||||
public:
|
||||
ContextReader() : valid_(false) {}
|
||||
|
||||
ContextReader(const char *name, unsigned char order) {
|
||||
Reset(name, order);
|
||||
}
|
||||
|
||||
void Reset(const char *name, unsigned char order) {
|
||||
file_.reset(OpenOrThrow(name, "r"));
|
||||
length_ = sizeof(WordIndex) * static_cast<size_t>(order);
|
||||
words_.resize(order);
|
||||
valid_ = true;
|
||||
++*this;
|
||||
}
|
||||
|
||||
ContextReader &operator++() {
|
||||
if (1 != fread(&*words_.begin(), length_, 1, file_.get())) {
|
||||
if (!feof(file_.get()))
|
||||
UTIL_THROW(util::ErrnoException, "Short read");
|
||||
valid_ = false;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
const WordIndex *operator*() const { return &*words_.begin(); }
|
||||
|
||||
operator bool() const { return valid_; }
|
||||
|
||||
FILE *GetFile() { return file_.get(); }
|
||||
|
||||
private:
|
||||
util::scoped_FILE file_;
|
||||
|
||||
size_t length_;
|
||||
|
||||
std::vector<WordIndex> words_;
|
||||
|
||||
bool valid_;
|
||||
};
|
||||
|
||||
void MergeContextFiles(const std::string &first_base, const std::string &second_base, const std::string &out_base, unsigned char order) {
|
||||
const size_t context_size = sizeof(WordIndex) * (order - 1);
|
||||
std::string first_name(first_base + kContextSuffix);
|
||||
std::string second_name(second_base + kContextSuffix);
|
||||
ContextReader first(first_name.c_str(), order - 1), second(second_name.c_str(), order - 1);
|
||||
RemoveOrThrow(first_name.c_str());
|
||||
RemoveOrThrow(second_name.c_str());
|
||||
std::string out_name(out_base + kContextSuffix);
|
||||
util::scoped_FILE out(OpenOrThrow(out_name.c_str(), "w"));
|
||||
while (first && second) {
|
||||
for (const WordIndex *f = *first, *s = *second; ; ++f, ++s) {
|
||||
if (f == *first + order - 1) {
|
||||
// Equal.
|
||||
WriteOrThrow(out.get(), *first, context_size);
|
||||
++first;
|
||||
++second;
|
||||
break;
|
||||
}
|
||||
if (*f < *s) {
|
||||
// First lower
|
||||
WriteOrThrow(out.get(), *first, context_size);
|
||||
++first;
|
||||
break;
|
||||
} else if (*f > *s) {
|
||||
WriteOrThrow(out.get(), *second, context_size);
|
||||
++second;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
ContextReader &remaining = first ? first : second;
|
||||
if (!remaining) return;
|
||||
WriteOrThrow(out.get(), *remaining, context_size);
|
||||
CopyRestOrThrow(remaining.GetFile(), out.get());
|
||||
}
|
||||
|
||||
void ConvertToSorted(util::FilePiece &f, const SortedVocabulary &vocab, const std::vector<uint64_t> &counts, util::scoped_memory &mem, const std::string &file_prefix, unsigned char order, PositiveProbWarn &warn) {
|
||||
ReadNGramHeader(f, order);
|
||||
const size_t count = counts[order - 1];
|
||||
// Size of weights. Does it include backoff?
|
||||
const size_t words_size = sizeof(WordIndex) * order;
|
||||
const size_t weights_size = sizeof(float) + ((order == counts.size()) ? 0 : sizeof(float));
|
||||
const size_t entry_size = words_size + weights_size;
|
||||
const size_t batch_size = std::min(count, mem.size() / entry_size);
|
||||
uint8_t *const begin = reinterpret_cast<uint8_t*>(mem.get());
|
||||
std::deque<std::string> files;
|
||||
for (std::size_t batch = 0, done = 0; done < count; ++batch) {
|
||||
uint8_t *out = begin;
|
||||
uint8_t *out_end = out + std::min(count - done, batch_size) * entry_size;
|
||||
if (order == counts.size()) {
|
||||
for (; out != out_end; out += entry_size) {
|
||||
ReadNGram(f, order, vocab, reinterpret_cast<WordIndex*>(out), *reinterpret_cast<Prob*>(out + words_size), warn);
|
||||
}
|
||||
} else {
|
||||
for (; out != out_end; out += entry_size) {
|
||||
ReadNGram(f, order, vocab, reinterpret_cast<WordIndex*>(out), *reinterpret_cast<ProbBackoff*>(out + words_size), warn);
|
||||
}
|
||||
}
|
||||
// Sort full records by full n-gram.
|
||||
EntryProxy proxy_begin(begin, entry_size), proxy_end(out_end, entry_size);
|
||||
// parallel_sort uses too much RAM
|
||||
std::sort(NGramIter(proxy_begin), NGramIter(proxy_end), CompareRecords<EntryProxy>(order));
|
||||
files.push_back(DiskFlush(begin, out_end, file_prefix, batch, order, weights_size));
|
||||
WriteContextFile(begin, out_end, files.back(), entry_size, order);
|
||||
|
||||
done += (out_end - begin) / entry_size;
|
||||
}
|
||||
|
||||
// All individual files created. Merge them.
|
||||
|
||||
std::size_t merge_count = 0;
|
||||
while (files.size() > 1) {
|
||||
std::stringstream assembled;
|
||||
assembled << file_prefix << static_cast<unsigned int>(order) << "_merge_" << (merge_count++);
|
||||
files.push_back(assembled.str());
|
||||
MergeSortedFiles(files[0], files[1], files.back(), weights_size, order);
|
||||
MergeContextFiles(files[0], files[1], files.back(), order);
|
||||
files.pop_front();
|
||||
files.pop_front();
|
||||
}
|
||||
if (!files.empty()) {
|
||||
std::stringstream assembled;
|
||||
assembled << file_prefix << static_cast<unsigned int>(order) << "_merged";
|
||||
std::string merged_name(assembled.str());
|
||||
if (std::rename(files[0].c_str(), merged_name.c_str())) UTIL_THROW(util::ErrnoException, "Could not rename " << files[0].c_str() << " to " << merged_name.c_str());
|
||||
std::string context_name = files[0] + kContextSuffix;
|
||||
merged_name += kContextSuffix;
|
||||
if (std::rename(context_name.c_str(), merged_name.c_str())) UTIL_THROW(util::ErrnoException, "Could not rename " << context_name << " to " << merged_name.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
void ARPAToSortedFiles(const Config &config, util::FilePiece &f, std::vector<uint64_t> &counts, size_t buffer, const std::string &file_prefix, SortedVocabulary &vocab) {
|
||||
PositiveProbWarn warn(config.positive_log_probability);
|
||||
{
|
||||
std::string unigram_name = file_prefix + "unigrams";
|
||||
util::scoped_fd unigram_file;
|
||||
// In case <unk> appears.
|
||||
size_t extra_count = counts[0] + 1;
|
||||
util::scoped_mmap unigram_mmap(util::MapZeroedWrite(unigram_name.c_str(), extra_count * sizeof(ProbBackoff), unigram_file), extra_count * sizeof(ProbBackoff));
|
||||
Read1Grams(f, counts[0], vocab, reinterpret_cast<ProbBackoff*>(unigram_mmap.get()), warn);
|
||||
CheckSpecials(config, vocab);
|
||||
if (!vocab.SawUnk()) ++counts[0];
|
||||
}
|
||||
|
||||
// Only use as much buffer as we need.
|
||||
size_t buffer_use = 0;
|
||||
for (unsigned int order = 2; order < counts.size(); ++order) {
|
||||
buffer_use = std::max<size_t>(buffer_use, static_cast<size_t>((sizeof(WordIndex) * order + 2 * sizeof(float)) * counts[order - 1]));
|
||||
}
|
||||
buffer_use = std::max<size_t>(buffer_use, static_cast<size_t>((sizeof(WordIndex) * counts.size() + sizeof(float)) * counts.back()));
|
||||
buffer = std::min<size_t>(buffer, buffer_use);
|
||||
|
||||
util::scoped_memory mem;
|
||||
mem.reset(malloc(buffer), buffer, util::scoped_memory::MALLOC_ALLOCATED);
|
||||
if (!mem.get()) UTIL_THROW(util::ErrnoException, "malloc failed for sort buffer size " << buffer);
|
||||
|
||||
for (unsigned char order = 2; order <= counts.size(); ++order) {
|
||||
ConvertToSorted(f, vocab, counts, mem, file_prefix, order, warn);
|
||||
}
|
||||
ReadEnd(f);
|
||||
}
|
||||
|
||||
bool HeadMatch(const WordIndex *words, const WordIndex *const words_end, const WordIndex *header) {
|
||||
for (; words != words_end; ++words, ++header) {
|
||||
if (*words != *header) {
|
||||
//assert(*words <= *header);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Phase to count n-grams, including blanks inserted because they were pruned but have extensions
|
||||
class JustCount {
|
||||
public:
|
||||
template <class Middle, class Longest> JustCount(ContextReader * /*contexts*/, UnigramValue * /*unigrams*/, Middle * /*middle*/, Longest &/*longest*/, uint64_t *counts, unsigned char order)
|
||||
: counts_(counts), longest_counts_(counts + order - 1) {}
|
||||
|
||||
void Unigrams(WordIndex begin, WordIndex end) {
|
||||
counts_[0] += end - begin;
|
||||
}
|
||||
|
||||
void MiddleBlank(const unsigned char mid_idx, WordIndex /* idx */) {
|
||||
++counts_[mid_idx + 1];
|
||||
}
|
||||
|
||||
void Middle(const unsigned char mid_idx, const WordIndex * /*before*/, WordIndex /*key*/, const ProbBackoff &/*weights*/) {
|
||||
++counts_[mid_idx + 1];
|
||||
}
|
||||
|
||||
void Longest(WordIndex /*key*/, Prob /*prob*/) {
|
||||
++*longest_counts_;
|
||||
}
|
||||
|
||||
// Unigrams wrote one past.
|
||||
void Cleanup() {
|
||||
--counts_[0];
|
||||
}
|
||||
|
||||
private:
|
||||
uint64_t *const counts_, *const longest_counts_;
|
||||
};
|
||||
|
||||
// Phase to actually write n-grams to the trie.
|
||||
template <class Quant, class Bhiksha> class WriteEntries {
|
||||
public:
|
||||
WriteEntries(ContextReader *contexts, UnigramValue *unigrams, BitPackedMiddle<typename Quant::Middle, Bhiksha> *middle, BitPackedLongest<typename Quant::Longest> &longest, const uint64_t * /*counts*/, unsigned char order) :
|
||||
contexts_(contexts),
|
||||
unigrams_(unigrams),
|
||||
middle_(middle),
|
||||
longest_(longest),
|
||||
bigram_pack_((order == 2) ? static_cast<BitPacked&>(longest_) : static_cast<BitPacked&>(*middle_)) {}
|
||||
|
||||
void Unigrams(WordIndex begin, WordIndex end) {
|
||||
uint64_t next = bigram_pack_.InsertIndex();
|
||||
for (UnigramValue *i = unigrams_ + begin; i < unigrams_ + end; ++i) {
|
||||
i->next = next;
|
||||
}
|
||||
}
|
||||
|
||||
void MiddleBlank(const unsigned char mid_idx, WordIndex key) {
|
||||
middle_[mid_idx].Insert(key, kBlankProb, kBlankBackoff);
|
||||
}
|
||||
|
||||
void Middle(const unsigned char mid_idx, const WordIndex *before, WordIndex key, ProbBackoff weights) {
|
||||
// Order (mid_idx+2).
|
||||
ContextReader &context = contexts_[mid_idx + 1];
|
||||
if (context && !memcmp(before, *context, sizeof(WordIndex) * (mid_idx + 1)) && (*context)[mid_idx + 1] == key) {
|
||||
SetExtension(weights.backoff);
|
||||
++context;
|
||||
}
|
||||
middle_[mid_idx].Insert(key, weights.prob, weights.backoff);
|
||||
}
|
||||
|
||||
void Longest(WordIndex key, Prob prob) {
|
||||
longest_.Insert(key, prob.prob);
|
||||
}
|
||||
|
||||
void Cleanup() {}
|
||||
|
||||
private:
|
||||
ContextReader *contexts_;
|
||||
UnigramValue *const unigrams_;
|
||||
BitPackedMiddle<typename Quant::Middle, Bhiksha> *const middle_;
|
||||
BitPackedLongest<typename Quant::Longest> &longest_;
|
||||
BitPacked &bigram_pack_;
|
||||
};
|
||||
|
||||
template <class Doing> class RecursiveInsert {
|
||||
public:
|
||||
template <class MiddleT, class LongestT> RecursiveInsert(SortedFileReader *inputs, ContextReader *contexts, UnigramValue *unigrams, MiddleT *middle, LongestT &longest, uint64_t *counts, unsigned char order) :
|
||||
doing_(contexts, unigrams, middle, longest, counts, order), inputs_(inputs), inputs_end_(inputs + order - 1), order_minus_2_(order - 2) {
|
||||
}
|
||||
|
||||
// Outer unigram loop.
|
||||
void Apply(std::ostream *progress_out, const char *message, WordIndex unigram_count) {
|
||||
util::ErsatzProgress progress(progress_out, message, unigram_count + 1);
|
||||
for (words_[0] = 0; ; ++words_[0]) {
|
||||
progress.Set(words_[0]);
|
||||
WordIndex min_continue = unigram_count;
|
||||
for (SortedFileReader *other = inputs_; other != inputs_end_; ++other) {
|
||||
if (other->Ended()) continue;
|
||||
min_continue = std::min(min_continue, other->Header()[0]);
|
||||
}
|
||||
// This will write at unigram_count. This is by design so that the next pointers will make sense.
|
||||
doing_.Unigrams(words_[0], min_continue + 1);
|
||||
if (min_continue == unigram_count) break;
|
||||
words_[0] = min_continue;
|
||||
Middle(0);
|
||||
}
|
||||
doing_.Cleanup();
|
||||
}
|
||||
|
||||
private:
|
||||
void Middle(const unsigned char mid_idx) {
|
||||
// (mid_idx + 2)-gram.
|
||||
if (mid_idx == order_minus_2_) {
|
||||
Longest();
|
||||
return;
|
||||
}
|
||||
// Orders [2, order)
|
||||
|
||||
SortedFileReader &reader = inputs_[mid_idx];
|
||||
|
||||
if (reader.Ended() || !HeadMatch(words_, words_ + mid_idx + 1, reader.Header())) {
|
||||
// This order doesn't have a header match, but longer ones might.
|
||||
MiddleAllBlank(mid_idx);
|
||||
return;
|
||||
}
|
||||
|
||||
// There is a header match.
|
||||
WordIndex count = reader.ReadCount();
|
||||
WordIndex current = reader.ReadWord();
|
||||
while (count) {
|
||||
WordIndex min_continue = std::numeric_limits<WordIndex>::max();
|
||||
for (SortedFileReader *other = inputs_ + mid_idx + 1; other < inputs_end_; ++other) {
|
||||
if (!other->Ended() && HeadMatch(words_, words_ + mid_idx + 1, other->Header()))
|
||||
min_continue = std::min(min_continue, other->Header()[mid_idx + 1]);
|
||||
}
|
||||
while (true) {
|
||||
if (current > min_continue) {
|
||||
doing_.MiddleBlank(mid_idx, min_continue);
|
||||
words_[mid_idx + 1] = min_continue;
|
||||
Middle(mid_idx + 1);
|
||||
break;
|
||||
}
|
||||
ProbBackoff weights;
|
||||
reader.ReadWeights(weights);
|
||||
doing_.Middle(mid_idx, words_, current, weights);
|
||||
--count;
|
||||
if (current == min_continue) {
|
||||
words_[mid_idx + 1] = min_continue;
|
||||
Middle(mid_idx + 1);
|
||||
if (count) current = reader.ReadWord();
|
||||
break;
|
||||
}
|
||||
if (!count) break;
|
||||
current = reader.ReadWord();
|
||||
}
|
||||
}
|
||||
// Count is now zero. Finish off remaining blanks.
|
||||
MiddleAllBlank(mid_idx);
|
||||
reader.NextHeader();
|
||||
}
|
||||
|
||||
void MiddleAllBlank(const unsigned char mid_idx) {
|
||||
while (true) {
|
||||
WordIndex min_continue = std::numeric_limits<WordIndex>::max();
|
||||
for (SortedFileReader *other = inputs_ + mid_idx + 1; other < inputs_end_; ++other) {
|
||||
if (!other->Ended() && HeadMatch(words_, words_ + mid_idx + 1, other->Header()))
|
||||
min_continue = std::min(min_continue, other->Header()[mid_idx + 1]);
|
||||
}
|
||||
if (min_continue == std::numeric_limits<WordIndex>::max()) return;
|
||||
doing_.MiddleBlank(mid_idx, min_continue);
|
||||
words_[mid_idx + 1] = min_continue;
|
||||
Middle(mid_idx + 1);
|
||||
}
|
||||
}
|
||||
|
||||
void Longest() {
|
||||
SortedFileReader &reader = *(inputs_end_ - 1);
|
||||
if (reader.Ended() || !HeadMatch(words_, words_ + order_minus_2_ + 1, reader.Header())) return;
|
||||
WordIndex count = reader.ReadCount();
|
||||
for (WordIndex i = 0; i < count; ++i) {
|
||||
WordIndex word = reader.ReadWord();
|
||||
Prob prob;
|
||||
reader.ReadWeights(prob);
|
||||
doing_.Longest(word, prob);
|
||||
}
|
||||
reader.NextHeader();
|
||||
return;
|
||||
}
|
||||
|
||||
Doing doing_;
|
||||
|
||||
SortedFileReader *inputs_;
|
||||
SortedFileReader *inputs_end_;
|
||||
|
||||
WordIndex words_[kMaxOrder];
|
||||
|
||||
const unsigned char order_minus_2_;
|
||||
};
|
||||
|
||||
void SanityCheckCounts(const std::vector<uint64_t> &initial, const std::vector<uint64_t> &fixed) {
|
||||
if (fixed[0] != initial[0]) UTIL_THROW(util::Exception, "Unigram count should be constant but initial is " << initial[0] << " and recounted is " << fixed[0]);
|
||||
if (fixed.back() != initial.back()) UTIL_THROW(util::Exception, "Longest count should be constant but it changed from " << initial.back() << " to " << fixed.back());
|
||||
for (unsigned char i = 0; i < initial.size(); ++i) {
|
||||
if (fixed[i] < initial[i]) UTIL_THROW(util::Exception, "Counts came out lower than expected. This shouldn't happen");
|
||||
}
|
||||
}
|
||||
|
||||
bool IsDirectory(const char *path) {
|
||||
struct stat info;
|
||||
if (0 != stat(path, &info)) return false;
|
||||
return S_ISDIR(info.st_mode);
|
||||
}
|
||||
|
||||
template <class Quant> void TrainQuantizer(uint8_t order, uint64_t count, SortedFileReader &reader, util::ErsatzProgress &progress, Quant &quant) {
|
||||
ProbBackoff weights;
|
||||
std::vector<float> probs, backoffs;
|
||||
probs.reserve(count);
|
||||
backoffs.reserve(count);
|
||||
for (reader.Rewind(); !reader.Ended(); reader.NextHeader()) {
|
||||
uint64_t entries = reader.ReadCount();
|
||||
for (uint64_t c = 0; c < entries; ++c) {
|
||||
reader.ReadWord();
|
||||
reader.ReadWeights(weights);
|
||||
// kBlankProb isn't added yet.
|
||||
probs.push_back(weights.prob);
|
||||
if (weights.backoff != 0.0) backoffs.push_back(weights.backoff);
|
||||
++progress;
|
||||
}
|
||||
}
|
||||
quant.Train(order, probs, backoffs);
|
||||
}
|
||||
|
||||
template <class Quant> void TrainProbQuantizer(uint8_t order, uint64_t count, SortedFileReader &reader, util::ErsatzProgress &progress, Quant &quant) {
|
||||
Prob weights;
|
||||
std::vector<float> probs, backoffs;
|
||||
probs.reserve(count);
|
||||
for (reader.Rewind(); !reader.Ended(); reader.NextHeader()) {
|
||||
uint64_t entries = reader.ReadCount();
|
||||
for (uint64_t c = 0; c < entries; ++c) {
|
||||
reader.ReadWord();
|
||||
reader.ReadWeights(weights);
|
||||
// kBlankProb isn't added yet.
|
||||
probs.push_back(weights.prob);
|
||||
++progress;
|
||||
}
|
||||
}
|
||||
quant.TrainProb(order, probs);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
template <class Quant, class Bhiksha> void BuildTrie(const std::string &file_prefix, std::vector<uint64_t> &counts, const Config &config, TrieSearch<Quant, Bhiksha> &out, Quant &quant, Backing &backing) {
|
||||
std::vector<SortedFileReader> inputs(counts.size() - 1);
|
||||
std::vector<ContextReader> contexts(counts.size() - 1);
|
||||
|
||||
for (unsigned char i = 2; i <= counts.size(); ++i) {
|
||||
std::stringstream assembled;
|
||||
assembled << file_prefix << static_cast<unsigned int>(i) << "_merged";
|
||||
inputs[i-2].Init(assembled.str(), i);
|
||||
RemoveOrThrow(assembled.str().c_str());
|
||||
assembled << kContextSuffix;
|
||||
contexts[i-2].Reset(assembled.str().c_str(), i-1);
|
||||
RemoveOrThrow(assembled.str().c_str());
|
||||
}
|
||||
|
||||
std::vector<uint64_t> fixed_counts(counts.size());
|
||||
{
|
||||
RecursiveInsert<JustCount> counter(&*inputs.begin(), &*contexts.begin(), NULL, out.middle_begin_, out.longest, &*fixed_counts.begin(), counts.size());
|
||||
counter.Apply(config.messages, "Counting n-grams that should not have been pruned", counts[0]);
|
||||
}
|
||||
for (std::vector<SortedFileReader>::const_iterator i = inputs.begin(); i != inputs.end(); ++i) {
|
||||
if (!i->Ended()) UTIL_THROW(FormatLoadException, "There's a bug in the trie implementation: the " << (i - inputs.begin() + 2) << "-gram table did not complete reading");
|
||||
}
|
||||
SanityCheckCounts(counts, fixed_counts);
|
||||
counts = fixed_counts;
|
||||
|
||||
out.SetupMemory(GrowForSearch(config, TrieSearch<Quant, Bhiksha>::Size(fixed_counts, config), backing), fixed_counts, config);
|
||||
|
||||
if (Quant::kTrain) {
|
||||
util::ErsatzProgress progress(config.messages, "Quantizing", std::accumulate(counts.begin() + 1, counts.end(), 0));
|
||||
for (unsigned char i = 2; i < counts.size(); ++i) {
|
||||
TrainQuantizer(i, counts[i-1], inputs[i-2], progress, quant);
|
||||
}
|
||||
TrainProbQuantizer(counts.size(), counts.back(), inputs[counts.size() - 2], progress, quant);
|
||||
quant.FinishedLoading(config);
|
||||
}
|
||||
|
||||
for (unsigned char i = 2; i <= counts.size(); ++i) {
|
||||
inputs[i-2].Rewind();
|
||||
}
|
||||
UnigramValue *unigrams = out.unigram.Raw();
|
||||
// Fill entries except unigram probabilities.
|
||||
{
|
||||
RecursiveInsert<WriteEntries<Quant, Bhiksha> > inserter(&*inputs.begin(), &*contexts.begin(), unigrams, out.middle_begin_, out.longest, &*fixed_counts.begin(), counts.size());
|
||||
inserter.Apply(config.messages, "Building trie", fixed_counts[0]);
|
||||
}
|
||||
|
||||
// Fill unigram probabilities.
|
||||
try {
|
||||
std::string name(file_prefix + "unigrams");
|
||||
util::scoped_FILE file(OpenOrThrow(name.c_str(), "r"));
|
||||
for (WordIndex i = 0; i < counts[0]; ++i) {
|
||||
ReadOrThrow(file.get(), &unigrams[i].weights, sizeof(ProbBackoff));
|
||||
if (contexts[0] && **contexts[0] == i) {
|
||||
SetExtension(unigrams[i].weights.backoff);
|
||||
++contexts[0];
|
||||
}
|
||||
}
|
||||
RemoveOrThrow(name.c_str());
|
||||
} catch (util::Exception &e) {
|
||||
e << " while re-reading unigram probabilities";
|
||||
throw;
|
||||
}
|
||||
|
||||
// Do not disable this error message or else too little state will be returned. Both WriteEntries::Middle and returning state based on found n-grams will need to be fixed to handle this situation.
|
||||
for (unsigned char order = 2; order <= counts.size(); ++order) {
|
||||
const ContextReader &context = contexts[order - 2];
|
||||
if (context) {
|
||||
FormatLoadException e;
|
||||
e << "An " << static_cast<unsigned int>(order) << "-gram has the context (i.e. all but the last word):";
|
||||
for (const WordIndex *i = *context; i != *context + order - 1; ++i) {
|
||||
e << ' ' << *i;
|
||||
}
|
||||
e << " so this context must appear in the model as a " << static_cast<unsigned int>(order - 1) << "-gram but it does not";
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/* Set ending offsets so the last entry will be sized properly */
|
||||
// Last entry for unigrams was already set.
|
||||
if (out.middle_begin_ != out.middle_end_) {
|
||||
for (typename TrieSearch<Quant, Bhiksha>::Middle *i = out.middle_begin_; i != out.middle_end_ - 1; ++i) {
|
||||
i->FinishedLoading((i+1)->InsertIndex(), config);
|
||||
}
|
||||
(out.middle_end_ - 1)->FinishedLoading(out.longest.InsertIndex(), config);
|
||||
}
|
||||
}
|
||||
|
||||
template <class Quant, class Bhiksha> uint8_t *TrieSearch<Quant, Bhiksha>::SetupMemory(uint8_t *start, const std::vector<uint64_t> &counts, const Config &config) {
|
||||
quant_.SetupMemory(start, config);
|
||||
start += Quant::Size(counts.size(), config);
|
||||
unigram.Init(start);
|
||||
start += Unigram::Size(counts[0]);
|
||||
FreeMiddles();
|
||||
middle_begin_ = static_cast<Middle*>(malloc(sizeof(Middle) * (counts.size() - 2)));
|
||||
middle_end_ = middle_begin_ + (counts.size() - 2);
|
||||
std::vector<uint8_t*> middle_starts(counts.size() - 2);
|
||||
for (unsigned char i = 2; i < counts.size(); ++i) {
|
||||
middle_starts[i-2] = start;
|
||||
start += Middle::Size(Quant::MiddleBits(config), counts[i-1], counts[0], counts[i], config);
|
||||
}
|
||||
// Crazy backwards thing so we initialize using pointers to ones that have already been initialized
|
||||
for (unsigned char i = counts.size() - 1; i >= 2; --i) {
|
||||
new (middle_begin_ + i - 2) Middle(
|
||||
middle_starts[i-2],
|
||||
quant_.Mid(i),
|
||||
counts[i-1],
|
||||
counts[0],
|
||||
counts[i],
|
||||
(i == counts.size() - 1) ? static_cast<const BitPacked&>(longest) : static_cast<const BitPacked &>(middle_begin_[i-1]),
|
||||
config);
|
||||
}
|
||||
longest.Init(start, quant_.Long(counts.size()), counts[0]);
|
||||
return start + Longest::Size(Quant::LongestBits(config), counts.back(), counts[0]);
|
||||
}
|
||||
|
||||
template <class Quant, class Bhiksha> void TrieSearch<Quant, Bhiksha>::LoadedBinary() {
|
||||
unigram.LoadedBinary();
|
||||
for (Middle *i = middle_begin_; i != middle_end_; ++i) {
|
||||
i->LoadedBinary();
|
||||
}
|
||||
longest.LoadedBinary();
|
||||
}
|
||||
|
||||
template <class Quant, class Bhiksha> void TrieSearch<Quant, Bhiksha>::InitializeFromARPA(const char *file, util::FilePiece &f, std::vector<uint64_t> &counts, const Config &config, SortedVocabulary &vocab, Backing &backing) {
|
||||
std::string temporary_directory;
|
||||
if (config.temporary_directory_prefix) {
|
||||
temporary_directory = config.temporary_directory_prefix;
|
||||
if (!temporary_directory.empty() && temporary_directory[temporary_directory.size() - 1] != '/' && IsDirectory(temporary_directory.c_str()))
|
||||
temporary_directory += '/';
|
||||
} else if (config.write_mmap) {
|
||||
temporary_directory = config.write_mmap;
|
||||
} else {
|
||||
temporary_directory = file;
|
||||
}
|
||||
// Null on end is kludge to ensure null termination.
|
||||
temporary_directory += "_trie_tmp_XXXXXX";
|
||||
temporary_directory += '\0';
|
||||
if (!mkdtemp(&temporary_directory[0])) {
|
||||
UTIL_THROW(util::ErrnoException, "Failed to make a temporary directory based on the name " << temporary_directory.c_str());
|
||||
}
|
||||
// Chop off null kludge.
|
||||
temporary_directory.resize(strlen(temporary_directory.c_str()));
|
||||
// Add directory delimiter. Assumes a real operating system.
|
||||
temporary_directory += '/';
|
||||
// At least 1MB sorting memory.
|
||||
ARPAToSortedFiles(config, f, counts, std::max<size_t>(config.building_memory, 1048576), temporary_directory.c_str(), vocab);
|
||||
|
||||
BuildTrie(temporary_directory, counts, config, *this, quant_, backing);
|
||||
if (rmdir(temporary_directory.c_str()) && config.messages) {
|
||||
*config.messages << "Failed to delete " << temporary_directory << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
template class TrieSearch<DontQuantize, DontBhiksha>;
|
||||
template class TrieSearch<DontQuantize, ArrayBhiksha>;
|
||||
template class TrieSearch<SeparatelyQuantize, DontBhiksha>;
|
||||
template class TrieSearch<SeparatelyQuantize, ArrayBhiksha>;
|
||||
|
||||
} // namespace trie
|
||||
} // namespace ngram
|
||||
} // namespace lm
|
106
trunk/kenlm/lm/search_trie.hh
Normal file
106
trunk/kenlm/lm/search_trie.hh
Normal file
@ -0,0 +1,106 @@
|
||||
#ifndef LM_SEARCH_TRIE__
|
||||
#define LM_SEARCH_TRIE__
|
||||
|
||||
#include "lm/binary_format.hh"
|
||||
#include "lm/trie.hh"
|
||||
#include "lm/weights.hh"
|
||||
|
||||
#include <assert.h>
|
||||
|
||||
namespace lm {
|
||||
namespace ngram {
|
||||
struct Backing;
|
||||
class SortedVocabulary;
|
||||
namespace trie {
|
||||
|
||||
template <class Quant, class Bhiksha> class TrieSearch;
|
||||
template <class Quant, class Bhiksha> void BuildTrie(const std::string &file_prefix, std::vector<uint64_t> &counts, const Config &config, TrieSearch<Quant, Bhiksha> &out, Quant &quant, Backing &backing);
|
||||
|
||||
template <class Quant, class Bhiksha> class TrieSearch {
|
||||
public:
|
||||
typedef NodeRange Node;
|
||||
|
||||
typedef ::lm::ngram::trie::Unigram Unigram;
|
||||
Unigram unigram;
|
||||
|
||||
typedef trie::BitPackedMiddle<typename Quant::Middle, Bhiksha> Middle;
|
||||
|
||||
typedef trie::BitPackedLongest<typename Quant::Longest> Longest;
|
||||
Longest longest;
|
||||
|
||||
static const ModelType kModelType = static_cast<ModelType>(TRIE_SORTED + Quant::kModelTypeAdd + Bhiksha::kModelTypeAdd);
|
||||
|
||||
static void UpdateConfigFromBinary(int fd, const std::vector<uint64_t> &counts, Config &config) {
|
||||
Quant::UpdateConfigFromBinary(fd, counts, config);
|
||||
AdvanceOrThrow(fd, Quant::Size(counts.size(), config) + Unigram::Size(counts[0]));
|
||||
Bhiksha::UpdateConfigFromBinary(fd, config);
|
||||
}
|
||||
|
||||
static std::size_t Size(const std::vector<uint64_t> &counts, const Config &config) {
|
||||
std::size_t ret = Quant::Size(counts.size(), config) + Unigram::Size(counts[0]);
|
||||
for (unsigned char i = 1; i < counts.size() - 1; ++i) {
|
||||
ret += Middle::Size(Quant::MiddleBits(config), counts[i], counts[0], counts[i+1], config);
|
||||
}
|
||||
return ret + Longest::Size(Quant::LongestBits(config), counts.back(), counts[0]);
|
||||
}
|
||||
|
||||
TrieSearch() : middle_begin_(NULL), middle_end_(NULL) {}
|
||||
|
||||
~TrieSearch() { FreeMiddles(); }
|
||||
|
||||
uint8_t *SetupMemory(uint8_t *start, const std::vector<uint64_t> &counts, const Config &config);
|
||||
|
||||
void LoadedBinary();
|
||||
|
||||
const Middle *MiddleBegin() const { return middle_begin_; }
|
||||
const Middle *MiddleEnd() const { return middle_end_; }
|
||||
|
||||
void InitializeFromARPA(const char *file, util::FilePiece &f, std::vector<uint64_t> &counts, const Config &config, SortedVocabulary &vocab, Backing &backing);
|
||||
|
||||
bool LookupUnigram(WordIndex word, float &prob, float &backoff, Node &node) const {
|
||||
return unigram.Find(word, prob, backoff, node);
|
||||
}
|
||||
|
||||
bool LookupMiddle(const Middle &mid, WordIndex word, float &prob, float &backoff, Node &node) const {
|
||||
return mid.Find(word, prob, backoff, node);
|
||||
}
|
||||
|
||||
bool LookupMiddleNoProb(const Middle &mid, WordIndex word, float &backoff, Node &node) const {
|
||||
return mid.FindNoProb(word, backoff, node);
|
||||
}
|
||||
|
||||
bool LookupLongest(WordIndex word, float &prob, const Node &node) const {
|
||||
return longest.Find(word, prob, node);
|
||||
}
|
||||
|
||||
bool FastMakeNode(const WordIndex *begin, const WordIndex *end, Node &node) const {
|
||||
// TODO: don't decode backoff.
|
||||
assert(begin != end);
|
||||
float ignored_prob, ignored_backoff;
|
||||
LookupUnigram(*begin, ignored_prob, ignored_backoff, node);
|
||||
for (const WordIndex *i = begin + 1; i < end; ++i) {
|
||||
if (!LookupMiddleNoProb(middle_begin_[i - begin - 1], *i, ignored_backoff, node)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
friend void BuildTrie<Quant, Bhiksha>(const std::string &file_prefix, std::vector<uint64_t> &counts, const Config &config, TrieSearch<Quant, Bhiksha> &out, Quant &quant, Backing &backing);
|
||||
|
||||
// Middles are managed manually so we can delay construction and they don't have to be copyable.
|
||||
void FreeMiddles() {
|
||||
for (const Middle *i = middle_begin_; i != middle_end_; ++i) {
|
||||
i->~Middle();
|
||||
}
|
||||
free(middle_begin_);
|
||||
}
|
||||
|
||||
Middle *middle_begin_, *middle_end_;
|
||||
Quant quant_;
|
||||
};
|
||||
|
||||
} // namespace trie
|
||||
} // namespace ngram
|
||||
} // namespace lm
|
||||
|
||||
#endif // LM_SEARCH_TRIE__
|
108
trunk/kenlm/lm/sri.cc
Normal file
108
trunk/kenlm/lm/sri.cc
Normal file
@ -0,0 +1,108 @@
|
||||
#include "lm/lm_exception.hh"
|
||||
#include "lm/sri.hh"
|
||||
|
||||
#include <Ngram.h>
|
||||
#include <Vocab.h>
|
||||
|
||||
#include <errno.h>
|
||||
|
||||
namespace lm {
|
||||
namespace sri {
|
||||
|
||||
Vocabulary::Vocabulary() : sri_(new Vocab) {}
|
||||
|
||||
Vocabulary::~Vocabulary() {}
|
||||
|
||||
WordIndex Vocabulary::Index(const char *str) const {
|
||||
WordIndex ret = sri_->getIndex(str);
|
||||
// NGram wants the index of Vocab_Unknown for unknown words, but for some reason SRI returns Vocab_None here :-(.
|
||||
if (ret == Vocab_None) {
|
||||
return not_found_;
|
||||
} else {
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
||||
const char *Vocabulary::Word(WordIndex index) const {
|
||||
return sri_->getWord(index);
|
||||
}
|
||||
|
||||
void Vocabulary::FinishedLoading() {
|
||||
SetSpecial(
|
||||
sri_->ssIndex(),
|
||||
sri_->seIndex(),
|
||||
sri_->unkIndex());
|
||||
}
|
||||
|
||||
namespace {
|
||||
Ngram *MakeSRIModel(const char *file_name, unsigned int ngram_length, Vocab &sri_vocab) {
|
||||
sri_vocab.unkIsWord() = true;
|
||||
std::auto_ptr<Ngram> ret(new Ngram(sri_vocab, ngram_length));
|
||||
File file(file_name, "r");
|
||||
errno = 0;
|
||||
if (!ret->read(file)) {
|
||||
UTIL_THROW(FormatLoadException, "reading file " << file_name << " with SRI failed.");
|
||||
}
|
||||
return ret.release();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Model::Model(const char *file_name, unsigned int ngram_length) : sri_(MakeSRIModel(file_name, ngram_length, *vocab_.sri_)) {
|
||||
if (!sri_->setorder()) {
|
||||
UTIL_THROW(FormatLoadException, "Can't have an SRI model with order 0.");
|
||||
}
|
||||
vocab_.FinishedLoading();
|
||||
State begin_state = State();
|
||||
begin_state.valid_length_ = 1;
|
||||
if (kMaxOrder > 1) {
|
||||
begin_state.history_[0] = vocab_.BeginSentence();
|
||||
if (kMaxOrder > 2) begin_state.history_[1] = Vocab_None;
|
||||
}
|
||||
State null_state = State();
|
||||
null_state.valid_length_ = 0;
|
||||
if (kMaxOrder > 1) null_state.history_[0] = Vocab_None;
|
||||
Init(begin_state, null_state, vocab_, sri_->setorder());
|
||||
not_found_ = vocab_.NotFound();
|
||||
}
|
||||
|
||||
Model::~Model() {}
|
||||
|
||||
namespace {
|
||||
|
||||
/* Argh SRI's wordProb knows the ngram length but doesn't return it. One more
|
||||
* reason you should use my model. */
|
||||
// TODO(stolcke): fix SRILM so I don't have to do this.
|
||||
unsigned int MatchedLength(Ngram &model, const WordIndex new_word, const SRIVocabIndex *const_history) {
|
||||
unsigned int out_length = 0;
|
||||
// This gets the length of context used, which is ngram_length - 1 unless new_word is OOV in which case it is 0.
|
||||
model.contextID(new_word, const_history, out_length);
|
||||
return out_length + 1;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
FullScoreReturn Model::FullScore(const State &in_state, const WordIndex new_word, State &out_state) const {
|
||||
// If you get a compiler in this function, change SRIVocabIndex in sri.hh to match the one found in SRI's Vocab.h.
|
||||
const SRIVocabIndex *const_history;
|
||||
SRIVocabIndex local_history[Order()];
|
||||
if (in_state.valid_length_ < kMaxOrder - 1) {
|
||||
const_history = in_state.history_;
|
||||
} else {
|
||||
std::copy(in_state.history_, in_state.history_ + in_state.valid_length_, local_history);
|
||||
local_history[in_state.valid_length_] = Vocab_None;
|
||||
const_history = local_history;
|
||||
}
|
||||
FullScoreReturn ret;
|
||||
ret.ngram_length = MatchedLength(*sri_, new_word, const_history);
|
||||
out_state.history_[0] = new_word;
|
||||
out_state.valid_length_ = std::min<unsigned char>(ret.ngram_length, Order() - 1);
|
||||
std::copy(const_history, const_history + out_state.valid_length_ - 1, out_state.history_ + 1);
|
||||
if (out_state.valid_length_ < kMaxOrder - 1) {
|
||||
out_state.history_[out_state.valid_length_] = Vocab_None;
|
||||
}
|
||||
ret.prob = sri_->wordProb(new_word, const_history);
|
||||
return ret;
|
||||
}
|
||||
|
||||
} // namespace sri
|
||||
} // namespace lm
|
102
trunk/kenlm/lm/sri.hh
Normal file
102
trunk/kenlm/lm/sri.hh
Normal file
@ -0,0 +1,102 @@
|
||||
#ifndef LM_SRI__
|
||||
#define LM_SRI__
|
||||
|
||||
#include "lm/facade.hh"
|
||||
#include "util/murmur_hash.hh"
|
||||
|
||||
#include <cmath>
|
||||
#include <exception>
|
||||
#include <memory>
|
||||
|
||||
class Ngram;
|
||||
class Vocab;
|
||||
|
||||
/* The ngram length reported uses some random API I found and may be wrong.
|
||||
*
|
||||
* See ngram, which should return equivalent results.
|
||||
*/
|
||||
|
||||
namespace lm {
|
||||
namespace sri {
|
||||
|
||||
static const unsigned int kMaxOrder = 6;
|
||||
|
||||
/* This should match VocabIndex found in SRI's Vocab.h
|
||||
* The reason I define this here independently is that SRI's headers
|
||||
* pollute and increase compile time.
|
||||
* It's difficult to extract this from their header and anyway would
|
||||
* break packaging.
|
||||
* If these differ there will be a compiler error in ActuallyCall.
|
||||
*/
|
||||
typedef unsigned int SRIVocabIndex;
|
||||
|
||||
class State {
|
||||
public:
|
||||
// You shouldn't need to touch these, but they're public so State will be a POD.
|
||||
// If valid_length_ < kMaxOrder - 1 then history_[valid_length_] == Vocab_None.
|
||||
SRIVocabIndex history_[kMaxOrder - 1];
|
||||
unsigned char valid_length_;
|
||||
};
|
||||
|
||||
inline bool operator==(const State &left, const State &right) {
|
||||
if (left.valid_length_ != right.valid_length_) {
|
||||
return false;
|
||||
}
|
||||
for (const SRIVocabIndex *l = left.history_, *r = right.history_;
|
||||
l != left.history_ + left.valid_length_;
|
||||
++l, ++r) {
|
||||
if (*l != *r) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
inline size_t hash_value(const State &state) {
|
||||
return util::MurmurHashNative(&state.history_, sizeof(SRIVocabIndex) * state.valid_length_);
|
||||
}
|
||||
|
||||
class Vocabulary : public base::Vocabulary {
|
||||
public:
|
||||
Vocabulary();
|
||||
|
||||
~Vocabulary();
|
||||
|
||||
WordIndex Index(const StringPiece &str) const {
|
||||
std::string temp(str.data(), str.length());
|
||||
return Index(temp.c_str());
|
||||
}
|
||||
WordIndex Index(const std::string &str) const {
|
||||
return Index(str.c_str());
|
||||
}
|
||||
WordIndex Index(const char *str) const;
|
||||
|
||||
const char *Word(WordIndex index) const;
|
||||
|
||||
private:
|
||||
friend class Model;
|
||||
void FinishedLoading();
|
||||
|
||||
// The parent class isn't copyable so auto_ptr is the same as scoped_ptr
|
||||
// but without the boost dependence.
|
||||
mutable std::auto_ptr<Vocab> sri_;
|
||||
};
|
||||
|
||||
class Model : public base::ModelFacade<Model, State, Vocabulary> {
|
||||
public:
|
||||
Model(const char *file_name, unsigned int ngram_length);
|
||||
|
||||
~Model();
|
||||
|
||||
FullScoreReturn FullScore(const State &in_state, const WordIndex new_word, State &out_state) const;
|
||||
|
||||
private:
|
||||
Vocabulary vocab_;
|
||||
|
||||
mutable std::auto_ptr<Ngram> sri_;
|
||||
|
||||
WordIndex not_found_;
|
||||
};
|
||||
|
||||
} // namespace sri
|
||||
} // namespace lm
|
||||
|
||||
#endif // LM_SRI__
|
65
trunk/kenlm/lm/sri_test.cc
Normal file
65
trunk/kenlm/lm/sri_test.cc
Normal file
@ -0,0 +1,65 @@
|
||||
#include "lm/sri.hh"
|
||||
|
||||
#include <stdlib.h>
|
||||
|
||||
#define BOOST_TEST_MODULE SRITest
|
||||
#include <boost/test/unit_test.hpp>
|
||||
|
||||
namespace lm {
|
||||
namespace sri {
|
||||
namespace {
|
||||
|
||||
#define StartTest(word, ngram, score) \
|
||||
ret = model.FullScore( \
|
||||
state, \
|
||||
model.GetVocabulary().Index(word), \
|
||||
out);\
|
||||
BOOST_CHECK_CLOSE(score, ret.prob, 0.001); \
|
||||
BOOST_CHECK_EQUAL(static_cast<unsigned int>(ngram), ret.ngram_length); \
|
||||
BOOST_CHECK_EQUAL(std::min<unsigned char>(ngram, 5 - 1), out.valid_length_);
|
||||
|
||||
#define AppendTest(word, ngram, score) \
|
||||
StartTest(word, ngram, score) \
|
||||
state = out;
|
||||
|
||||
template <class M> void Starters(M &model) {
|
||||
FullScoreReturn ret;
|
||||
Model::State state(model.BeginSentenceState());
|
||||
Model::State out;
|
||||
|
||||
StartTest("looking", 2, -0.4846522);
|
||||
|
||||
// , probability plus <s> backoff
|
||||
StartTest(",", 1, -1.383514 + -0.4149733);
|
||||
// <unk> probability plus <s> backoff
|
||||
StartTest("this_is_not_found", 0, -1.995635 + -0.4149733);
|
||||
}
|
||||
|
||||
template <class M> void Continuation(M &model) {
|
||||
FullScoreReturn ret;
|
||||
Model::State state(model.BeginSentenceState());
|
||||
Model::State out;
|
||||
|
||||
AppendTest("looking", 2, -0.484652);
|
||||
AppendTest("on", 3, -0.348837);
|
||||
AppendTest("a", 4, -0.0155266);
|
||||
AppendTest("little", 5, -0.00306122);
|
||||
State preserve = state;
|
||||
AppendTest("the", 1, -4.04005);
|
||||
AppendTest("biarritz", 1, -1.9889);
|
||||
AppendTest("not_found", 0, -2.29666);
|
||||
AppendTest("more", 1, -1.20632);
|
||||
AppendTest(".", 2, -0.51363);
|
||||
AppendTest("</s>", 3, -0.0191651);
|
||||
|
||||
state = preserve;
|
||||
AppendTest("more", 5, -0.00181395);
|
||||
AppendTest("loin", 5, -0.0432557);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(starters) { Model m("test.arpa", 5); Starters(m); }
|
||||
BOOST_AUTO_TEST_CASE(continuation) { Model m("test.arpa", 5); Continuation(m); }
|
||||
|
||||
} // namespace
|
||||
} // namespace sri
|
||||
} // namespace lm
|
124
trunk/kenlm/lm/test.arpa
Normal file
124
trunk/kenlm/lm/test.arpa
Normal file
@ -0,0 +1,124 @@
|
||||
|
||||
\data\
|
||||
ngram 1=37
|
||||
ngram 2=47
|
||||
ngram 3=11
|
||||
ngram 4=6
|
||||
ngram 5=4
|
||||
|
||||
\1-grams:
|
||||
-1.383514 , -0.30103
|
||||
-1.139057 . -0.845098
|
||||
-1.029493 </s>
|
||||
-99 <s> -0.4149733
|
||||
-1.995635 <unk> -20
|
||||
-1.285941 a -0.69897
|
||||
-1.687872 also -0.30103
|
||||
-1.687872 beyond -0.30103
|
||||
-1.687872 biarritz -0.30103
|
||||
-1.687872 call -0.30103
|
||||
-1.687872 concerns -0.30103
|
||||
-1.687872 consider -0.30103
|
||||
-1.687872 considering -0.30103
|
||||
-1.687872 for -0.30103
|
||||
-1.509559 higher -0.30103
|
||||
-1.687872 however -0.30103
|
||||
-1.687872 i -0.30103
|
||||
-1.687872 immediate -0.30103
|
||||
-1.687872 in -0.30103
|
||||
-1.687872 is -0.30103
|
||||
-1.285941 little -0.69897
|
||||
-1.383514 loin -0.30103
|
||||
-1.687872 look -0.30103
|
||||
-1.285941 looking -0.4771212
|
||||
-1.206319 more -0.544068
|
||||
-1.509559 on -0.4771212
|
||||
-1.509559 screening -0.4771212
|
||||
-1.687872 small -0.30103
|
||||
-1.687872 the -0.30103
|
||||
-1.687872 to -0.30103
|
||||
-1.687872 watch -0.30103
|
||||
-1.687872 watching -0.30103
|
||||
-1.687872 what -0.30103
|
||||
-1.687872 would -0.30103
|
||||
-3.141592 foo
|
||||
-2.718281 bar 3.0
|
||||
-6.535897 baz -0.0
|
||||
|
||||
\2-grams:
|
||||
-0.6925742 , .
|
||||
-0.7522095 , however
|
||||
-0.7522095 , is
|
||||
-0.0602359 . </s>
|
||||
-0.4846522 <s> looking -0.4771214
|
||||
-1.051485 <s> screening
|
||||
-1.07153 <s> the
|
||||
-1.07153 <s> watching
|
||||
-1.07153 <s> what
|
||||
-0.09132547 a little -0.69897
|
||||
-0.2922095 also call
|
||||
-0.2922095 beyond immediate
|
||||
-0.2705918 biarritz .
|
||||
-0.2922095 call for
|
||||
-0.2922095 concerns in
|
||||
-0.2922095 consider watch
|
||||
-0.2922095 considering consider
|
||||
-0.2834328 for ,
|
||||
-0.5511513 higher more
|
||||
-0.5845945 higher small
|
||||
-0.2834328 however ,
|
||||
-0.2922095 i would
|
||||
-0.2922095 immediate concerns
|
||||
-0.2922095 in biarritz
|
||||
-0.2922095 is to
|
||||
-0.09021038 little more -0.1998621
|
||||
-0.7273645 loin ,
|
||||
-0.6925742 loin .
|
||||
-0.6708385 loin </s>
|
||||
-0.2922095 look beyond
|
||||
-0.4638903 looking higher
|
||||
-0.4638903 looking on -0.4771212
|
||||
-0.5136299 more . -0.4771212
|
||||
-0.3561665 more loin
|
||||
-0.1649931 on a -0.4771213
|
||||
-0.1649931 screening a -0.4771213
|
||||
-0.2705918 small .
|
||||
-0.287799 the screening
|
||||
-0.2922095 to look
|
||||
-0.2622373 watch </s>
|
||||
-0.2922095 watching considering
|
||||
-0.2922095 what i
|
||||
-0.2922095 would also
|
||||
-2 also would -6
|
||||
-15 <unk> <unk> -2
|
||||
-4 <unk> however -1
|
||||
-6 foo bar
|
||||
|
||||
\3-grams:
|
||||
-0.01916512 more . </s>
|
||||
-0.0283603 on a little -0.4771212
|
||||
-0.0283603 screening a little -0.4771212
|
||||
-0.01660496 a little more -0.09409451
|
||||
-0.3488368 <s> looking higher
|
||||
-0.3488368 <s> looking on -0.4771212
|
||||
-0.1892331 little more loin
|
||||
-0.04835128 looking on a -0.4771212
|
||||
-3 also would consider -7
|
||||
-6 <unk> however <unk> -12
|
||||
-7 to look good
|
||||
|
||||
\4-grams:
|
||||
-0.009249173 looking on a little -0.4771212
|
||||
-0.005464747 on a little more -0.4771212
|
||||
-0.005464747 screening a little more
|
||||
-0.1453306 a little more loin
|
||||
-0.01552657 <s> looking on a -0.4771212
|
||||
-4 also would consider higher -8
|
||||
|
||||
\5-grams:
|
||||
-0.003061223 <s> looking on a little
|
||||
-0.001813953 looking on a little more
|
||||
-0.0432557 on a little more loin
|
||||
-5 also would consider higher looking
|
||||
|
||||
\end\
|
148
trunk/kenlm/lm/trie.cc
Normal file
148
trunk/kenlm/lm/trie.cc
Normal file
@ -0,0 +1,148 @@
|
||||
#include "lm/trie.hh"
|
||||
|
||||
#include "lm/bhiksha.hh"
|
||||
#include "lm/quantize.hh"
|
||||
#include "util/bit_packing.hh"
|
||||
#include "util/exception.hh"
|
||||
#include "util/sorted_uniform.hh"
|
||||
|
||||
#include <assert.h>
|
||||
|
||||
namespace lm {
|
||||
namespace ngram {
|
||||
namespace trie {
|
||||
namespace {
|
||||
|
||||
class KeyAccessor {
|
||||
public:
|
||||
KeyAccessor(const void *base, uint64_t key_mask, uint8_t key_bits, uint8_t total_bits)
|
||||
: base_(reinterpret_cast<const uint8_t*>(base)), key_mask_(key_mask), key_bits_(key_bits), total_bits_(total_bits) {}
|
||||
|
||||
typedef uint64_t Key;
|
||||
|
||||
Key operator()(uint64_t index) const {
|
||||
return util::ReadInt57(base_, index * static_cast<uint64_t>(total_bits_), key_bits_, key_mask_);
|
||||
}
|
||||
|
||||
private:
|
||||
const uint8_t *const base_;
|
||||
const WordIndex key_mask_;
|
||||
const uint8_t key_bits_, total_bits_;
|
||||
};
|
||||
|
||||
bool FindBitPacked(const void *base, uint64_t key_mask, uint8_t key_bits, uint8_t total_bits, uint64_t begin_index, uint64_t end_index, const uint64_t max_vocab, const uint64_t key, uint64_t &at_index) {
|
||||
KeyAccessor accessor(base, key_mask, key_bits, total_bits);
|
||||
if (!util::BoundedSortedUniformFind<uint64_t, KeyAccessor, util::PivotSelect<sizeof(WordIndex)>::T>(accessor, begin_index - 1, (uint64_t)0, end_index, max_vocab, key, at_index)) return false;
|
||||
return true;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::size_t BitPacked::BaseSize(uint64_t entries, uint64_t max_vocab, uint8_t remaining_bits) {
|
||||
uint8_t total_bits = util::RequiredBits(max_vocab) + remaining_bits;
|
||||
// Extra entry for next pointer at the end.
|
||||
// +7 then / 8 to round up bits and convert to bytes
|
||||
// +sizeof(uint64_t) so that ReadInt57 etc don't go segfault.
|
||||
// Note that this waste is O(order), not O(number of ngrams).
|
||||
return ((1 + entries) * total_bits + 7) / 8 + sizeof(uint64_t);
|
||||
}
|
||||
|
||||
void BitPacked::BaseInit(void *base, uint64_t max_vocab, uint8_t remaining_bits) {
|
||||
util::BitPackingSanity();
|
||||
word_bits_ = util::RequiredBits(max_vocab);
|
||||
word_mask_ = (1ULL << word_bits_) - 1ULL;
|
||||
if (word_bits_ > 57) UTIL_THROW(util::Exception, "Sorry, word indices more than " << (1ULL << 57) << " are not implemented. Edit util/bit_packing.hh and fix the bit packing functions.");
|
||||
total_bits_ = word_bits_ + remaining_bits;
|
||||
|
||||
base_ = static_cast<uint8_t*>(base);
|
||||
insert_index_ = 0;
|
||||
max_vocab_ = max_vocab;
|
||||
}
|
||||
|
||||
template <class Quant, class Bhiksha> std::size_t BitPackedMiddle<Quant, Bhiksha>::Size(uint8_t quant_bits, uint64_t entries, uint64_t max_vocab, uint64_t max_ptr, const Config &config) {
|
||||
return Bhiksha::Size(entries + 1, max_ptr, config) + BaseSize(entries, max_vocab, quant_bits + Bhiksha::InlineBits(entries + 1, max_ptr, config));
|
||||
}
|
||||
|
||||
template <class Quant, class Bhiksha> BitPackedMiddle<Quant, Bhiksha>::BitPackedMiddle(void *base, const Quant &quant, uint64_t entries, uint64_t max_vocab, uint64_t max_next, const BitPacked &next_source, const Config &config) :
|
||||
BitPacked(),
|
||||
quant_(quant),
|
||||
// If the offset of the method changes, also change TrieSearch::UpdateConfigFromBinary.
|
||||
bhiksha_(base, entries + 1, max_next, config),
|
||||
next_source_(&next_source) {
|
||||
if (entries + 1 >= (1ULL << 57) || (max_next >= (1ULL << 57))) UTIL_THROW(util::Exception, "Sorry, this does not support more than " << (1ULL << 57) << " n-grams of a particular order. Edit util/bit_packing.hh and fix the bit packing functions.");
|
||||
BaseInit(reinterpret_cast<uint8_t*>(base) + Bhiksha::Size(entries + 1, max_next, config), max_vocab, quant.TotalBits() + bhiksha_.InlineBits());
|
||||
}
|
||||
|
||||
template <class Quant, class Bhiksha> void BitPackedMiddle<Quant, Bhiksha>::Insert(WordIndex word, float prob, float backoff) {
|
||||
assert(word <= word_mask_);
|
||||
uint64_t at_pointer = insert_index_ * total_bits_;
|
||||
|
||||
util::WriteInt57(base_, at_pointer, word_bits_, word);
|
||||
at_pointer += word_bits_;
|
||||
quant_.Write(base_, at_pointer, prob, backoff);
|
||||
at_pointer += quant_.TotalBits();
|
||||
uint64_t next = next_source_->InsertIndex();
|
||||
bhiksha_.WriteNext(base_, at_pointer, insert_index_, next);
|
||||
|
||||
++insert_index_;
|
||||
}
|
||||
|
||||
template <class Quant, class Bhiksha> bool BitPackedMiddle<Quant, Bhiksha>::Find(WordIndex word, float &prob, float &backoff, NodeRange &range) const {
|
||||
uint64_t at_pointer;
|
||||
if (!FindBitPacked(base_, word_mask_, word_bits_, total_bits_, range.begin, range.end, max_vocab_, word, at_pointer)) {
|
||||
return false;
|
||||
}
|
||||
uint64_t index = at_pointer;
|
||||
at_pointer *= total_bits_;
|
||||
at_pointer += word_bits_;
|
||||
quant_.Read(base_, at_pointer, prob, backoff);
|
||||
at_pointer += quant_.TotalBits();
|
||||
|
||||
bhiksha_.ReadNext(base_, at_pointer, index, total_bits_, range);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
template <class Quant, class Bhiksha> bool BitPackedMiddle<Quant, Bhiksha>::FindNoProb(WordIndex word, float &backoff, NodeRange &range) const {
|
||||
uint64_t index;
|
||||
if (!FindBitPacked(base_, word_mask_, word_bits_, total_bits_, range.begin, range.end, max_vocab_, word, index)) return false;
|
||||
uint64_t at_pointer = index * total_bits_;
|
||||
at_pointer += word_bits_;
|
||||
quant_.ReadBackoff(base_, at_pointer, backoff);
|
||||
at_pointer += quant_.TotalBits();
|
||||
bhiksha_.ReadNext(base_, at_pointer, index, total_bits_, range);
|
||||
return true;
|
||||
}
|
||||
|
||||
template <class Quant, class Bhiksha> void BitPackedMiddle<Quant, Bhiksha>::FinishedLoading(uint64_t next_end, const Config &config) {
|
||||
uint64_t last_next_write = (insert_index_ + 1) * total_bits_ - bhiksha_.InlineBits();
|
||||
bhiksha_.WriteNext(base_, last_next_write, insert_index_ + 1, next_end);
|
||||
bhiksha_.FinishedLoading(config);
|
||||
}
|
||||
|
||||
template <class Quant> void BitPackedLongest<Quant>::Insert(WordIndex index, float prob) {
|
||||
assert(index <= word_mask_);
|
||||
uint64_t at_pointer = insert_index_ * total_bits_;
|
||||
util::WriteInt57(base_, at_pointer, word_bits_, index);
|
||||
at_pointer += word_bits_;
|
||||
quant_.Write(base_, at_pointer, prob);
|
||||
++insert_index_;
|
||||
}
|
||||
|
||||
template <class Quant> bool BitPackedLongest<Quant>::Find(WordIndex word, float &prob, const NodeRange &range) const {
|
||||
uint64_t at_pointer;
|
||||
if (!FindBitPacked(base_, word_mask_, word_bits_, total_bits_, range.begin, range.end, max_vocab_, word, at_pointer)) return false;
|
||||
at_pointer = at_pointer * total_bits_ + word_bits_;
|
||||
quant_.Read(base_, at_pointer, prob);
|
||||
return true;
|
||||
}
|
||||
|
||||
template class BitPackedMiddle<DontQuantize::Middle, DontBhiksha>;
|
||||
template class BitPackedMiddle<DontQuantize::Middle, ArrayBhiksha>;
|
||||
template class BitPackedMiddle<SeparatelyQuantize::Middle, DontBhiksha>;
|
||||
template class BitPackedMiddle<SeparatelyQuantize::Middle, ArrayBhiksha>;
|
||||
template class BitPackedLongest<DontQuantize::Longest>;
|
||||
template class BitPackedLongest<SeparatelyQuantize::Longest>;
|
||||
|
||||
} // namespace trie
|
||||
} // namespace ngram
|
||||
} // namespace lm
|
136
trunk/kenlm/lm/trie.hh
Normal file
136
trunk/kenlm/lm/trie.hh
Normal file
@ -0,0 +1,136 @@
|
||||
#ifndef LM_TRIE__
|
||||
#define LM_TRIE__
|
||||
|
||||
#include <inttypes.h>
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
#include "lm/word_index.hh"
|
||||
#include "lm/weights.hh"
|
||||
|
||||
namespace lm {
|
||||
namespace ngram {
|
||||
class Config;
|
||||
namespace trie {
|
||||
|
||||
struct NodeRange {
|
||||
uint64_t begin, end;
|
||||
};
|
||||
|
||||
// TODO: if the number of unigrams is a concern, also bit pack these records.
|
||||
struct UnigramValue {
|
||||
ProbBackoff weights;
|
||||
uint64_t next;
|
||||
uint64_t Next() const { return next; }
|
||||
};
|
||||
|
||||
class Unigram {
|
||||
public:
|
||||
Unigram() {}
|
||||
|
||||
void Init(void *start) {
|
||||
unigram_ = static_cast<UnigramValue*>(start);
|
||||
}
|
||||
|
||||
static std::size_t Size(uint64_t count) {
|
||||
// +1 in case unknown doesn't appear. +1 for the final next.
|
||||
return (count + 2) * sizeof(UnigramValue);
|
||||
}
|
||||
|
||||
const ProbBackoff &Lookup(WordIndex index) const { return unigram_[index].weights; }
|
||||
|
||||
ProbBackoff &Unknown() { return unigram_[0].weights; }
|
||||
|
||||
UnigramValue *Raw() {
|
||||
return unigram_;
|
||||
}
|
||||
|
||||
void LoadedBinary() {}
|
||||
|
||||
bool Find(WordIndex word, float &prob, float &backoff, NodeRange &next) const {
|
||||
UnigramValue *val = unigram_ + word;
|
||||
prob = val->weights.prob;
|
||||
backoff = val->weights.backoff;
|
||||
next.begin = val->next;
|
||||
next.end = (val+1)->next;
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
UnigramValue *unigram_;
|
||||
};
|
||||
|
||||
class BitPacked {
|
||||
public:
|
||||
BitPacked() {}
|
||||
|
||||
uint64_t InsertIndex() const {
|
||||
return insert_index_;
|
||||
}
|
||||
|
||||
protected:
|
||||
static std::size_t BaseSize(uint64_t entries, uint64_t max_vocab, uint8_t remaining_bits);
|
||||
|
||||
void BaseInit(void *base, uint64_t max_vocab, uint8_t remaining_bits);
|
||||
|
||||
uint8_t word_bits_;
|
||||
uint8_t total_bits_;
|
||||
uint64_t word_mask_;
|
||||
|
||||
uint8_t *base_;
|
||||
|
||||
uint64_t insert_index_, max_vocab_;
|
||||
};
|
||||
|
||||
template <class Quant, class Bhiksha> class BitPackedMiddle : public BitPacked {
|
||||
public:
|
||||
static std::size_t Size(uint8_t quant_bits, uint64_t entries, uint64_t max_vocab, uint64_t max_next, const Config &config);
|
||||
|
||||
// next_source need not be initialized.
|
||||
BitPackedMiddle(void *base, const Quant &quant, uint64_t entries, uint64_t max_vocab, uint64_t max_next, const BitPacked &next_source, const Config &config);
|
||||
|
||||
void Insert(WordIndex word, float prob, float backoff);
|
||||
|
||||
void FinishedLoading(uint64_t next_end, const Config &config);
|
||||
|
||||
void LoadedBinary() { bhiksha_.LoadedBinary(); }
|
||||
|
||||
bool Find(WordIndex word, float &prob, float &backoff, NodeRange &range) const;
|
||||
|
||||
bool FindNoProb(WordIndex word, float &backoff, NodeRange &range) const;
|
||||
|
||||
private:
|
||||
Quant quant_;
|
||||
Bhiksha bhiksha_;
|
||||
|
||||
const BitPacked *next_source_;
|
||||
};
|
||||
|
||||
template <class Quant> class BitPackedLongest : public BitPacked {
|
||||
public:
|
||||
static std::size_t Size(uint8_t quant_bits, uint64_t entries, uint64_t max_vocab) {
|
||||
return BaseSize(entries, max_vocab, quant_bits);
|
||||
}
|
||||
|
||||
BitPackedLongest() {}
|
||||
|
||||
void Init(void *base, const Quant &quant, uint64_t max_vocab) {
|
||||
quant_ = quant;
|
||||
BaseInit(base, max_vocab, quant_.TotalBits());
|
||||
}
|
||||
|
||||
void LoadedBinary() {}
|
||||
|
||||
void Insert(WordIndex word, float prob);
|
||||
|
||||
bool Find(WordIndex word, float &prob, const NodeRange &node) const;
|
||||
|
||||
private:
|
||||
Quant quant_;
|
||||
};
|
||||
|
||||
} // namespace trie
|
||||
} // namespace ngram
|
||||
} // namespace lm
|
||||
|
||||
#endif // LM_TRIE__
|
19
trunk/kenlm/lm/virtual_interface.cc
Normal file
19
trunk/kenlm/lm/virtual_interface.cc
Normal file
@ -0,0 +1,19 @@
|
||||
#include "lm/virtual_interface.hh"
|
||||
|
||||
#include "lm/lm_exception.hh"
|
||||
|
||||
namespace lm {
|
||||
namespace base {
|
||||
|
||||
Vocabulary::~Vocabulary() {}
|
||||
|
||||
void Vocabulary::SetSpecial(WordIndex begin_sentence, WordIndex end_sentence, WordIndex not_found) {
|
||||
begin_sentence_ = begin_sentence;
|
||||
end_sentence_ = end_sentence;
|
||||
not_found_ = not_found;
|
||||
}
|
||||
|
||||
Model::~Model() {}
|
||||
|
||||
} // namespace base
|
||||
} // namespace lm
|
178
trunk/kenlm/lm/virtual_interface.hh
Normal file
178
trunk/kenlm/lm/virtual_interface.hh
Normal file
@ -0,0 +1,178 @@
|
||||
#ifndef LM_VIRTUAL_INTERFACE__
|
||||
#define LM_VIRTUAL_INTERFACE__
|
||||
|
||||
#include "lm/word_index.hh"
|
||||
#include "util/string_piece.hh"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace lm {
|
||||
|
||||
/* Structure returned by scoring routines. */
|
||||
struct FullScoreReturn {
|
||||
// log10 probability
|
||||
float prob;
|
||||
|
||||
/* The length of n-gram matched. Do not use this for recombination.
|
||||
* Consider a model containing only the following n-grams:
|
||||
* -1 foo
|
||||
* -3.14 bar
|
||||
* -2.718 baz -5
|
||||
* -6 foo bar
|
||||
*
|
||||
* If you score ``bar'' then ngram_length is 1 and recombination state is the
|
||||
* empty string because bar has zero backoff and does not extend to the
|
||||
* right.
|
||||
* If you score ``foo'' then ngram_length is 1 and recombination state is
|
||||
* ``foo''.
|
||||
*
|
||||
* Ideally, keep output states around and compare them. Failing that,
|
||||
* get out_state.ValidLength() and use that length for recombination.
|
||||
*/
|
||||
unsigned char ngram_length;
|
||||
};
|
||||
|
||||
namespace base {
|
||||
|
||||
template <class T, class U, class V> class ModelFacade;
|
||||
|
||||
/* Vocabulary interface. Call Index(string) and get a word index for use in
|
||||
* calling Model. It provides faster convenience functions for <s>, </s>, and
|
||||
* <unk> although you can also find these using Index.
|
||||
*
|
||||
* Some models do not load the mapping from index to string. If you need this,
|
||||
* check if the model Vocabulary class implements such a function and access it
|
||||
* directly.
|
||||
*
|
||||
* The Vocabulary object is always owned by the Model and can be retrieved from
|
||||
* the Model using BaseVocabulary() for this abstract interface or
|
||||
* GetVocabulary() for the actual implementation (in which case you'll need the
|
||||
* actual implementation of the Model too).
|
||||
*/
|
||||
class Vocabulary {
|
||||
public:
|
||||
virtual ~Vocabulary();
|
||||
|
||||
WordIndex BeginSentence() const { return begin_sentence_; }
|
||||
WordIndex EndSentence() const { return end_sentence_; }
|
||||
WordIndex NotFound() const { return not_found_; }
|
||||
|
||||
/* Most implementations allow StringPiece lookups and need only override
|
||||
* Index(StringPiece). SRI requires null termination and overrides all
|
||||
* three methods.
|
||||
*/
|
||||
virtual WordIndex Index(const StringPiece &str) const = 0;
|
||||
virtual WordIndex Index(const std::string &str) const {
|
||||
return Index(StringPiece(str));
|
||||
}
|
||||
virtual WordIndex Index(const char *str) const {
|
||||
return Index(StringPiece(str));
|
||||
}
|
||||
|
||||
protected:
|
||||
// Call SetSpecial afterward.
|
||||
Vocabulary() {}
|
||||
|
||||
Vocabulary(WordIndex begin_sentence, WordIndex end_sentence, WordIndex not_found) {
|
||||
SetSpecial(begin_sentence, end_sentence, not_found);
|
||||
}
|
||||
|
||||
void SetSpecial(WordIndex begin_sentence, WordIndex end_sentence, WordIndex not_found);
|
||||
|
||||
WordIndex begin_sentence_, end_sentence_, not_found_;
|
||||
|
||||
private:
|
||||
// Disable copy constructors. They're private and undefined.
|
||||
// Ersatz boost::noncopyable.
|
||||
Vocabulary(const Vocabulary &);
|
||||
Vocabulary &operator=(const Vocabulary &);
|
||||
};
|
||||
|
||||
/* There are two ways to access a Model.
|
||||
*
|
||||
*
|
||||
* OPTION 1: Access the Model directly (e.g. lm::ngram::Model in model.hh).
|
||||
*
|
||||
* Every Model implements the scoring function:
|
||||
* float Score(
|
||||
* const Model::State &in_state,
|
||||
* const WordIndex new_word,
|
||||
* Model::State &out_state) const;
|
||||
*
|
||||
* It can also return the length of n-gram matched by the model:
|
||||
* FullScoreReturn FullScore(
|
||||
* const Model::State &in_state,
|
||||
* const WordIndex new_word,
|
||||
* Model::State &out_state) const;
|
||||
*
|
||||
*
|
||||
* There are also accessor functions:
|
||||
* const State &BeginSentenceState() const;
|
||||
* const State &NullContextState() const;
|
||||
* const Vocabulary &GetVocabulary() const;
|
||||
* unsigned int Order() const;
|
||||
*
|
||||
* NB: In case you're wondering why the model implementation looks like it's
|
||||
* missing these methods, see facade.hh.
|
||||
*
|
||||
* This is the fastest way to use a model and presents a normal State class to
|
||||
* be included in a hypothesis state structure.
|
||||
*
|
||||
*
|
||||
* OPTION 2: Use the virtual interface below.
|
||||
*
|
||||
* The virtual interface allow you to decide which Model to use at runtime
|
||||
* without templatizing everything on the Model type. However, each Model has
|
||||
* its own State class, so a single State cannot be efficiently provided (it
|
||||
* would require using the maximum memory of any Model's State or memory
|
||||
* allocation with each lookup). This means you become responsible for
|
||||
* allocating memory with size StateSize() and passing it to the Score or
|
||||
* FullScore functions provided here.
|
||||
*
|
||||
* For example, cdec has a std::string containing the entire state of a
|
||||
* hypothesis. It can reserve StateSize bytes in this string for the model
|
||||
* state.
|
||||
*
|
||||
* All the State objects are POD, so it's ok to use raw memory for storing
|
||||
* State.
|
||||
* in_state and out_state must not have the same address.
|
||||
*/
|
||||
class Model {
|
||||
public:
|
||||
virtual ~Model();
|
||||
|
||||
size_t StateSize() const { return state_size_; }
|
||||
const void *BeginSentenceMemory() const { return begin_sentence_memory_; }
|
||||
const void *NullContextMemory() const { return null_context_memory_; }
|
||||
|
||||
// Requires in_state != out_state
|
||||
virtual float Score(const void *in_state, const WordIndex new_word, void *out_state) const = 0;
|
||||
|
||||
// Requires in_state != out_state
|
||||
virtual FullScoreReturn FullScore(const void *in_state, const WordIndex new_word, void *out_state) const = 0;
|
||||
|
||||
unsigned char Order() const { return order_; }
|
||||
|
||||
const Vocabulary &BaseVocabulary() const { return *base_vocab_; }
|
||||
|
||||
private:
|
||||
template <class T, class U, class V> friend class ModelFacade;
|
||||
explicit Model(size_t state_size) : state_size_(state_size) {}
|
||||
|
||||
const size_t state_size_;
|
||||
const void *begin_sentence_memory_, *null_context_memory_;
|
||||
|
||||
const Vocabulary *base_vocab_;
|
||||
|
||||
unsigned char order_;
|
||||
|
||||
// Disable copy constructors. They're private and undefined.
|
||||
// Ersatz boost::noncopyable.
|
||||
Model(const Model &);
|
||||
Model &operator=(const Model &);
|
||||
};
|
||||
|
||||
} // mamespace base
|
||||
} // namespace lm
|
||||
|
||||
#endif // LM_VIRTUAL_INTERFACE__
|
217
trunk/kenlm/lm/vocab.cc
Normal file
217
trunk/kenlm/lm/vocab.cc
Normal file
@ -0,0 +1,217 @@
|
||||
#include "lm/vocab.hh"
|
||||
|
||||
#include "lm/enumerate_vocab.hh"
|
||||
#include "lm/lm_exception.hh"
|
||||
#include "lm/config.hh"
|
||||
#include "lm/weights.hh"
|
||||
#include "util/exception.hh"
|
||||
#include "util/joint_sort.hh"
|
||||
#include "util/murmur_hash.hh"
|
||||
#include "util/probing_hash_table.hh"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace lm {
|
||||
namespace ngram {
|
||||
|
||||
namespace detail {
|
||||
uint64_t HashForVocab(const char *str, std::size_t len) {
|
||||
// This proved faster than Boost's hash in speed trials: total load time Murmur 67090000, Boost 72210000
|
||||
// Chose to use 64A instead of native so binary format will be portable across 64 and 32 bit.
|
||||
return util::MurmurHash64A(str, len, 0);
|
||||
}
|
||||
} // namespace detail
|
||||
|
||||
namespace {
|
||||
// Normally static initialization is a bad idea but MurmurHash is pure arithmetic, so this is ok.
|
||||
const uint64_t kUnknownHash = detail::HashForVocab("<unk>", 5);
|
||||
// Sadly some LMs have <UNK>.
|
||||
const uint64_t kUnknownCapHash = detail::HashForVocab("<UNK>", 5);
|
||||
|
||||
WordIndex ReadWords(int fd, EnumerateVocab *enumerate) {
|
||||
if (!enumerate) return std::numeric_limits<WordIndex>::max();
|
||||
const std::size_t kInitialRead = 16384;
|
||||
std::string buf;
|
||||
buf.reserve(kInitialRead + 100);
|
||||
buf.resize(kInitialRead);
|
||||
WordIndex index = 0;
|
||||
while (true) {
|
||||
ssize_t got = read(fd, &buf[0], kInitialRead);
|
||||
UTIL_THROW_IF(got == -1, util::ErrnoException, "Reading vocabulary words");
|
||||
if (got == 0) return index;
|
||||
buf.resize(got);
|
||||
while (buf[buf.size() - 1]) {
|
||||
char next_char;
|
||||
ssize_t ret = read(fd, &next_char, 1);
|
||||
UTIL_THROW_IF(ret == -1, util::ErrnoException, "Reading vocabulary words");
|
||||
UTIL_THROW_IF(ret == 0, FormatLoadException, "Missing null terminator on a vocab word.");
|
||||
buf.push_back(next_char);
|
||||
}
|
||||
// Ok now we have null terminated strings.
|
||||
for (const char *i = buf.data(); i != buf.data() + buf.size();) {
|
||||
std::size_t length = strlen(i);
|
||||
enumerate->Add(index++, StringPiece(i, length));
|
||||
i += length + 1 /* null byte */;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void WriteOrThrow(int fd, const void *data_void, std::size_t size) {
|
||||
const uint8_t *data = static_cast<const uint8_t*>(data_void);
|
||||
while (size) {
|
||||
ssize_t ret = write(fd, data, size);
|
||||
if (ret < 1) UTIL_THROW(util::ErrnoException, "Write failed");
|
||||
data += ret;
|
||||
size -= ret;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
WriteWordsWrapper::WriteWordsWrapper(EnumerateVocab *inner) : inner_(inner) {}
|
||||
WriteWordsWrapper::~WriteWordsWrapper() {}
|
||||
|
||||
void WriteWordsWrapper::Add(WordIndex index, const StringPiece &str) {
|
||||
if (inner_) inner_->Add(index, str);
|
||||
buffer_.append(str.data(), str.size());
|
||||
buffer_.push_back(0);
|
||||
}
|
||||
|
||||
void WriteWordsWrapper::Write(int fd) {
|
||||
if ((off_t)-1 == lseek(fd, 0, SEEK_END))
|
||||
UTIL_THROW(util::ErrnoException, "Failed to seek in binary to vocab words");
|
||||
WriteOrThrow(fd, buffer_.data(), buffer_.size());
|
||||
}
|
||||
|
||||
SortedVocabulary::SortedVocabulary() : begin_(NULL), end_(NULL), enumerate_(NULL) {}
|
||||
|
||||
std::size_t SortedVocabulary::Size(std::size_t entries, const Config &/*config*/) {
|
||||
// Lead with the number of entries.
|
||||
return sizeof(uint64_t) + sizeof(uint64_t) * entries;
|
||||
}
|
||||
|
||||
void SortedVocabulary::SetupMemory(void *start, std::size_t allocated, std::size_t entries, const Config &config) {
|
||||
assert(allocated >= Size(entries, config));
|
||||
// Leave space for number of entries.
|
||||
begin_ = reinterpret_cast<uint64_t*>(start) + 1;
|
||||
end_ = begin_;
|
||||
saw_unk_ = false;
|
||||
}
|
||||
|
||||
void SortedVocabulary::ConfigureEnumerate(EnumerateVocab *to, std::size_t max_entries) {
|
||||
enumerate_ = to;
|
||||
if (enumerate_) {
|
||||
enumerate_->Add(0, "<unk>");
|
||||
strings_to_enumerate_.resize(max_entries);
|
||||
}
|
||||
}
|
||||
|
||||
WordIndex SortedVocabulary::Insert(const StringPiece &str) {
|
||||
uint64_t hashed = detail::HashForVocab(str);
|
||||
if (hashed == kUnknownHash || hashed == kUnknownCapHash) {
|
||||
saw_unk_ = true;
|
||||
return 0;
|
||||
}
|
||||
*end_ = hashed;
|
||||
if (enumerate_) {
|
||||
strings_to_enumerate_[end_ - begin_].assign(str.data(), str.size());
|
||||
}
|
||||
++end_;
|
||||
// This is 1 + the offset where it was inserted to make room for unk.
|
||||
return end_ - begin_;
|
||||
}
|
||||
|
||||
void SortedVocabulary::FinishedLoading(ProbBackoff *reorder_vocab) {
|
||||
if (enumerate_) {
|
||||
util::PairedIterator<ProbBackoff*, std::string*> values(reorder_vocab + 1, &*strings_to_enumerate_.begin());
|
||||
util::JointSort(begin_, end_, values);
|
||||
for (WordIndex i = 0; i < static_cast<WordIndex>(end_ - begin_); ++i) {
|
||||
// <unk> strikes again: +1 here.
|
||||
enumerate_->Add(i + 1, strings_to_enumerate_[i]);
|
||||
}
|
||||
strings_to_enumerate_.clear();
|
||||
} else {
|
||||
util::JointSort(begin_, end_, reorder_vocab + 1);
|
||||
}
|
||||
SetSpecial(Index("<s>"), Index("</s>"), 0);
|
||||
// Save size. Excludes UNK.
|
||||
*(reinterpret_cast<uint64_t*>(begin_) - 1) = end_ - begin_;
|
||||
// Includes UNK.
|
||||
bound_ = end_ - begin_ + 1;
|
||||
}
|
||||
|
||||
void SortedVocabulary::LoadedBinary(int fd, EnumerateVocab *to) {
|
||||
end_ = begin_ + *(reinterpret_cast<const uint64_t*>(begin_) - 1);
|
||||
ReadWords(fd, to);
|
||||
SetSpecial(Index("<s>"), Index("</s>"), 0);
|
||||
}
|
||||
|
||||
ProbingVocabulary::ProbingVocabulary() : enumerate_(NULL) {}
|
||||
|
||||
std::size_t ProbingVocabulary::Size(std::size_t entries, const Config &config) {
|
||||
return Lookup::Size(entries, config.probing_multiplier);
|
||||
}
|
||||
|
||||
void ProbingVocabulary::SetupMemory(void *start, std::size_t allocated, std::size_t /*entries*/, const Config &/*config*/) {
|
||||
lookup_ = Lookup(start, allocated);
|
||||
available_ = 1;
|
||||
saw_unk_ = false;
|
||||
}
|
||||
|
||||
void ProbingVocabulary::ConfigureEnumerate(EnumerateVocab *to, std::size_t /*max_entries*/) {
|
||||
enumerate_ = to;
|
||||
if (enumerate_) {
|
||||
enumerate_->Add(0, "<unk>");
|
||||
}
|
||||
}
|
||||
|
||||
WordIndex ProbingVocabulary::Insert(const StringPiece &str) {
|
||||
uint64_t hashed = detail::HashForVocab(str);
|
||||
// Prevent unknown from going into the table.
|
||||
if (hashed == kUnknownHash || hashed == kUnknownCapHash) {
|
||||
saw_unk_ = true;
|
||||
return 0;
|
||||
} else {
|
||||
if (enumerate_) enumerate_->Add(available_, str);
|
||||
lookup_.Insert(Lookup::Packing::Make(hashed, available_));
|
||||
return available_++;
|
||||
}
|
||||
}
|
||||
|
||||
void ProbingVocabulary::FinishedLoading(ProbBackoff * /*reorder_vocab*/) {
|
||||
lookup_.FinishedInserting();
|
||||
SetSpecial(Index("<s>"), Index("</s>"), 0);
|
||||
}
|
||||
|
||||
void ProbingVocabulary::LoadedBinary(int fd, EnumerateVocab *to) {
|
||||
lookup_.LoadedBinary();
|
||||
available_ = ReadWords(fd, to);
|
||||
SetSpecial(Index("<s>"), Index("</s>"), 0);
|
||||
}
|
||||
|
||||
void MissingUnknown(const Config &config) throw(SpecialWordMissingException) {
|
||||
switch(config.unknown_missing) {
|
||||
case SILENT:
|
||||
return;
|
||||
case COMPLAIN:
|
||||
if (config.messages) *config.messages << "The ARPA file is missing <unk>. Substituting log10 probability " << config.unknown_missing_logprob << "." << std::endl;
|
||||
break;
|
||||
case THROW_UP:
|
||||
UTIL_THROW(SpecialWordMissingException, "The ARPA file is missing <unk> and the model is configured to throw an exception.");
|
||||
}
|
||||
}
|
||||
|
||||
void MissingSentenceMarker(const Config &config, const char *str) throw(SpecialWordMissingException) {
|
||||
switch (config.sentence_marker_missing) {
|
||||
case SILENT:
|
||||
return;
|
||||
case COMPLAIN:
|
||||
if (config.messages) *config.messages << "Missing special word " << str << "; will treat it as <unk>.";
|
||||
break;
|
||||
case THROW_UP:
|
||||
UTIL_THROW(SpecialWordMissingException, "The ARPA file is missing " << str << " and the model is configured to reject these models. Run build_binary -s to disable this check.");
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace ngram
|
||||
} // namespace lm
|
159
trunk/kenlm/lm/vocab.hh
Normal file
159
trunk/kenlm/lm/vocab.hh
Normal file
@ -0,0 +1,159 @@
|
||||
#ifndef LM_VOCAB__
|
||||
#define LM_VOCAB__
|
||||
|
||||
#include "lm/enumerate_vocab.hh"
|
||||
#include "lm/lm_exception.hh"
|
||||
#include "lm/virtual_interface.hh"
|
||||
#include "util/key_value_packing.hh"
|
||||
#include "util/probing_hash_table.hh"
|
||||
#include "util/sorted_uniform.hh"
|
||||
#include "util/string_piece.hh"
|
||||
|
||||
#include <limits>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace lm {
|
||||
class ProbBackoff;
|
||||
|
||||
namespace ngram {
|
||||
class Config;
|
||||
class EnumerateVocab;
|
||||
|
||||
namespace detail {
|
||||
uint64_t HashForVocab(const char *str, std::size_t len);
|
||||
inline uint64_t HashForVocab(const StringPiece &str) {
|
||||
return HashForVocab(str.data(), str.length());
|
||||
}
|
||||
} // namespace detail
|
||||
|
||||
class WriteWordsWrapper : public EnumerateVocab {
|
||||
public:
|
||||
WriteWordsWrapper(EnumerateVocab *inner);
|
||||
|
||||
~WriteWordsWrapper();
|
||||
|
||||
void Add(WordIndex index, const StringPiece &str);
|
||||
|
||||
void Write(int fd);
|
||||
|
||||
private:
|
||||
EnumerateVocab *inner_;
|
||||
|
||||
std::string buffer_;
|
||||
};
|
||||
|
||||
// Vocabulary based on sorted uniform find storing only uint64_t values and using their offsets as indices.
|
||||
class SortedVocabulary : public base::Vocabulary {
|
||||
public:
|
||||
SortedVocabulary();
|
||||
|
||||
WordIndex Index(const StringPiece &str) const {
|
||||
const uint64_t *found;
|
||||
if (util::BoundedSortedUniformFind<const uint64_t*, util::IdentityAccessor<uint64_t>, util::Pivot64>(
|
||||
util::IdentityAccessor<uint64_t>(),
|
||||
begin_ - 1, 0,
|
||||
end_, std::numeric_limits<uint64_t>::max(),
|
||||
detail::HashForVocab(str), found)) {
|
||||
return found - begin_ + 1; // +1 because <unk> is 0 and does not appear in the lookup table.
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
static size_t Size(std::size_t entries, const Config &config);
|
||||
|
||||
// Vocab words are [0, Bound()) Only valid after FinishedLoading/LoadedBinary.
|
||||
// While this number is correct, ProbingVocabulary::Bound might not be correct in some cases.
|
||||
WordIndex Bound() const { return bound_; }
|
||||
|
||||
// Everything else is for populating. I'm too lazy to hide and friend these, but you'll only get a const reference anyway.
|
||||
void SetupMemory(void *start, std::size_t allocated, std::size_t entries, const Config &config);
|
||||
|
||||
void ConfigureEnumerate(EnumerateVocab *to, std::size_t max_entries);
|
||||
|
||||
WordIndex Insert(const StringPiece &str);
|
||||
|
||||
// Reorders reorder_vocab so that the IDs are sorted.
|
||||
void FinishedLoading(ProbBackoff *reorder_vocab);
|
||||
|
||||
bool SawUnk() const { return saw_unk_; }
|
||||
|
||||
void LoadedBinary(int fd, EnumerateVocab *to);
|
||||
|
||||
private:
|
||||
uint64_t *begin_, *end_;
|
||||
|
||||
WordIndex bound_;
|
||||
|
||||
WordIndex highest_value_;
|
||||
|
||||
bool saw_unk_;
|
||||
|
||||
EnumerateVocab *enumerate_;
|
||||
|
||||
// Actual strings. Used only when loading from ARPA and enumerate_ != NULL
|
||||
std::vector<std::string> strings_to_enumerate_;
|
||||
};
|
||||
|
||||
// Vocabulary storing a map from uint64_t to WordIndex.
|
||||
class ProbingVocabulary : public base::Vocabulary {
|
||||
public:
|
||||
ProbingVocabulary();
|
||||
|
||||
WordIndex Index(const StringPiece &str) const {
|
||||
Lookup::ConstIterator i;
|
||||
return lookup_.Find(detail::HashForVocab(str), i) ? i->GetValue() : 0;
|
||||
}
|
||||
|
||||
static size_t Size(std::size_t entries, const Config &config);
|
||||
|
||||
// Vocab words are [0, Bound()).
|
||||
// WARNING WARNING: returns UINT_MAX when loading binary and not enumerating vocabulary.
|
||||
// Fixing this bug requires a binary file format change and will be fixed with the next binary file format update.
|
||||
// Specifically, the binary file format does not currently indicate whether <unk> is in count or not.
|
||||
WordIndex Bound() const { return available_; }
|
||||
|
||||
// Everything else is for populating. I'm too lazy to hide and friend these, but you'll only get a const reference anyway.
|
||||
void SetupMemory(void *start, std::size_t allocated, std::size_t entries, const Config &config);
|
||||
|
||||
void ConfigureEnumerate(EnumerateVocab *to, std::size_t max_entries);
|
||||
|
||||
WordIndex Insert(const StringPiece &str);
|
||||
|
||||
void FinishedLoading(ProbBackoff *reorder_vocab);
|
||||
|
||||
bool SawUnk() const { return saw_unk_; }
|
||||
|
||||
void LoadedBinary(int fd, EnumerateVocab *to);
|
||||
|
||||
private:
|
||||
// std::identity is an SGI extension :-(
|
||||
struct IdentityHash : public std::unary_function<uint64_t, std::size_t> {
|
||||
std::size_t operator()(uint64_t arg) const { return static_cast<std::size_t>(arg); }
|
||||
};
|
||||
|
||||
typedef util::ProbingHashTable<util::ByteAlignedPacking<uint64_t, WordIndex>, IdentityHash> Lookup;
|
||||
|
||||
Lookup lookup_;
|
||||
|
||||
WordIndex available_;
|
||||
|
||||
bool saw_unk_;
|
||||
|
||||
EnumerateVocab *enumerate_;
|
||||
};
|
||||
|
||||
void MissingUnknown(const Config &config) throw(SpecialWordMissingException);
|
||||
void MissingSentenceMarker(const Config &config, const char *str) throw(SpecialWordMissingException);
|
||||
|
||||
template <class Vocab> void CheckSpecials(const Config &config, const Vocab &vocab) throw(SpecialWordMissingException) {
|
||||
if (!vocab.SawUnk()) MissingUnknown(config);
|
||||
if (vocab.BeginSentence() == vocab.NotFound()) MissingSentenceMarker(config, "<s>");
|
||||
if (vocab.EndSentence() == vocab.NotFound()) MissingSentenceMarker(config, "</s>");
|
||||
}
|
||||
|
||||
} // namespace ngram
|
||||
} // namespace lm
|
||||
|
||||
#endif // LM_VOCAB__
|
17
trunk/kenlm/lm/weights.hh
Normal file
17
trunk/kenlm/lm/weights.hh
Normal file
@ -0,0 +1,17 @@
|
||||
#ifndef LM_WEIGHTS__
|
||||
#define LM_WEIGHTS__
|
||||
|
||||
// Weights for n-grams. Probability and possibly a backoff.
|
||||
|
||||
namespace lm {
|
||||
struct Prob {
|
||||
float prob;
|
||||
};
|
||||
// No inheritance so this will be a POD.
|
||||
struct ProbBackoff {
|
||||
float prob;
|
||||
float backoff;
|
||||
};
|
||||
|
||||
} // namespace lm
|
||||
#endif // LM_WEIGHTS__
|
11
trunk/kenlm/lm/word_index.hh
Normal file
11
trunk/kenlm/lm/word_index.hh
Normal file
@ -0,0 +1,11 @@
|
||||
// Separate header because this is used often.
|
||||
#ifndef LM_WORD_INDEX__
|
||||
#define LM_WORD_INDEX__
|
||||
|
||||
namespace lm {
|
||||
typedef unsigned int WordIndex;
|
||||
} // namespace lm
|
||||
|
||||
typedef lm::WordIndex LMWordIndex;
|
||||
|
||||
#endif
|
8
trunk/kenlm/test.sh
Executable file
8
trunk/kenlm/test.sh
Executable file
@ -0,0 +1,8 @@
|
||||
#!/bin/bash
|
||||
#Run tests. Requires Boost.
|
||||
set -e
|
||||
./compile.sh
|
||||
for i in util/{bit_packing,file_piece,joint_sort,key_value_packing,probing_hash_table,sorted_uniform}_test lm/model_test; do
|
||||
g++ -I. -O3 $CXXFLAGS $i.cc {lm,util}/*.o -lboost_test_exec_monitor -lz -o $i
|
||||
pushd $(dirname $i) >/dev/null && ./$(basename $i) || echo "$i failed"; popd >/dev/null
|
||||
done
|
40
trunk/kenlm/util/bit_packing.cc
Normal file
40
trunk/kenlm/util/bit_packing.cc
Normal file
@ -0,0 +1,40 @@
|
||||
#include "util/bit_packing.hh"
|
||||
#include "util/exception.hh"
|
||||
|
||||
#include <string.h>
|
||||
|
||||
namespace util {
|
||||
|
||||
namespace {
|
||||
template <bool> struct StaticCheck {};
|
||||
template <> struct StaticCheck<true> { typedef bool StaticAssertionPassed; };
|
||||
|
||||
// If your float isn't 4 bytes, we're hosed.
|
||||
typedef StaticCheck<sizeof(float) == 4>::StaticAssertionPassed FloatSize;
|
||||
|
||||
} // namespace
|
||||
|
||||
uint8_t RequiredBits(uint64_t max_value) {
|
||||
if (!max_value) return 0;
|
||||
uint8_t ret = 1;
|
||||
while (max_value >>= 1) ++ret;
|
||||
return ret;
|
||||
}
|
||||
|
||||
void BitPackingSanity() {
|
||||
const FloatEnc neg1 = { -1.0 }, pos1 = { 1.0 };
|
||||
if ((neg1.i ^ pos1.i) != 0x80000000) UTIL_THROW(Exception, "Sign bit is not 0x80000000");
|
||||
char mem[57+8];
|
||||
memset(mem, 0, sizeof(mem));
|
||||
const uint64_t test57 = 0x123456789abcdefULL;
|
||||
for (uint64_t b = 0; b < 57 * 8; b += 57) {
|
||||
WriteInt57(mem, b, 57, test57);
|
||||
}
|
||||
for (uint64_t b = 0; b < 57 * 8; b += 57) {
|
||||
if (test57 != ReadInt57(mem, b, 57, (1ULL << 57) - 1))
|
||||
UTIL_THROW(Exception, "The bit packing routines are failing for your architecture. Please send a bug report with your architecture, operating system, and compiler.");
|
||||
}
|
||||
// TODO: more checks.
|
||||
}
|
||||
|
||||
} // namespace util
|
131
trunk/kenlm/util/bit_packing.hh
Normal file
131
trunk/kenlm/util/bit_packing.hh
Normal file
@ -0,0 +1,131 @@
|
||||
#ifndef UTIL_BIT_PACKING__
|
||||
#define UTIL_BIT_PACKING__
|
||||
|
||||
/* Bit-level packing routines */
|
||||
|
||||
#include <assert.h>
|
||||
#ifdef __APPLE__
|
||||
#include <architecture/byte_order.h>
|
||||
#elif __linux__
|
||||
#include <endian.h>
|
||||
#else
|
||||
#include <arpa/nameser_compat.h>
|
||||
#endif
|
||||
|
||||
#include <inttypes.h>
|
||||
|
||||
namespace util {
|
||||
|
||||
/* WARNING WARNING WARNING:
|
||||
* The write functions assume that memory is zero initially. This makes them
|
||||
* faster and is the appropriate case for mmapped language model construction.
|
||||
* These routines assume that unaligned access to uint64_t is fast and that
|
||||
* storage is little endian. This is the case on x86_64. I'm not sure how
|
||||
* fast unaligned 64-bit access is on x86 but my target audience is large
|
||||
* language models for which 64-bit is necessary.
|
||||
*
|
||||
* Call the BitPackingSanity function to sanity check. Calling once suffices,
|
||||
* but it may be called multiple times when that's inconvenient.
|
||||
*/
|
||||
|
||||
|
||||
// Fun fact: __BYTE_ORDER is wrong on Solaris Sparc, but the version without __ is correct.
|
||||
#if BYTE_ORDER == LITTLE_ENDIAN
|
||||
inline uint8_t BitPackShift(uint8_t bit, uint8_t /*length*/) {
|
||||
return bit;
|
||||
}
|
||||
#elif BYTE_ORDER == BIG_ENDIAN
|
||||
inline uint8_t BitPackShift(uint8_t bit, uint8_t length) {
|
||||
return 64 - length - bit;
|
||||
}
|
||||
#else
|
||||
#error "Bit packing code isn't written for your byte order."
|
||||
#endif
|
||||
|
||||
inline uint64_t ReadOff(const void *base, uint64_t bit_off) {
|
||||
return *reinterpret_cast<const uint64_t*>(reinterpret_cast<const uint8_t*>(base) + (bit_off >> 3));
|
||||
}
|
||||
|
||||
/* Pack integers up to 57 bits using their least significant digits.
|
||||
* The length is specified using mask:
|
||||
* Assumes mask == (1 << length) - 1 where length <= 57.
|
||||
*/
|
||||
inline uint64_t ReadInt57(const void *base, uint64_t bit_off, uint8_t length, uint64_t mask) {
|
||||
return (ReadOff(base, bit_off) >> BitPackShift(bit_off & 7, length)) & mask;
|
||||
}
|
||||
/* Assumes value < (1 << length) and length <= 57.
|
||||
* Assumes the memory is zero initially.
|
||||
*/
|
||||
inline void WriteInt57(void *base, uint64_t bit_off, uint8_t length, uint64_t value) {
|
||||
*reinterpret_cast<uint64_t*>(reinterpret_cast<uint8_t*>(base) + (bit_off >> 3)) |=
|
||||
(value << BitPackShift(bit_off & 7, length));
|
||||
}
|
||||
|
||||
/* Same caveats as above, but for a 25 bit limit. */
|
||||
inline uint32_t ReadInt25(const void *base, uint64_t bit_off, uint8_t length, uint32_t mask) {
|
||||
return (*reinterpret_cast<const uint32_t*>(reinterpret_cast<const uint8_t*>(base) + (bit_off >> 3)) >> BitPackShift(bit_off & 7, length)) & mask;
|
||||
}
|
||||
|
||||
inline void WriteInt25(void *base, uint64_t bit_off, uint8_t length, uint32_t value) {
|
||||
*reinterpret_cast<uint32_t*>(reinterpret_cast<uint8_t*>(base) + (bit_off >> 3)) |=
|
||||
(value << BitPackShift(bit_off & 7, length));
|
||||
}
|
||||
|
||||
typedef union { float f; uint32_t i; } FloatEnc;
|
||||
|
||||
inline float ReadFloat32(const void *base, uint64_t bit_off) {
|
||||
FloatEnc encoded;
|
||||
encoded.i = ReadOff(base, bit_off) >> BitPackShift(bit_off & 7, 32);
|
||||
return encoded.f;
|
||||
}
|
||||
inline void WriteFloat32(void *base, uint64_t bit_off, float value) {
|
||||
FloatEnc encoded;
|
||||
encoded.f = value;
|
||||
WriteInt57(base, bit_off, 32, encoded.i);
|
||||
}
|
||||
|
||||
const uint32_t kSignBit = 0x80000000;
|
||||
|
||||
inline float ReadNonPositiveFloat31(const void *base, uint64_t bit_off) {
|
||||
FloatEnc encoded;
|
||||
encoded.i = ReadOff(base, bit_off) >> BitPackShift(bit_off & 7, 31);
|
||||
// Sign bit set means negative.
|
||||
encoded.i |= kSignBit;
|
||||
return encoded.f;
|
||||
}
|
||||
inline void WriteNonPositiveFloat31(void *base, uint64_t bit_off, float value) {
|
||||
FloatEnc encoded;
|
||||
encoded.f = value;
|
||||
encoded.i &= ~kSignBit;
|
||||
WriteInt57(base, bit_off, 31, encoded.i);
|
||||
}
|
||||
|
||||
void BitPackingSanity();
|
||||
|
||||
// Return bits required to store integers upto max_value. Not the most
|
||||
// efficient implementation, but this is only called a few times to size tries.
|
||||
uint8_t RequiredBits(uint64_t max_value);
|
||||
|
||||
struct BitsMask {
|
||||
static BitsMask ByMax(uint64_t max_value) {
|
||||
BitsMask ret;
|
||||
ret.FromMax(max_value);
|
||||
return ret;
|
||||
}
|
||||
static BitsMask ByBits(uint8_t bits) {
|
||||
BitsMask ret;
|
||||
ret.bits = bits;
|
||||
ret.mask = (1ULL << bits) - 1;
|
||||
return ret;
|
||||
}
|
||||
void FromMax(uint64_t max_value) {
|
||||
bits = RequiredBits(max_value);
|
||||
mask = (1ULL << bits) - 1;
|
||||
}
|
||||
uint8_t bits;
|
||||
uint64_t mask;
|
||||
};
|
||||
|
||||
} // namespace util
|
||||
|
||||
#endif // UTIL_BIT_PACKING__
|
59
trunk/kenlm/util/bit_packing_test.cc
Normal file
59
trunk/kenlm/util/bit_packing_test.cc
Normal file
@ -0,0 +1,59 @@
|
||||
#include "util/bit_packing.hh"
|
||||
|
||||
#define BOOST_TEST_MODULE BitPackingTest
|
||||
#include <boost/test/unit_test.hpp>
|
||||
|
||||
#include <string.h>
|
||||
|
||||
namespace util {
|
||||
namespace {
|
||||
|
||||
const uint64_t test57 = 0x123456789abcdefULL;
|
||||
const uint32_t test25 = 0x1234567;
|
||||
|
||||
BOOST_AUTO_TEST_CASE(ZeroBit57) {
|
||||
char mem[16];
|
||||
memset(mem, 0, sizeof(mem));
|
||||
WriteInt57(mem, 0, 57, test57);
|
||||
BOOST_CHECK_EQUAL(test57, ReadInt57(mem, 0, 57, (1ULL << 57) - 1));
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(EachBit57) {
|
||||
char mem[16];
|
||||
for (uint8_t b = 0; b < 8; ++b) {
|
||||
memset(mem, 0, sizeof(mem));
|
||||
WriteInt57(mem, b, 57, test57);
|
||||
BOOST_CHECK_EQUAL(test57, ReadInt57(mem, b, 57, (1ULL << 57) - 1));
|
||||
}
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(Consecutive57) {
|
||||
char mem[57+8];
|
||||
memset(mem, 0, sizeof(mem));
|
||||
for (uint64_t b = 0; b < 57 * 8; b += 57) {
|
||||
WriteInt57(mem, b, 57, test57);
|
||||
BOOST_CHECK_EQUAL(test57, ReadInt57(mem, b, 57, (1ULL << 57) - 1));
|
||||
}
|
||||
for (uint64_t b = 0; b < 57 * 8; b += 57) {
|
||||
BOOST_CHECK_EQUAL(test57, ReadInt57(mem, b, 57, (1ULL << 57) - 1));
|
||||
}
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(Consecutive25) {
|
||||
char mem[25+8];
|
||||
memset(mem, 0, sizeof(mem));
|
||||
for (uint64_t b = 0; b < 25 * 8; b += 25) {
|
||||
WriteInt25(mem, b, 25, test25);
|
||||
BOOST_CHECK_EQUAL(test25, ReadInt25(mem, b, 25, (1ULL << 25) - 1));
|
||||
}
|
||||
for (uint64_t b = 0; b < 25 * 8; b += 25) {
|
||||
BOOST_CHECK_EQUAL(test25, ReadInt25(mem, b, 25, (1ULL << 25) - 1));
|
||||
}
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(Sanity) {
|
||||
BitPackingSanity();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace util
|
45
trunk/kenlm/util/ersatz_progress.cc
Normal file
45
trunk/kenlm/util/ersatz_progress.cc
Normal file
@ -0,0 +1,45 @@
|
||||
#include "util/ersatz_progress.hh"
|
||||
|
||||
#include <algorithm>
|
||||
#include <ostream>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
|
||||
namespace util {
|
||||
|
||||
namespace { const unsigned char kWidth = 100; }
|
||||
|
||||
ErsatzProgress::ErsatzProgress() : current_(0), next_(std::numeric_limits<std::size_t>::max()), complete_(next_), out_(NULL) {}
|
||||
|
||||
ErsatzProgress::~ErsatzProgress() {
|
||||
if (!out_) return;
|
||||
Finished();
|
||||
}
|
||||
|
||||
ErsatzProgress::ErsatzProgress(std::ostream *to, const std::string &message, std::size_t complete)
|
||||
: current_(0), next_(complete / kWidth), complete_(complete), stones_written_(0), out_(to) {
|
||||
if (!out_) {
|
||||
next_ = std::numeric_limits<std::size_t>::max();
|
||||
return;
|
||||
}
|
||||
*out_ << message << "\n----5---10---15---20---25---30---35---40---45---50---55---60---65---70---75---80---85---90---95--100\n";
|
||||
}
|
||||
|
||||
void ErsatzProgress::Milestone() {
|
||||
if (!out_) { current_ = 0; return; }
|
||||
if (!complete_) return;
|
||||
unsigned char stone = std::min(static_cast<std::size_t>(kWidth), (current_ * kWidth) / complete_);
|
||||
|
||||
for (; stones_written_ < stone; ++stones_written_) {
|
||||
(*out_) << '*';
|
||||
}
|
||||
if (stone == kWidth) {
|
||||
(*out_) << std::endl;
|
||||
next_ = std::numeric_limits<std::size_t>::max();
|
||||
out_ = NULL;
|
||||
} else {
|
||||
next_ = std::max(next_, (stone * complete_) / kWidth);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace util
|
54
trunk/kenlm/util/ersatz_progress.hh
Normal file
54
trunk/kenlm/util/ersatz_progress.hh
Normal file
@ -0,0 +1,54 @@
|
||||
#ifndef UTIL_ERSATZ_PROGRESS__
|
||||
#define UTIL_ERSATZ_PROGRESS__
|
||||
|
||||
#include <iosfwd>
|
||||
#include <string>
|
||||
|
||||
// Ersatz version of boost::progress so core language model doesn't depend on
|
||||
// boost. Also adds option to print nothing.
|
||||
|
||||
namespace util {
|
||||
class ErsatzProgress {
|
||||
public:
|
||||
// No output.
|
||||
ErsatzProgress();
|
||||
|
||||
// Null means no output. The null value is useful for passing along the ostream pointer from another caller.
|
||||
ErsatzProgress(std::ostream *to, const std::string &message, std::size_t complete);
|
||||
|
||||
~ErsatzProgress();
|
||||
|
||||
ErsatzProgress &operator++() {
|
||||
if (++current_ >= next_) Milestone();
|
||||
return *this;
|
||||
}
|
||||
|
||||
ErsatzProgress &operator+=(std::size_t amount) {
|
||||
if ((current_ += amount) >= next_) Milestone();
|
||||
return *this;
|
||||
}
|
||||
|
||||
void Set(std::size_t to) {
|
||||
if ((current_ = to) >= next_) Milestone();
|
||||
Milestone();
|
||||
}
|
||||
|
||||
void Finished() {
|
||||
Set(complete_);
|
||||
}
|
||||
|
||||
private:
|
||||
void Milestone();
|
||||
|
||||
std::size_t current_, next_, complete_;
|
||||
unsigned char stones_written_;
|
||||
std::ostream *out_;
|
||||
|
||||
// noncopyable
|
||||
ErsatzProgress(const ErsatzProgress &other);
|
||||
ErsatzProgress &operator=(const ErsatzProgress &other);
|
||||
};
|
||||
|
||||
} // namespace util
|
||||
|
||||
#endif // UTIL_ERSATZ_PROGRESS__
|
82
trunk/kenlm/util/exception.cc
Normal file
82
trunk/kenlm/util/exception.cc
Normal file
@ -0,0 +1,82 @@
|
||||
#include "util/exception.hh"
|
||||
|
||||
#ifdef __GXX_RTTI
|
||||
#include <typeinfo>
|
||||
#endif
|
||||
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
|
||||
namespace util {
|
||||
|
||||
Exception::Exception() throw() {}
|
||||
Exception::~Exception() throw() {}
|
||||
|
||||
Exception::Exception(const Exception &from) : std::exception() {
|
||||
stream_ << from.stream_.str();
|
||||
}
|
||||
|
||||
Exception &Exception::operator=(const Exception &from) {
|
||||
stream_ << from.stream_.str();
|
||||
return *this;
|
||||
}
|
||||
|
||||
const char *Exception::what() const throw() {
|
||||
text_ = stream_.str();
|
||||
return text_.c_str();
|
||||
}
|
||||
|
||||
void Exception::SetLocation(const char *file, unsigned int line, const char *func, const char *child_name, const char *condition) {
|
||||
/* The child class might have set some text, but we want this to come first.
|
||||
* Another option would be passing this information to the constructor, but
|
||||
* then child classes would have to accept constructor arguments and pass
|
||||
* them down.
|
||||
*/
|
||||
text_ = stream_.str();
|
||||
stream_.str("");
|
||||
stream_ << file << ':' << line;
|
||||
if (func) stream_ << " in " << func << " threw ";
|
||||
if (child_name) {
|
||||
stream_ << child_name;
|
||||
} else {
|
||||
#ifdef __GXX_RTTI
|
||||
stream_ << typeid(this).name();
|
||||
#else
|
||||
stream_ << "an exception";
|
||||
#endif
|
||||
}
|
||||
if (condition) stream_ << " because `" << condition;
|
||||
stream_ << "'.\n";
|
||||
stream_ << text_;
|
||||
}
|
||||
|
||||
namespace {
|
||||
// The XOPEN version.
|
||||
const char *HandleStrerror(int ret, const char *buf) {
|
||||
if (!ret) return buf;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// The GNU version.
|
||||
const char *HandleStrerror(const char *ret, const char * /*buf*/) {
|
||||
return ret;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
ErrnoException::ErrnoException() throw() : errno_(errno) {
|
||||
char buf[200];
|
||||
buf[0] = 0;
|
||||
#ifdef sun
|
||||
const char *add = strerror(errno);
|
||||
#else
|
||||
const char *add = HandleStrerror(strerror_r(errno, buf, 200), buf);
|
||||
#endif
|
||||
|
||||
if (add) {
|
||||
*this << add << ' ';
|
||||
}
|
||||
}
|
||||
|
||||
ErrnoException::~ErrnoException() throw() {}
|
||||
|
||||
} // namespace util
|
110
trunk/kenlm/util/exception.hh
Normal file
110
trunk/kenlm/util/exception.hh
Normal file
@ -0,0 +1,110 @@
|
||||
#ifndef UTIL_EXCEPTION__
|
||||
#define UTIL_EXCEPTION__
|
||||
|
||||
#include <exception>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
namespace util {
|
||||
|
||||
template <class Except, class Data> typename Except::template ExceptionTag<Except&>::Identity operator<<(Except &e, const Data &data);
|
||||
|
||||
class Exception : public std::exception {
|
||||
public:
|
||||
Exception() throw();
|
||||
virtual ~Exception() throw();
|
||||
|
||||
Exception(const Exception &from);
|
||||
Exception &operator=(const Exception &from);
|
||||
|
||||
// Not threadsafe, but probably doesn't matter. FWIW, Boost's exception guidance implies that what() isn't threadsafe.
|
||||
const char *what() const throw();
|
||||
|
||||
// For use by the UTIL_THROW macros.
|
||||
void SetLocation(
|
||||
const char *file,
|
||||
unsigned int line,
|
||||
const char *func,
|
||||
const char *child_name,
|
||||
const char *condition);
|
||||
|
||||
private:
|
||||
template <class Except, class Data> friend typename Except::template ExceptionTag<Except&>::Identity operator<<(Except &e, const Data &data);
|
||||
|
||||
// This helps restrict operator<< defined below.
|
||||
template <class T> struct ExceptionTag {
|
||||
typedef T Identity;
|
||||
};
|
||||
|
||||
std::stringstream stream_;
|
||||
mutable std::string text_;
|
||||
};
|
||||
|
||||
/* This implements the normal operator<< for Exception and all its children.
|
||||
* SNIFAE means it only applies to Exception. Think of this as an ersatz
|
||||
* boost::enable_if.
|
||||
*/
|
||||
template <class Except, class Data> typename Except::template ExceptionTag<Except&>::Identity operator<<(Except &e, const Data &data) {
|
||||
e.stream_ << data;
|
||||
return e;
|
||||
}
|
||||
|
||||
#ifdef __GNUC__
|
||||
#define UTIL_FUNC_NAME __PRETTY_FUNCTION__
|
||||
#else
|
||||
#ifdef _WIN32
|
||||
#define UTIL_FUNC_NAME __FUNCTION__
|
||||
#else
|
||||
#define UTIL_FUNC_NAME NULL
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#define UTIL_SET_LOCATION(UTIL_e, child, condition) do { \
|
||||
(UTIL_e).SetLocation(__FILE__, __LINE__, UTIL_FUNC_NAME, (child), (condition)); \
|
||||
} while (0)
|
||||
|
||||
/* Create an instance of Exception, add the message Modify, and throw it.
|
||||
* Modify is appended to the what() message and can contain << for ostream
|
||||
* operations.
|
||||
*
|
||||
* do .. while kludge to swallow trailing ; character
|
||||
* http://gcc.gnu.org/onlinedocs/cpp/Swallowing-the-Semicolon.html .
|
||||
*/
|
||||
#define UTIL_THROW(Exception, Modify) do { \
|
||||
Exception UTIL_e; \
|
||||
UTIL_SET_LOCATION(UTIL_e, #Exception, NULL); \
|
||||
UTIL_e << Modify; \
|
||||
throw UTIL_e; \
|
||||
} while (0)
|
||||
|
||||
#define UTIL_THROW_VAR(Var, Modify) do { \
|
||||
Exception &UTIL_e = (Var); \
|
||||
UTIL_SET_LOCATION(UTIL_e, NULL, NULL); \
|
||||
UTIL_e << Modify; \
|
||||
throw UTIL_e; \
|
||||
} while (0)
|
||||
|
||||
#define UTIL_THROW_IF(Condition, Exception, Modify) do { \
|
||||
if (Condition) { \
|
||||
Exception UTIL_e; \
|
||||
UTIL_SET_LOCATION(UTIL_e, #Exception, #Condition); \
|
||||
UTIL_e << Modify; \
|
||||
throw UTIL_e; \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
class ErrnoException : public Exception {
|
||||
public:
|
||||
ErrnoException() throw();
|
||||
|
||||
virtual ~ErrnoException() throw();
|
||||
|
||||
int Error() const throw() { return errno_; }
|
||||
|
||||
private:
|
||||
int errno_;
|
||||
};
|
||||
|
||||
} // namespace util
|
||||
|
||||
#endif // UTIL_EXCEPTION__
|
330
trunk/kenlm/util/file_piece.cc
Normal file
330
trunk/kenlm/util/file_piece.cc
Normal file
@ -0,0 +1,330 @@
|
||||
#include "util/file_piece.hh"
|
||||
|
||||
#include "util/exception.hh"
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <limits>
|
||||
|
||||
#include <assert.h>
|
||||
#include <ctype.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifdef HAVE_ZLIB
|
||||
#include <zlib.h>
|
||||
#endif
|
||||
|
||||
namespace util {
|
||||
|
||||
EndOfFileException::EndOfFileException() throw() {
|
||||
*this << "End of file";
|
||||
}
|
||||
EndOfFileException::~EndOfFileException() throw() {}
|
||||
|
||||
ParseNumberException::ParseNumberException(StringPiece value) throw() {
|
||||
*this << "Could not parse \"" << value << "\" into a number";
|
||||
}
|
||||
|
||||
GZException::GZException(void *file) {
|
||||
#ifdef HAVE_ZLIB
|
||||
int num;
|
||||
*this << gzerror(file, &num) << " from zlib";
|
||||
#endif // HAVE_ZLIB
|
||||
}
|
||||
|
||||
// Sigh this is the only way I could come up with to do a _const_ bool. It has ' ', '\f', '\n', '\r', '\t', and '\v' (same as isspace on C locale).
|
||||
const bool kSpaces[256] = {0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
|
||||
|
||||
int OpenReadOrThrow(const char *name) {
|
||||
int ret;
|
||||
UTIL_THROW_IF(-1 == (ret = open(name, O_RDONLY)), ErrnoException, "while opening " << name);
|
||||
return ret;
|
||||
}
|
||||
|
||||
off_t SizeFile(int fd) {
|
||||
struct stat sb;
|
||||
if (fstat(fd, &sb) == -1 || (!sb.st_size && !S_ISREG(sb.st_mode))) return kBadSize;
|
||||
return sb.st_size;
|
||||
}
|
||||
|
||||
FilePiece::FilePiece(const char *name, std::ostream *show_progress, off_t min_buffer) :
|
||||
file_(OpenReadOrThrow(name)), total_size_(SizeFile(file_.get())), page_(sysconf(_SC_PAGE_SIZE)),
|
||||
progress_(total_size_ == kBadSize ? NULL : show_progress, std::string("Reading ") + name, total_size_) {
|
||||
Initialize(name, show_progress, min_buffer);
|
||||
}
|
||||
|
||||
FilePiece::FilePiece(int fd, const char *name, std::ostream *show_progress, off_t min_buffer) :
|
||||
file_(fd), total_size_(SizeFile(file_.get())), page_(sysconf(_SC_PAGE_SIZE)),
|
||||
progress_(total_size_ == kBadSize ? NULL : show_progress, std::string("Reading ") + name, total_size_) {
|
||||
Initialize(name, show_progress, min_buffer);
|
||||
}
|
||||
|
||||
FilePiece::~FilePiece() {
|
||||
#ifdef HAVE_ZLIB
|
||||
if (gz_file_) {
|
||||
// zlib took ownership
|
||||
file_.release();
|
||||
int ret;
|
||||
if (Z_OK != (ret = gzclose(gz_file_))) {
|
||||
std::cerr << "could not close file " << file_name_ << " using zlib" << std::endl;
|
||||
abort();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
StringPiece FilePiece::ReadLine(char delim) {
|
||||
size_t skip = 0;
|
||||
while (true) {
|
||||
for (const char *i = position_ + skip; i < position_end_; ++i) {
|
||||
if (*i == delim) {
|
||||
StringPiece ret(position_, i - position_);
|
||||
position_ = i + 1;
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
if (at_end_) {
|
||||
if (position_ == position_end_) Shift();
|
||||
return Consume(position_end_);
|
||||
}
|
||||
skip = position_end_ - position_;
|
||||
Shift();
|
||||
}
|
||||
}
|
||||
|
||||
float FilePiece::ReadFloat() {
|
||||
return ReadNumber<float>();
|
||||
}
|
||||
double FilePiece::ReadDouble() {
|
||||
return ReadNumber<double>();
|
||||
}
|
||||
long int FilePiece::ReadLong() {
|
||||
return ReadNumber<long int>();
|
||||
}
|
||||
unsigned long int FilePiece::ReadULong() {
|
||||
return ReadNumber<unsigned long int>();
|
||||
}
|
||||
|
||||
void FilePiece::Initialize(const char *name, std::ostream *show_progress, off_t min_buffer) {
|
||||
#ifdef HAVE_ZLIB
|
||||
gz_file_ = NULL;
|
||||
#endif
|
||||
file_name_ = name;
|
||||
|
||||
default_map_size_ = page_ * std::max<off_t>((min_buffer / page_ + 1), 2);
|
||||
position_ = NULL;
|
||||
position_end_ = NULL;
|
||||
mapped_offset_ = 0;
|
||||
at_end_ = false;
|
||||
|
||||
if (total_size_ == kBadSize) {
|
||||
// So the assertion passes.
|
||||
fallback_to_read_ = false;
|
||||
if (show_progress)
|
||||
*show_progress << "File " << name << " isn't normal. Using slower read() instead of mmap(). No progress bar." << std::endl;
|
||||
TransitionToRead();
|
||||
} else {
|
||||
fallback_to_read_ = false;
|
||||
}
|
||||
Shift();
|
||||
// gzip detect.
|
||||
if ((position_end_ - position_) > 2 && *position_ == 0x1f && static_cast<unsigned char>(*(position_ + 1)) == 0x8b) {
|
||||
#ifndef HAVE_ZLIB
|
||||
UTIL_THROW(GZException, "Looks like a gzip file but support was not compiled in.");
|
||||
#endif
|
||||
if (!fallback_to_read_) {
|
||||
at_end_ = false;
|
||||
TransitionToRead();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
void ParseNumber(const char *begin, char *&end, float &out) {
|
||||
#ifdef sun
|
||||
out = static_cast<float>(strtod(begin, &end));
|
||||
#else
|
||||
out = strtof(begin, &end);
|
||||
#endif
|
||||
}
|
||||
void ParseNumber(const char *begin, char *&end, double &out) {
|
||||
out = strtod(begin, &end);
|
||||
}
|
||||
void ParseNumber(const char *begin, char *&end, long int &out) {
|
||||
out = strtol(begin, &end, 10);
|
||||
}
|
||||
void ParseNumber(const char *begin, char *&end, unsigned long int &out) {
|
||||
out = strtoul(begin, &end, 10);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
template <class T> T FilePiece::ReadNumber() {
|
||||
SkipSpaces();
|
||||
while (last_space_ < position_) {
|
||||
if (at_end_) {
|
||||
// Hallucinate a null off the end of the file.
|
||||
std::string buffer(position_, position_end_);
|
||||
char *end;
|
||||
T ret;
|
||||
ParseNumber(buffer.c_str(), end, ret);
|
||||
if (buffer.c_str() == end) throw ParseNumberException(buffer);
|
||||
position_ += end - buffer.c_str();
|
||||
return ret;
|
||||
}
|
||||
Shift();
|
||||
}
|
||||
char *end;
|
||||
T ret;
|
||||
ParseNumber(position_, end, ret);
|
||||
if (end == position_) throw ParseNumberException(ReadDelimited());
|
||||
position_ = end;
|
||||
return ret;
|
||||
}
|
||||
|
||||
const char *FilePiece::FindDelimiterOrEOF(const bool *delim) {
|
||||
size_t skip = 0;
|
||||
while (true) {
|
||||
for (const char *i = position_ + skip; i < position_end_; ++i) {
|
||||
if (delim[static_cast<unsigned char>(*i)]) return i;
|
||||
}
|
||||
if (at_end_) {
|
||||
if (position_ == position_end_) Shift();
|
||||
return position_end_;
|
||||
}
|
||||
skip = position_end_ - position_;
|
||||
Shift();
|
||||
}
|
||||
}
|
||||
|
||||
void FilePiece::Shift() {
|
||||
if (at_end_) {
|
||||
progress_.Finished();
|
||||
throw EndOfFileException();
|
||||
}
|
||||
off_t desired_begin = position_ - data_.begin() + mapped_offset_;
|
||||
|
||||
if (!fallback_to_read_) MMapShift(desired_begin);
|
||||
// Notice an mmap failure might set the fallback.
|
||||
if (fallback_to_read_) ReadShift();
|
||||
|
||||
for (last_space_ = position_end_ - 1; last_space_ >= position_; --last_space_) {
|
||||
if (isspace(*last_space_)) break;
|
||||
}
|
||||
}
|
||||
|
||||
void FilePiece::MMapShift(off_t desired_begin) {
|
||||
// Use mmap.
|
||||
off_t ignore = desired_begin % page_;
|
||||
// Duplicate request for Shift means give more data.
|
||||
if (position_ == data_.begin() + ignore) {
|
||||
default_map_size_ *= 2;
|
||||
}
|
||||
// Local version so that in case of failure it doesn't overwrite the class variable.
|
||||
off_t mapped_offset = desired_begin - ignore;
|
||||
|
||||
off_t mapped_size;
|
||||
if (default_map_size_ >= static_cast<size_t>(total_size_ - mapped_offset)) {
|
||||
at_end_ = true;
|
||||
mapped_size = total_size_ - mapped_offset;
|
||||
} else {
|
||||
mapped_size = default_map_size_;
|
||||
}
|
||||
|
||||
// Forcibly clear the existing mmap first.
|
||||
data_.reset();
|
||||
data_.reset(mmap(NULL, mapped_size, PROT_READ, MAP_SHARED
|
||||
// Populate where available on linux
|
||||
#ifdef MAP_POPULATE
|
||||
| MAP_POPULATE
|
||||
#endif
|
||||
, *file_, mapped_offset), mapped_size, scoped_memory::MMAP_ALLOCATED);
|
||||
if (data_.get() == MAP_FAILED) {
|
||||
if (desired_begin) {
|
||||
if (((off_t)-1) == lseek(*file_, desired_begin, SEEK_SET)) UTIL_THROW(ErrnoException, "mmap failed even though it worked before. lseek failed too, so using read isn't an option either.");
|
||||
}
|
||||
// The mmap was scheduled to end the file, but now we're going to read it.
|
||||
at_end_ = false;
|
||||
TransitionToRead();
|
||||
return;
|
||||
}
|
||||
mapped_offset_ = mapped_offset;
|
||||
position_ = data_.begin() + ignore;
|
||||
position_end_ = data_.begin() + mapped_size;
|
||||
|
||||
progress_.Set(desired_begin);
|
||||
}
|
||||
|
||||
void FilePiece::TransitionToRead() {
|
||||
assert(!fallback_to_read_);
|
||||
fallback_to_read_ = true;
|
||||
data_.reset();
|
||||
data_.reset(malloc(default_map_size_), default_map_size_, scoped_memory::MALLOC_ALLOCATED);
|
||||
UTIL_THROW_IF(!data_.get(), ErrnoException, "malloc failed for " << default_map_size_);
|
||||
position_ = data_.begin();
|
||||
position_end_ = position_;
|
||||
|
||||
#ifdef HAVE_ZLIB
|
||||
assert(!gz_file_);
|
||||
gz_file_ = gzdopen(file_.get(), "r");
|
||||
UTIL_THROW_IF(!gz_file_, GZException, "zlib failed to open " << file_name_);
|
||||
#endif
|
||||
}
|
||||
|
||||
void FilePiece::ReadShift() {
|
||||
assert(fallback_to_read_);
|
||||
// Bytes [data_.begin(), position_) have been consumed.
|
||||
// Bytes [position_, position_end_) have been read into the buffer.
|
||||
|
||||
// Start at the beginning of the buffer if there's nothing useful in it.
|
||||
if (position_ == position_end_) {
|
||||
mapped_offset_ += (position_end_ - data_.begin());
|
||||
position_ = data_.begin();
|
||||
position_end_ = position_;
|
||||
}
|
||||
|
||||
std::size_t already_read = position_end_ - data_.begin();
|
||||
|
||||
if (already_read == default_map_size_) {
|
||||
if (position_ == data_.begin()) {
|
||||
// Buffer too small.
|
||||
std::size_t valid_length = position_end_ - position_;
|
||||
default_map_size_ *= 2;
|
||||
data_.call_realloc(default_map_size_);
|
||||
UTIL_THROW_IF(!data_.get(), ErrnoException, "realloc failed for " << default_map_size_);
|
||||
position_ = data_.begin();
|
||||
position_end_ = position_ + valid_length;
|
||||
} else {
|
||||
size_t moving = position_end_ - position_;
|
||||
memmove(data_.get(), position_, moving);
|
||||
position_ = data_.begin();
|
||||
position_end_ = position_ + moving;
|
||||
already_read = moving;
|
||||
}
|
||||
}
|
||||
|
||||
ssize_t read_return;
|
||||
#ifdef HAVE_ZLIB
|
||||
read_return = gzread(gz_file_, static_cast<char*>(data_.get()) + already_read, default_map_size_ - already_read);
|
||||
if (read_return == -1) throw GZException(gz_file_);
|
||||
if (total_size_ != kBadSize) {
|
||||
// Just get the position, don't actually seek. Apparently this is how you do it. . .
|
||||
off_t ret = lseek(file_.get(), 0, SEEK_CUR);
|
||||
if (ret != -1) progress_.Set(ret);
|
||||
}
|
||||
#else
|
||||
read_return = read(file_.get(), static_cast<char*>(data_.get()) + already_read, default_map_size_ - already_read);
|
||||
UTIL_THROW_IF(read_return == -1, ErrnoException, "read failed");
|
||||
progress_.Set(mapped_offset_);
|
||||
#endif
|
||||
if (read_return == 0) {
|
||||
at_end_ = true;
|
||||
}
|
||||
position_end_ += read_return;
|
||||
}
|
||||
|
||||
} // namespace util
|
137
trunk/kenlm/util/file_piece.hh
Normal file
137
trunk/kenlm/util/file_piece.hh
Normal file
@ -0,0 +1,137 @@
|
||||
#ifndef UTIL_FILE_PIECE__
|
||||
#define UTIL_FILE_PIECE__
|
||||
|
||||
#include "util/ersatz_progress.hh"
|
||||
#include "util/exception.hh"
|
||||
#include "util/have.hh"
|
||||
#include "util/mmap.hh"
|
||||
#include "util/scoped.hh"
|
||||
#include "util/string_piece.hh"
|
||||
|
||||
#include <string>
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
namespace util {
|
||||
|
||||
class EndOfFileException : public Exception {
|
||||
public:
|
||||
EndOfFileException() throw();
|
||||
~EndOfFileException() throw();
|
||||
};
|
||||
|
||||
class ParseNumberException : public Exception {
|
||||
public:
|
||||
explicit ParseNumberException(StringPiece value) throw();
|
||||
~ParseNumberException() throw() {}
|
||||
};
|
||||
|
||||
class GZException : public Exception {
|
||||
public:
|
||||
explicit GZException(void *file);
|
||||
GZException() throw() {}
|
||||
~GZException() throw() {}
|
||||
};
|
||||
|
||||
int OpenReadOrThrow(const char *name);
|
||||
|
||||
extern const bool kSpaces[256];
|
||||
|
||||
// Return value for SizeFile when it can't size properly.
|
||||
const off_t kBadSize = -1;
|
||||
off_t SizeFile(int fd);
|
||||
|
||||
// Memory backing the returned StringPiece may vanish on the next call.
|
||||
class FilePiece {
|
||||
public:
|
||||
// 32 MB default.
|
||||
explicit FilePiece(const char *file, std::ostream *show_progress = NULL, off_t min_buffer = 33554432);
|
||||
// Takes ownership of fd. name is used for messages.
|
||||
explicit FilePiece(int fd, const char *name, std::ostream *show_progress = NULL, off_t min_buffer = 33554432);
|
||||
|
||||
~FilePiece();
|
||||
|
||||
char get() {
|
||||
if (position_ == position_end_) {
|
||||
Shift();
|
||||
if (at_end_) throw EndOfFileException();
|
||||
}
|
||||
return *(position_++);
|
||||
}
|
||||
|
||||
// Leaves the delimiter, if any, to be returned by get(). Delimiters defined by isspace().
|
||||
StringPiece ReadDelimited(const bool *delim = kSpaces) {
|
||||
SkipSpaces(delim);
|
||||
return Consume(FindDelimiterOrEOF(delim));
|
||||
}
|
||||
|
||||
// Unlike ReadDelimited, this includes leading spaces and consumes the delimiter.
|
||||
// It is similar to getline in that way.
|
||||
StringPiece ReadLine(char delim = '\n');
|
||||
|
||||
float ReadFloat();
|
||||
double ReadDouble();
|
||||
long int ReadLong();
|
||||
unsigned long int ReadULong();
|
||||
|
||||
// Skip spaces defined by isspace.
|
||||
void SkipSpaces(const bool *delim = kSpaces) {
|
||||
for (; ; ++position_) {
|
||||
if (position_ == position_end_) Shift();
|
||||
if (!delim[static_cast<unsigned char>(*position_)]) return;
|
||||
}
|
||||
}
|
||||
|
||||
off_t Offset() const {
|
||||
return position_ - data_.begin() + mapped_offset_;
|
||||
}
|
||||
|
||||
const std::string &FileName() const { return file_name_; }
|
||||
|
||||
private:
|
||||
void Initialize(const char *name, std::ostream *show_progress, off_t min_buffer);
|
||||
|
||||
template <class T> T ReadNumber();
|
||||
|
||||
StringPiece Consume(const char *to) {
|
||||
StringPiece ret(position_, to - position_);
|
||||
position_ = to;
|
||||
return ret;
|
||||
}
|
||||
|
||||
const char *FindDelimiterOrEOF(const bool *delim = kSpaces);
|
||||
|
||||
void Shift();
|
||||
// Backends to Shift().
|
||||
void MMapShift(off_t desired_begin);
|
||||
|
||||
void TransitionToRead();
|
||||
void ReadShift();
|
||||
|
||||
const char *position_, *last_space_, *position_end_;
|
||||
|
||||
scoped_fd file_;
|
||||
const off_t total_size_;
|
||||
const off_t page_;
|
||||
|
||||
size_t default_map_size_;
|
||||
off_t mapped_offset_;
|
||||
|
||||
// Order matters: file_ should always be destroyed after this.
|
||||
scoped_memory data_;
|
||||
|
||||
bool at_end_;
|
||||
bool fallback_to_read_;
|
||||
|
||||
ErsatzProgress progress_;
|
||||
|
||||
std::string file_name_;
|
||||
|
||||
#ifdef HAVE_ZLIB
|
||||
void *gz_file_;
|
||||
#endif // HAVE_ZLIB
|
||||
};
|
||||
|
||||
} // namespace util
|
||||
|
||||
#endif // UTIL_FILE_PIECE__
|
102
trunk/kenlm/util/file_piece_test.cc
Normal file
102
trunk/kenlm/util/file_piece_test.cc
Normal file
@ -0,0 +1,102 @@
|
||||
#include "util/file_piece.hh"
|
||||
|
||||
#include "util/scoped.hh"
|
||||
|
||||
#define BOOST_TEST_MODULE FilePieceTest
|
||||
#include <boost/test/unit_test.hpp>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
|
||||
#include <stdio.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
namespace util {
|
||||
namespace {
|
||||
|
||||
/* mmap implementation */
|
||||
BOOST_AUTO_TEST_CASE(MMapReadLine) {
|
||||
std::fstream ref("file_piece.cc", std::ios::in);
|
||||
FilePiece test("file_piece.cc", NULL, 1);
|
||||
std::string ref_line;
|
||||
while (getline(ref, ref_line)) {
|
||||
StringPiece test_line(test.ReadLine());
|
||||
// I submitted a bug report to ICU: http://bugs.icu-project.org/trac/ticket/7924
|
||||
if (!test_line.empty() || !ref_line.empty()) {
|
||||
BOOST_CHECK_EQUAL(ref_line, test_line);
|
||||
}
|
||||
}
|
||||
BOOST_CHECK_THROW(test.get(), EndOfFileException);
|
||||
}
|
||||
|
||||
#ifndef __APPLE__
|
||||
/* Apple isn't happy with the popen, fileno, dup. And I don't want to
|
||||
* reimplement popen. This is an issue with the test.
|
||||
*/
|
||||
/* read() implementation */
|
||||
BOOST_AUTO_TEST_CASE(StreamReadLine) {
|
||||
std::fstream ref("file_piece.cc", std::ios::in);
|
||||
|
||||
FILE *catter = popen("cat file_piece.cc", "r");
|
||||
BOOST_REQUIRE(catter);
|
||||
|
||||
FilePiece test(dup(fileno(catter)), "file_piece.cc", NULL, 1);
|
||||
std::string ref_line;
|
||||
while (getline(ref, ref_line)) {
|
||||
StringPiece test_line(test.ReadLine());
|
||||
// I submitted a bug report to ICU: http://bugs.icu-project.org/trac/ticket/7924
|
||||
if (!test_line.empty() || !ref_line.empty()) {
|
||||
BOOST_CHECK_EQUAL(ref_line, test_line);
|
||||
}
|
||||
}
|
||||
BOOST_CHECK_THROW(test.get(), EndOfFileException);
|
||||
BOOST_REQUIRE(!pclose(catter));
|
||||
}
|
||||
#endif // __APPLE__
|
||||
|
||||
#ifdef HAVE_ZLIB
|
||||
|
||||
// gzip file
|
||||
BOOST_AUTO_TEST_CASE(PlainZipReadLine) {
|
||||
std::fstream ref("file_piece.cc", std::ios::in);
|
||||
|
||||
BOOST_REQUIRE_EQUAL(0, system("gzip <file_piece.cc >file_piece.cc.gz"));
|
||||
FilePiece test("file_piece.cc.gz", NULL, 1);
|
||||
std::string ref_line;
|
||||
while (getline(ref, ref_line)) {
|
||||
StringPiece test_line(test.ReadLine());
|
||||
// I submitted a bug report to ICU: http://bugs.icu-project.org/trac/ticket/7924
|
||||
if (!test_line.empty() || !ref_line.empty()) {
|
||||
BOOST_CHECK_EQUAL(ref_line, test_line);
|
||||
}
|
||||
}
|
||||
BOOST_CHECK_THROW(test.get(), EndOfFileException);
|
||||
}
|
||||
|
||||
// gzip stream. Apple doesn't like popen, fileno, dup. This is an issue with
|
||||
// the test.
|
||||
#ifndef __APPLE__
|
||||
BOOST_AUTO_TEST_CASE(StreamZipReadLine) {
|
||||
std::fstream ref("file_piece.cc", std::ios::in);
|
||||
|
||||
FILE * catter = popen("gzip <file_piece.cc", "r");
|
||||
BOOST_REQUIRE(catter);
|
||||
|
||||
FilePiece test(dup(fileno(catter)), "file_piece.cc", NULL, 1);
|
||||
std::string ref_line;
|
||||
while (getline(ref, ref_line)) {
|
||||
StringPiece test_line(test.ReadLine());
|
||||
// I submitted a bug report to ICU: http://bugs.icu-project.org/trac/ticket/7924
|
||||
if (!test_line.empty() || !ref_line.empty()) {
|
||||
BOOST_CHECK_EQUAL(ref_line, test_line);
|
||||
}
|
||||
}
|
||||
BOOST_CHECK_THROW(test.get(), EndOfFileException);
|
||||
BOOST_REQUIRE(!pclose(catter));
|
||||
}
|
||||
#endif // __APPLE__
|
||||
|
||||
#endif // HAVE_ZLIB
|
||||
|
||||
} // namespace
|
||||
} // namespace util
|
9
trunk/kenlm/util/have.hh
Normal file
9
trunk/kenlm/util/have.hh
Normal file
@ -0,0 +1,9 @@
|
||||
/* This ties kenlm's config into Moses's build system. If you are using kenlm
|
||||
* outside Moses, see http://kheafield.com/code/kenlm/developers/ .
|
||||
*/
|
||||
#ifndef UTIL_HAVE__
|
||||
#define UTIL_HAVE__
|
||||
|
||||
#define HAVE_ZLIB
|
||||
|
||||
#endif // UTIL_HAVE__
|
151
trunk/kenlm/util/joint_sort.hh
Normal file
151
trunk/kenlm/util/joint_sort.hh
Normal file
@ -0,0 +1,151 @@
|
||||
#ifndef UTIL_JOINT_SORT__
|
||||
#define UTIL_JOINT_SORT__
|
||||
|
||||
/* A terrifying amount of C++ to coax std::sort into soring one range while
|
||||
* also permuting another range the same way.
|
||||
*/
|
||||
|
||||
#include "util/proxy_iterator.hh"
|
||||
|
||||
#include <algorithm>
|
||||
#include <functional>
|
||||
#include <iostream>
|
||||
|
||||
namespace util {
|
||||
|
||||
namespace detail {
|
||||
|
||||
template <class KeyIter, class ValueIter> class JointProxy;
|
||||
|
||||
template <class KeyIter, class ValueIter> class JointIter {
|
||||
public:
|
||||
JointIter() {}
|
||||
|
||||
JointIter(const KeyIter &key_iter, const ValueIter &value_iter) : key_(key_iter), value_(value_iter) {}
|
||||
|
||||
bool operator==(const JointIter<KeyIter, ValueIter> &other) const { return key_ == other.key_; }
|
||||
|
||||
bool operator<(const JointIter<KeyIter, ValueIter> &other) const { return (key_ < other.key_); }
|
||||
|
||||
std::ptrdiff_t operator-(const JointIter<KeyIter, ValueIter> &other) const { return key_ - other.key_; }
|
||||
|
||||
JointIter<KeyIter, ValueIter> &operator+=(std::ptrdiff_t amount) {
|
||||
key_ += amount;
|
||||
value_ += amount;
|
||||
return *this;
|
||||
}
|
||||
|
||||
void swap(const JointIter &other) {
|
||||
std::swap(key_, other.key_);
|
||||
std::swap(value_, other.value_);
|
||||
}
|
||||
|
||||
private:
|
||||
friend class JointProxy<KeyIter, ValueIter>;
|
||||
KeyIter key_;
|
||||
ValueIter value_;
|
||||
};
|
||||
|
||||
template <class KeyIter, class ValueIter> class JointProxy {
|
||||
private:
|
||||
typedef JointIter<KeyIter, ValueIter> InnerIterator;
|
||||
|
||||
public:
|
||||
typedef struct {
|
||||
typename std::iterator_traits<KeyIter>::value_type key;
|
||||
typename std::iterator_traits<ValueIter>::value_type value;
|
||||
const typename std::iterator_traits<KeyIter>::value_type &GetKey() const { return key; }
|
||||
} value_type;
|
||||
|
||||
JointProxy(const KeyIter &key_iter, const ValueIter &value_iter) : inner_(key_iter, value_iter) {}
|
||||
JointProxy(const JointProxy<KeyIter, ValueIter> &other) : inner_(other.inner_) {}
|
||||
|
||||
operator const value_type() const {
|
||||
value_type ret;
|
||||
ret.key = *inner_.key_;
|
||||
ret.value = *inner_.value_;
|
||||
return ret;
|
||||
}
|
||||
|
||||
JointProxy &operator=(const JointProxy &other) {
|
||||
*inner_.key_ = *other.inner_.key_;
|
||||
*inner_.value_ = *other.inner_.value_;
|
||||
return *this;
|
||||
}
|
||||
|
||||
JointProxy &operator=(const value_type &other) {
|
||||
*inner_.key_ = other.key;
|
||||
*inner_.value_ = other.value;
|
||||
return *this;
|
||||
}
|
||||
|
||||
typename std::iterator_traits<KeyIter>::reference GetKey() const {
|
||||
return *(inner_.key_);
|
||||
}
|
||||
|
||||
void swap(JointProxy<KeyIter, ValueIter> &other) {
|
||||
std::swap(*inner_.key_, *other.inner_.key_);
|
||||
std::swap(*inner_.value_, *other.inner_.value_);
|
||||
}
|
||||
|
||||
private:
|
||||
friend class ProxyIterator<JointProxy<KeyIter, ValueIter> >;
|
||||
|
||||
InnerIterator &Inner() { return inner_; }
|
||||
const InnerIterator &Inner() const { return inner_; }
|
||||
InnerIterator inner_;
|
||||
};
|
||||
|
||||
template <class Proxy, class Less> class LessWrapper : public std::binary_function<const typename Proxy::value_type &, const typename Proxy::value_type &, bool> {
|
||||
public:
|
||||
explicit LessWrapper(const Less &less) : less_(less) {}
|
||||
|
||||
bool operator()(const Proxy &left, const Proxy &right) const {
|
||||
return less_(left.GetKey(), right.GetKey());
|
||||
}
|
||||
bool operator()(const Proxy &left, const typename Proxy::value_type &right) const {
|
||||
return less_(left.GetKey(), right.GetKey());
|
||||
}
|
||||
bool operator()(const typename Proxy::value_type &left, const Proxy &right) const {
|
||||
return less_(left.GetKey(), right.GetKey());
|
||||
}
|
||||
bool operator()(const typename Proxy::value_type &left, const typename Proxy::value_type &right) const {
|
||||
return less_(left.GetKey(), right.GetKey());
|
||||
}
|
||||
|
||||
private:
|
||||
const Less less_;
|
||||
};
|
||||
|
||||
} // namespace detail
|
||||
|
||||
template <class KeyIter, class ValueIter> class PairedIterator : public ProxyIterator<detail::JointProxy<KeyIter, ValueIter> > {
|
||||
public:
|
||||
PairedIterator(const KeyIter &key, const ValueIter &value) :
|
||||
ProxyIterator<detail::JointProxy<KeyIter, ValueIter> >(detail::JointProxy<KeyIter, ValueIter>(key, value)) {}
|
||||
};
|
||||
|
||||
template <class KeyIter, class ValueIter, class Less> void JointSort(const KeyIter &key_begin, const KeyIter &key_end, const ValueIter &value_begin, const Less &less) {
|
||||
ProxyIterator<detail::JointProxy<KeyIter, ValueIter> > full_begin(detail::JointProxy<KeyIter, ValueIter>(key_begin, value_begin));
|
||||
detail::LessWrapper<detail::JointProxy<KeyIter, ValueIter>, Less> less_wrap(less);
|
||||
std::sort(full_begin, full_begin + (key_end - key_begin), less_wrap);
|
||||
}
|
||||
|
||||
|
||||
template <class KeyIter, class ValueIter> void JointSort(const KeyIter &key_begin, const KeyIter &key_end, const ValueIter &value_begin) {
|
||||
JointSort(key_begin, key_end, value_begin, std::less<typename std::iterator_traits<KeyIter>::value_type>());
|
||||
}
|
||||
|
||||
} // namespace util
|
||||
|
||||
namespace std {
|
||||
template <class KeyIter, class ValueIter> void swap(util::detail::JointIter<KeyIter, ValueIter> &left, util::detail::JointIter<KeyIter, ValueIter> &right) {
|
||||
left.swap(right);
|
||||
}
|
||||
|
||||
template <class KeyIter, class ValueIter> void swap(util::detail::JointProxy<KeyIter, ValueIter> &left, util::detail::JointProxy<KeyIter, ValueIter> &right) {
|
||||
left.swap(right);
|
||||
}
|
||||
} // namespace std
|
||||
|
||||
#endif // UTIL_JOINT_SORT__
|
50
trunk/kenlm/util/joint_sort_test.cc
Normal file
50
trunk/kenlm/util/joint_sort_test.cc
Normal file
@ -0,0 +1,50 @@
|
||||
#include "util/joint_sort.hh"
|
||||
|
||||
#define BOOST_TEST_MODULE JointSortTest
|
||||
#include <boost/test/unit_test.hpp>
|
||||
|
||||
namespace util { namespace {
|
||||
|
||||
BOOST_AUTO_TEST_CASE(just_flip) {
|
||||
char keys[2];
|
||||
int values[2];
|
||||
keys[0] = 1; values[0] = 327;
|
||||
keys[1] = 0; values[1] = 87897;
|
||||
JointSort<char *, int *>(keys + 0, keys + 2, values + 0);
|
||||
BOOST_CHECK_EQUAL(0, keys[0]);
|
||||
BOOST_CHECK_EQUAL(87897, values[0]);
|
||||
BOOST_CHECK_EQUAL(1, keys[1]);
|
||||
BOOST_CHECK_EQUAL(327, values[1]);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(three) {
|
||||
char keys[3];
|
||||
int values[3];
|
||||
keys[0] = 1; values[0] = 327;
|
||||
keys[1] = 2; values[1] = 87897;
|
||||
keys[2] = 0; values[2] = 10;
|
||||
JointSort<char *, int *>(keys + 0, keys + 3, values + 0);
|
||||
BOOST_CHECK_EQUAL(0, keys[0]);
|
||||
BOOST_CHECK_EQUAL(1, keys[1]);
|
||||
BOOST_CHECK_EQUAL(2, keys[2]);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(char_int) {
|
||||
char keys[4];
|
||||
int values[4];
|
||||
keys[0] = 3; values[0] = 327;
|
||||
keys[1] = 1; values[1] = 87897;
|
||||
keys[2] = 2; values[2] = 10;
|
||||
keys[3] = 0; values[3] = 24347;
|
||||
JointSort<char *, int *>(keys + 0, keys + 4, values + 0);
|
||||
BOOST_CHECK_EQUAL(0, keys[0]);
|
||||
BOOST_CHECK_EQUAL(24347, values[0]);
|
||||
BOOST_CHECK_EQUAL(1, keys[1]);
|
||||
BOOST_CHECK_EQUAL(87897, values[1]);
|
||||
BOOST_CHECK_EQUAL(2, keys[2]);
|
||||
BOOST_CHECK_EQUAL(10, values[2]);
|
||||
BOOST_CHECK_EQUAL(3, keys[3]);
|
||||
BOOST_CHECK_EQUAL(327, values[3]);
|
||||
}
|
||||
|
||||
}} // namespace anonymous util
|
126
trunk/kenlm/util/key_value_packing.hh
Normal file
126
trunk/kenlm/util/key_value_packing.hh
Normal file
@ -0,0 +1,126 @@
|
||||
#ifndef UTIL_KEY_VALUE_PACKING__
|
||||
#define UTIL_KEY_VALUE_PACKING__
|
||||
|
||||
/* Why such a general interface? I'm planning on doing bit-level packing. */
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
|
||||
#include <inttypes.h>
|
||||
|
||||
namespace util {
|
||||
|
||||
template <class Key, class Value> struct Entry {
|
||||
Key key;
|
||||
Value value;
|
||||
|
||||
const Key &GetKey() const { return key; }
|
||||
const Value &GetValue() const { return value; }
|
||||
|
||||
Value &MutableValue() { return value; }
|
||||
|
||||
void Set(const Key &key_in, const Value &value_in) {
|
||||
SetKey(key_in);
|
||||
SetValue(value_in);
|
||||
}
|
||||
void SetKey(const Key &key_in) { key = key_in; }
|
||||
void SetValue(const Value &value_in) { value = value_in; }
|
||||
|
||||
bool operator<(const Entry<Key, Value> &other) const { return GetKey() < other.GetKey(); }
|
||||
};
|
||||
|
||||
// And now for a brief interlude to specialize std::swap.
|
||||
} // namespace util
|
||||
namespace std {
|
||||
template <class Key, class Value> void swap(util::Entry<Key, Value> &first, util::Entry<Key, Value> &second) {
|
||||
swap(first.key, second.key);
|
||||
swap(first.value, second.value);
|
||||
}
|
||||
}// namespace std
|
||||
namespace util {
|
||||
|
||||
template <class KeyT, class ValueT> class AlignedPacking {
|
||||
public:
|
||||
typedef KeyT Key;
|
||||
typedef ValueT Value;
|
||||
|
||||
public:
|
||||
static const std::size_t kBytes = sizeof(Entry<Key, Value>);
|
||||
static const std::size_t kBits = kBytes * 8;
|
||||
|
||||
typedef Entry<Key, Value> * MutableIterator;
|
||||
typedef const Entry<Key, Value> * ConstIterator;
|
||||
typedef const Entry<Key, Value> & ConstReference;
|
||||
|
||||
static MutableIterator FromVoid(void *start) {
|
||||
return reinterpret_cast<MutableIterator>(start);
|
||||
}
|
||||
|
||||
static Entry<Key, Value> Make(const Key &key, const Value &value) {
|
||||
Entry<Key, Value> ret;
|
||||
ret.Set(key, value);
|
||||
return ret;
|
||||
}
|
||||
};
|
||||
|
||||
template <class KeyT, class ValueT> class ByteAlignedPacking {
|
||||
public:
|
||||
typedef KeyT Key;
|
||||
typedef ValueT Value;
|
||||
|
||||
private:
|
||||
#pragma pack(push)
|
||||
#pragma pack(1)
|
||||
struct RawEntry {
|
||||
Key key;
|
||||
Value value;
|
||||
|
||||
const Key &GetKey() const { return key; }
|
||||
const Value &GetValue() const { return value; }
|
||||
|
||||
Value &MutableValue() { return value; }
|
||||
|
||||
void Set(const Key &key_in, const Value &value_in) {
|
||||
SetKey(key_in);
|
||||
SetValue(value_in);
|
||||
}
|
||||
void SetKey(const Key &key_in) { key = key_in; }
|
||||
void SetValue(const Value &value_in) { value = value_in; }
|
||||
|
||||
bool operator<(const RawEntry &other) const { return GetKey() < other.GetKey(); }
|
||||
};
|
||||
#pragma pack(pop)
|
||||
|
||||
friend void std::swap<>(RawEntry&, RawEntry&);
|
||||
|
||||
public:
|
||||
typedef RawEntry *MutableIterator;
|
||||
typedef const RawEntry *ConstIterator;
|
||||
typedef RawEntry &ConstReference;
|
||||
|
||||
static const std::size_t kBytes = sizeof(RawEntry);
|
||||
static const std::size_t kBits = kBytes * 8;
|
||||
|
||||
static MutableIterator FromVoid(void *start) {
|
||||
return MutableIterator(reinterpret_cast<RawEntry*>(start));
|
||||
}
|
||||
|
||||
static RawEntry Make(const Key &key, const Value &value) {
|
||||
RawEntry ret;
|
||||
ret.Set(key, value);
|
||||
return ret;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace util
|
||||
namespace std {
|
||||
template <class Key, class Value> void swap(
|
||||
typename util::ByteAlignedPacking<Key, Value>::RawEntry &first,
|
||||
typename util::ByteAlignedPacking<Key, Value>::RawEntry &second) {
|
||||
swap(first.key, second.key);
|
||||
swap(first.value, second.value);
|
||||
}
|
||||
}// namespace std
|
||||
|
||||
#endif // UTIL_KEY_VALUE_PACKING__
|
75
trunk/kenlm/util/key_value_packing_test.cc
Normal file
75
trunk/kenlm/util/key_value_packing_test.cc
Normal file
@ -0,0 +1,75 @@
|
||||
#include "util/key_value_packing.hh"
|
||||
|
||||
#include <boost/random/mersenne_twister.hpp>
|
||||
#include <boost/random/uniform_int.hpp>
|
||||
#include <boost/random/variate_generator.hpp>
|
||||
#include <boost/scoped_array.hpp>
|
||||
#define BOOST_TEST_MODULE KeyValueStoreTest
|
||||
#include <boost/test/unit_test.hpp>
|
||||
|
||||
#include <limits>
|
||||
#include <stdlib.h>
|
||||
|
||||
namespace util {
|
||||
namespace {
|
||||
|
||||
BOOST_AUTO_TEST_CASE(basic_in_out) {
|
||||
typedef ByteAlignedPacking<uint64_t, unsigned char> Packing;
|
||||
void *backing = malloc(Packing::kBytes * 2);
|
||||
Packing::MutableIterator i(Packing::FromVoid(backing));
|
||||
i->SetKey(10);
|
||||
BOOST_CHECK_EQUAL(10, i->GetKey());
|
||||
i->SetValue(3);
|
||||
BOOST_CHECK_EQUAL(3, i->GetValue());
|
||||
++i;
|
||||
i->SetKey(5);
|
||||
BOOST_CHECK_EQUAL(5, i->GetKey());
|
||||
i->SetValue(42);
|
||||
BOOST_CHECK_EQUAL(42, i->GetValue());
|
||||
|
||||
Packing::ConstIterator c(i);
|
||||
BOOST_CHECK_EQUAL(5, c->GetKey());
|
||||
--c;
|
||||
BOOST_CHECK_EQUAL(10, c->GetKey());
|
||||
BOOST_CHECK_EQUAL(42, i->GetValue());
|
||||
|
||||
BOOST_CHECK_EQUAL(5, i->GetKey());
|
||||
free(backing);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(simple_sort) {
|
||||
typedef ByteAlignedPacking<uint64_t, unsigned char> Packing;
|
||||
char foo[Packing::kBytes * 4];
|
||||
Packing::MutableIterator begin(Packing::FromVoid(foo));
|
||||
Packing::MutableIterator i = begin;
|
||||
i->SetKey(0); ++i;
|
||||
i->SetKey(2); ++i;
|
||||
i->SetKey(3); ++i;
|
||||
i->SetKey(1); ++i;
|
||||
std::sort(begin, i);
|
||||
BOOST_CHECK_EQUAL(0, begin[0].GetKey());
|
||||
BOOST_CHECK_EQUAL(1, begin[1].GetKey());
|
||||
BOOST_CHECK_EQUAL(2, begin[2].GetKey());
|
||||
BOOST_CHECK_EQUAL(3, begin[3].GetKey());
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(big_sort) {
|
||||
typedef ByteAlignedPacking<uint64_t, unsigned char> Packing;
|
||||
boost::scoped_array<char> memory(new char[Packing::kBytes * 1000]);
|
||||
Packing::MutableIterator begin(Packing::FromVoid(memory.get()));
|
||||
|
||||
boost::mt19937 rng;
|
||||
boost::uniform_int<uint64_t> range(0, std::numeric_limits<uint64_t>::max());
|
||||
boost::variate_generator<boost::mt19937&, boost::uniform_int<uint64_t> > gen(rng, range);
|
||||
|
||||
for (size_t i = 0; i < 1000; ++i) {
|
||||
(begin + i)->SetKey(gen());
|
||||
}
|
||||
std::sort(begin, begin + 1000);
|
||||
for (size_t i = 0; i < 999; ++i) {
|
||||
BOOST_CHECK(begin[i] < begin[i+1]);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace util
|
138
trunk/kenlm/util/mmap.cc
Normal file
138
trunk/kenlm/util/mmap.cc
Normal file
@ -0,0 +1,138 @@
|
||||
#include "util/exception.hh"
|
||||
#include "util/mmap.hh"
|
||||
#include "util/scoped.hh"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include <assert.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/mman.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace util {
|
||||
|
||||
scoped_mmap::~scoped_mmap() {
|
||||
if (data_ != (void*)-1) {
|
||||
// Thanks Denis Filimonov for pointing on NFS likes msync first.
|
||||
if (msync(data_, size_, MS_SYNC) || munmap(data_, size_)) {
|
||||
std::cerr << "msync or mmap failed for " << size_ << " bytes." << std::endl;
|
||||
abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void scoped_memory::reset(void *data, std::size_t size, Alloc source) {
|
||||
switch(source_) {
|
||||
case MMAP_ALLOCATED:
|
||||
scoped_mmap(data_, size_);
|
||||
break;
|
||||
case ARRAY_ALLOCATED:
|
||||
delete [] reinterpret_cast<char*>(data_);
|
||||
break;
|
||||
case MALLOC_ALLOCATED:
|
||||
free(data_);
|
||||
break;
|
||||
case NONE_ALLOCATED:
|
||||
break;
|
||||
}
|
||||
data_ = data;
|
||||
size_ = size;
|
||||
source_ = source;
|
||||
}
|
||||
|
||||
void scoped_memory::call_realloc(std::size_t size) {
|
||||
assert(source_ == MALLOC_ALLOCATED || source_ == NONE_ALLOCATED);
|
||||
void *new_data = realloc(data_, size);
|
||||
if (!new_data) {
|
||||
reset();
|
||||
} else {
|
||||
reset(new_data, size, MALLOC_ALLOCATED);
|
||||
}
|
||||
}
|
||||
|
||||
void *MapOrThrow(std::size_t size, bool for_write, int flags, bool prefault, int fd, off_t offset) {
|
||||
#ifdef MAP_POPULATE // Linux specific
|
||||
if (prefault) {
|
||||
flags |= MAP_POPULATE;
|
||||
}
|
||||
#endif
|
||||
int protect = for_write ? (PROT_READ | PROT_WRITE) : PROT_READ;
|
||||
void *ret = mmap(NULL, size, protect, flags, fd, offset);
|
||||
if (ret == MAP_FAILED) {
|
||||
UTIL_THROW(ErrnoException, "mmap failed for size " << size << " at offset " << offset);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
namespace {
|
||||
void ReadAll(int fd, void *to_void, std::size_t amount) {
|
||||
uint8_t *to = static_cast<uint8_t*>(to_void);
|
||||
while (amount) {
|
||||
ssize_t ret = read(fd, to, amount);
|
||||
if (ret == -1) UTIL_THROW(ErrnoException, "Reading " << amount << " from fd " << fd << " failed.");
|
||||
if (ret == 0) UTIL_THROW(Exception, "Hit EOF in fd " << fd << " but there should be " << amount << " more bytes to read.");
|
||||
amount -= ret;
|
||||
to += ret;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
const int kFileFlags =
|
||||
#ifdef MAP_FILE
|
||||
MAP_FILE | MAP_SHARED
|
||||
#else
|
||||
MAP_SHARED
|
||||
#endif
|
||||
;
|
||||
|
||||
void MapRead(LoadMethod method, int fd, off_t offset, std::size_t size, scoped_memory &out) {
|
||||
switch (method) {
|
||||
case LAZY:
|
||||
out.reset(MapOrThrow(size, false, kFileFlags, false, fd, offset), size, scoped_memory::MMAP_ALLOCATED);
|
||||
break;
|
||||
case POPULATE_OR_LAZY:
|
||||
#ifdef MAP_POPULATE
|
||||
case POPULATE_OR_READ:
|
||||
#endif
|
||||
out.reset(MapOrThrow(size, false, kFileFlags, true, fd, offset), size, scoped_memory::MMAP_ALLOCATED);
|
||||
break;
|
||||
#ifndef MAP_POPULATE
|
||||
case POPULATE_OR_READ:
|
||||
#endif
|
||||
case READ:
|
||||
out.reset(malloc(size), size, scoped_memory::MALLOC_ALLOCATED);
|
||||
if (!out.get()) UTIL_THROW(util::ErrnoException, "Allocating " << size << " bytes with malloc");
|
||||
if (-1 == lseek(fd, offset, SEEK_SET)) UTIL_THROW(ErrnoException, "lseek to " << offset << " in fd " << fd << " failed.");
|
||||
ReadAll(fd, out.get(), size);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void *MapAnonymous(std::size_t size) {
|
||||
return MapOrThrow(size, true,
|
||||
#ifdef MAP_ANONYMOUS
|
||||
MAP_ANONYMOUS // Linux
|
||||
#else
|
||||
MAP_ANON // BSD
|
||||
#endif
|
||||
| MAP_PRIVATE, false, -1, 0);
|
||||
}
|
||||
|
||||
void *MapZeroedWrite(const char *name, std::size_t size, scoped_fd &file) {
|
||||
file.reset(open(name, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
|
||||
if (-1 == file.get())
|
||||
UTIL_THROW(ErrnoException, "Failed to open " << name << " for writing");
|
||||
if (-1 == ftruncate(file.get(), size))
|
||||
UTIL_THROW(ErrnoException, "ftruncate on " << name << " to " << size << " failed");
|
||||
try {
|
||||
return MapOrThrow(size, true, kFileFlags, false, file.get(), 0);
|
||||
} catch (ErrnoException &e) {
|
||||
e << " in file " << name;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace util
|
108
trunk/kenlm/util/mmap.hh
Normal file
108
trunk/kenlm/util/mmap.hh
Normal file
@ -0,0 +1,108 @@
|
||||
#ifndef UTIL_MMAP__
|
||||
#define UTIL_MMAP__
|
||||
// Utilities for mmaped files.
|
||||
|
||||
#include "util/scoped.hh"
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
namespace util {
|
||||
|
||||
// (void*)-1 is MAP_FAILED; this is done to avoid including the mmap header here.
|
||||
class scoped_mmap {
|
||||
public:
|
||||
scoped_mmap() : data_((void*)-1), size_(0) {}
|
||||
scoped_mmap(void *data, std::size_t size) : data_(data), size_(size) {}
|
||||
~scoped_mmap();
|
||||
|
||||
void *get() const { return data_; }
|
||||
|
||||
const uint8_t *begin() const { return reinterpret_cast<uint8_t*>(data_); }
|
||||
const uint8_t *end() const { return reinterpret_cast<uint8_t*>(data_) + size_; }
|
||||
std::size_t size() const { return size_; }
|
||||
|
||||
void reset(void *data, std::size_t size) {
|
||||
scoped_mmap other(data_, size_);
|
||||
data_ = data;
|
||||
size_ = size;
|
||||
}
|
||||
|
||||
void reset() {
|
||||
reset((void*)-1, 0);
|
||||
}
|
||||
|
||||
private:
|
||||
void *data_;
|
||||
std::size_t size_;
|
||||
|
||||
scoped_mmap(const scoped_mmap &);
|
||||
scoped_mmap &operator=(const scoped_mmap &);
|
||||
};
|
||||
|
||||
/* For when the memory might come from mmap, new char[], or malloc. Uses NULL
|
||||
* and 0 for blanks even though mmap signals errors with (void*)-1). The reset
|
||||
* function checks that blank for mmap.
|
||||
*/
|
||||
class scoped_memory {
|
||||
public:
|
||||
typedef enum {MMAP_ALLOCATED, ARRAY_ALLOCATED, MALLOC_ALLOCATED, NONE_ALLOCATED} Alloc;
|
||||
|
||||
scoped_memory() : data_(NULL), size_(0), source_(NONE_ALLOCATED) {}
|
||||
|
||||
~scoped_memory() { reset(); }
|
||||
|
||||
void *get() const { return data_; }
|
||||
const char *begin() const { return reinterpret_cast<char*>(data_); }
|
||||
const char *end() const { return reinterpret_cast<char*>(data_) + size_; }
|
||||
std::size_t size() const { return size_; }
|
||||
|
||||
Alloc source() const { return source_; }
|
||||
|
||||
void reset() { reset(NULL, 0, NONE_ALLOCATED); }
|
||||
|
||||
void reset(void *data, std::size_t size, Alloc from);
|
||||
|
||||
// realloc allows the current data to escape hence the need for this call
|
||||
// If realloc fails, destroys the original too and get() returns NULL.
|
||||
void call_realloc(std::size_t to);
|
||||
|
||||
private:
|
||||
|
||||
void *data_;
|
||||
std::size_t size_;
|
||||
|
||||
Alloc source_;
|
||||
|
||||
scoped_memory(const scoped_memory &);
|
||||
scoped_memory &operator=(const scoped_memory &);
|
||||
};
|
||||
|
||||
typedef enum {
|
||||
// mmap with no prepopulate
|
||||
LAZY,
|
||||
// On linux, pass MAP_POPULATE to mmap.
|
||||
POPULATE_OR_LAZY,
|
||||
// Populate on Linux. malloc and read on non-Linux.
|
||||
POPULATE_OR_READ,
|
||||
// malloc and read.
|
||||
READ
|
||||
} LoadMethod;
|
||||
|
||||
extern const int kFileFlags;
|
||||
|
||||
// Wrapper around mmap to check it worked and hide some platform macros.
|
||||
void *MapOrThrow(std::size_t size, bool for_write, int flags, bool prefault, int fd, off_t offset = 0);
|
||||
|
||||
void MapRead(LoadMethod method, int fd, off_t offset, std::size_t size, scoped_memory &out);
|
||||
|
||||
void *MapAnonymous(std::size_t size);
|
||||
|
||||
// Open file name with mmap of size bytes, all of which are initially zero.
|
||||
void *MapZeroedWrite(const char *name, std::size_t size, scoped_fd &file);
|
||||
|
||||
} // namespace util
|
||||
|
||||
#endif // UTIL_MMAP__
|
129
trunk/kenlm/util/murmur_hash.cc
Normal file
129
trunk/kenlm/util/murmur_hash.cc
Normal file
@ -0,0 +1,129 @@
|
||||
/* Downloaded from http://sites.google.com/site/murmurhash/ which says "All
|
||||
* code is released to the public domain. For business purposes, Murmurhash is
|
||||
* under the MIT license."
|
||||
* This is modified from the original:
|
||||
* ULL tag on 0xc6a4a7935bd1e995 so this will compile on 32-bit.
|
||||
* length changed to unsigned int.
|
||||
* placed in namespace util
|
||||
* add MurmurHashNative
|
||||
* default option = 0 for seed
|
||||
*/
|
||||
|
||||
#include "util/murmur_hash.hh"
|
||||
|
||||
namespace util {
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// MurmurHash2, 64-bit versions, by Austin Appleby
|
||||
|
||||
// The same caveats as 32-bit MurmurHash2 apply here - beware of alignment
|
||||
// and endian-ness issues if used across multiple platforms.
|
||||
|
||||
// 64-bit hash for 64-bit platforms
|
||||
|
||||
uint64_t MurmurHash64A ( const void * key, std::size_t len, unsigned int seed )
|
||||
{
|
||||
const uint64_t m = 0xc6a4a7935bd1e995ULL;
|
||||
const int r = 47;
|
||||
|
||||
uint64_t h = seed ^ (len * m);
|
||||
|
||||
const uint64_t * data = (const uint64_t *)key;
|
||||
const uint64_t * end = data + (len/8);
|
||||
|
||||
while(data != end)
|
||||
{
|
||||
uint64_t k = *data++;
|
||||
|
||||
k *= m;
|
||||
k ^= k >> r;
|
||||
k *= m;
|
||||
|
||||
h ^= k;
|
||||
h *= m;
|
||||
}
|
||||
|
||||
const unsigned char * data2 = (const unsigned char*)data;
|
||||
|
||||
switch(len & 7)
|
||||
{
|
||||
case 7: h ^= uint64_t(data2[6]) << 48;
|
||||
case 6: h ^= uint64_t(data2[5]) << 40;
|
||||
case 5: h ^= uint64_t(data2[4]) << 32;
|
||||
case 4: h ^= uint64_t(data2[3]) << 24;
|
||||
case 3: h ^= uint64_t(data2[2]) << 16;
|
||||
case 2: h ^= uint64_t(data2[1]) << 8;
|
||||
case 1: h ^= uint64_t(data2[0]);
|
||||
h *= m;
|
||||
};
|
||||
|
||||
h ^= h >> r;
|
||||
h *= m;
|
||||
h ^= h >> r;
|
||||
|
||||
return h;
|
||||
}
|
||||
|
||||
|
||||
// 64-bit hash for 32-bit platforms
|
||||
|
||||
uint64_t MurmurHash64B ( const void * key, std::size_t len, unsigned int seed )
|
||||
{
|
||||
const unsigned int m = 0x5bd1e995;
|
||||
const int r = 24;
|
||||
|
||||
unsigned int h1 = seed ^ len;
|
||||
unsigned int h2 = 0;
|
||||
|
||||
const unsigned int * data = (const unsigned int *)key;
|
||||
|
||||
while(len >= 8)
|
||||
{
|
||||
unsigned int k1 = *data++;
|
||||
k1 *= m; k1 ^= k1 >> r; k1 *= m;
|
||||
h1 *= m; h1 ^= k1;
|
||||
len -= 4;
|
||||
|
||||
unsigned int k2 = *data++;
|
||||
k2 *= m; k2 ^= k2 >> r; k2 *= m;
|
||||
h2 *= m; h2 ^= k2;
|
||||
len -= 4;
|
||||
}
|
||||
|
||||
if(len >= 4)
|
||||
{
|
||||
unsigned int k1 = *data++;
|
||||
k1 *= m; k1 ^= k1 >> r; k1 *= m;
|
||||
h1 *= m; h1 ^= k1;
|
||||
len -= 4;
|
||||
}
|
||||
|
||||
switch(len)
|
||||
{
|
||||
case 3: h2 ^= ((unsigned char*)data)[2] << 16;
|
||||
case 2: h2 ^= ((unsigned char*)data)[1] << 8;
|
||||
case 1: h2 ^= ((unsigned char*)data)[0];
|
||||
h2 *= m;
|
||||
};
|
||||
|
||||
h1 ^= h2 >> 18; h1 *= m;
|
||||
h2 ^= h1 >> 22; h2 *= m;
|
||||
h1 ^= h2 >> 17; h1 *= m;
|
||||
h2 ^= h1 >> 19; h2 *= m;
|
||||
|
||||
uint64_t h = h1;
|
||||
|
||||
h = (h << 32) | h2;
|
||||
|
||||
return h;
|
||||
}
|
||||
|
||||
uint64_t MurmurHashNative(const void * key, std::size_t len, unsigned int seed) {
|
||||
if (sizeof(int) == 4) {
|
||||
return MurmurHash64B(key, len, seed);
|
||||
} else {
|
||||
return MurmurHash64A(key, len, seed);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace util
|
14
trunk/kenlm/util/murmur_hash.hh
Normal file
14
trunk/kenlm/util/murmur_hash.hh
Normal file
@ -0,0 +1,14 @@
|
||||
#ifndef UTIL_MURMUR_HASH__
|
||||
#define UTIL_MURMUR_HASH__
|
||||
#include <cstddef>
|
||||
#include <inttypes.h>
|
||||
|
||||
namespace util {
|
||||
|
||||
uint64_t MurmurHash64A(const void * key, std::size_t len, unsigned int seed = 0);
|
||||
uint64_t MurmurHash64B(const void * key, std::size_t len, unsigned int seed = 0);
|
||||
uint64_t MurmurHashNative(const void * key, std::size_t len, unsigned int seed = 0);
|
||||
|
||||
} // namespace util
|
||||
|
||||
#endif // UTIL_MURMUR_HASH__
|
117
trunk/kenlm/util/probing_hash_table.hh
Normal file
117
trunk/kenlm/util/probing_hash_table.hh
Normal file
@ -0,0 +1,117 @@
|
||||
#ifndef UTIL_PROBING_HASH_TABLE__
|
||||
#define UTIL_PROBING_HASH_TABLE__
|
||||
|
||||
#include "util/exception.hh"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
|
||||
#include <assert.h>
|
||||
|
||||
namespace util {
|
||||
|
||||
/* Thrown when table grows too large */
|
||||
class ProbingSizeException : public Exception {
|
||||
public:
|
||||
ProbingSizeException() throw() {}
|
||||
~ProbingSizeException() throw() {}
|
||||
};
|
||||
|
||||
/* Non-standard hash table
|
||||
* Buckets must be set at the beginning and must be greater than maximum number
|
||||
* of elements, else an infinite loop happens.
|
||||
* Memory management and initialization is externalized to make it easier to
|
||||
* serialize these to disk and load them quickly.
|
||||
* Uses linear probing to find value.
|
||||
* Only insert and lookup operations.
|
||||
*/
|
||||
|
||||
template <class PackingT, class HashT, class EqualT = std::equal_to<typename PackingT::Key> > class ProbingHashTable {
|
||||
public:
|
||||
typedef PackingT Packing;
|
||||
typedef typename Packing::Key Key;
|
||||
typedef typename Packing::MutableIterator MutableIterator;
|
||||
typedef typename Packing::ConstIterator ConstIterator;
|
||||
|
||||
typedef HashT Hash;
|
||||
typedef EqualT Equal;
|
||||
|
||||
static std::size_t Size(std::size_t entries, float multiplier) {
|
||||
return std::max(entries + 1, static_cast<std::size_t>(multiplier * static_cast<float>(entries))) * Packing::kBytes;
|
||||
}
|
||||
|
||||
// Must be assigned to later.
|
||||
ProbingHashTable() : entries_(0)
|
||||
#ifdef DEBUG
|
||||
, initialized_(false)
|
||||
#endif
|
||||
{}
|
||||
|
||||
ProbingHashTable(void *start, std::size_t allocated, const Key &invalid = Key(), const Hash &hash_func = Hash(), const Equal &equal_func = Equal())
|
||||
: begin_(Packing::FromVoid(start)),
|
||||
buckets_(allocated / Packing::kBytes),
|
||||
end_(begin_ + (allocated / Packing::kBytes)),
|
||||
invalid_(invalid),
|
||||
hash_(hash_func),
|
||||
equal_(equal_func),
|
||||
entries_(0)
|
||||
#ifdef DEBUG
|
||||
, initialized_(true)
|
||||
#endif
|
||||
{}
|
||||
|
||||
template <class T> void Insert(const T &t) {
|
||||
if (++entries_ >= buckets_)
|
||||
UTIL_THROW(ProbingSizeException, "Hash table with " << buckets_ << " buckets is full.");
|
||||
#ifdef DEBUG
|
||||
assert(initialized_);
|
||||
#endif
|
||||
for (MutableIterator i(begin_ + (hash_(t.GetKey()) % buckets_));;) {
|
||||
if (equal_(i->GetKey(), invalid_)) { *i = t; return; }
|
||||
if (++i == end_) { i = begin_; }
|
||||
}
|
||||
}
|
||||
|
||||
void FinishedInserting() {}
|
||||
|
||||
void LoadedBinary() {}
|
||||
|
||||
// Don't change anything related to GetKey,
|
||||
template <class Key> bool UnsafeMutableFind(const Key key, MutableIterator &out) {
|
||||
for (MutableIterator i(begin_ + (hash_(key) % buckets_));;) {
|
||||
Key got(i->GetKey());
|
||||
if (equal_(got, key)) { out = i; return true; }
|
||||
if (equal_(got, invalid_)) return false;
|
||||
if (++i == end_) i = begin_;
|
||||
}
|
||||
}
|
||||
|
||||
template <class Key> bool Find(const Key key, ConstIterator &out) const {
|
||||
#ifdef DEBUG
|
||||
assert(initialized_);
|
||||
#endif
|
||||
for (ConstIterator i(begin_ + (hash_(key) % buckets_));;) {
|
||||
Key got(i->GetKey());
|
||||
if (equal_(got, key)) { out = i; return true; }
|
||||
if (equal_(got, invalid_)) return false;
|
||||
if (++i == end_) i = begin_;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
MutableIterator begin_;
|
||||
std::size_t buckets_;
|
||||
MutableIterator end_;
|
||||
Key invalid_;
|
||||
Hash hash_;
|
||||
Equal equal_;
|
||||
std::size_t entries_;
|
||||
#ifdef DEBUG
|
||||
bool initialized_;
|
||||
#endif
|
||||
};
|
||||
|
||||
} // namespace util
|
||||
|
||||
#endif // UTIL_PROBING_HASH_TABLE__
|
30
trunk/kenlm/util/probing_hash_table_test.cc
Normal file
30
trunk/kenlm/util/probing_hash_table_test.cc
Normal file
@ -0,0 +1,30 @@
|
||||
#include "util/probing_hash_table.hh"
|
||||
|
||||
#include "util/key_value_packing.hh"
|
||||
|
||||
#define BOOST_TEST_MODULE ProbingHashTableTest
|
||||
#include <boost/test/unit_test.hpp>
|
||||
#include <boost/functional/hash.hpp>
|
||||
|
||||
namespace util {
|
||||
namespace {
|
||||
|
||||
typedef AlignedPacking<char, uint64_t> Packing;
|
||||
typedef ProbingHashTable<Packing, boost::hash<char> > Table;
|
||||
|
||||
BOOST_AUTO_TEST_CASE(simple) {
|
||||
char mem[Table::Size(10, 1.2)];
|
||||
memset(mem, 0, sizeof(mem));
|
||||
|
||||
Table table(mem, sizeof(mem));
|
||||
Packing::ConstIterator i = Packing::ConstIterator();
|
||||
BOOST_CHECK(!table.Find(2, i));
|
||||
table.Insert(Packing::Make(3, 328920));
|
||||
BOOST_REQUIRE(table.Find(3, i));
|
||||
BOOST_CHECK_EQUAL(3, i->GetKey());
|
||||
BOOST_CHECK_EQUAL(static_cast<uint64_t>(328920), i->GetValue());
|
||||
BOOST_CHECK(!table.Find(2, i));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace util
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user