Upload folder using huggingface_hub (part 3)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- examples/llama.swiftui/llama.swiftui.xcodeproj/project.pbxproj +449 -0
- examples/llama.swiftui/llama.swiftui.xcodeproj/project.xcworkspace/contents.xcworkspacedata +7 -0
- examples/llama.swiftui/llama.swiftui.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +8 -0
- examples/llama.swiftui/llama.swiftui/UI/LoadCustomButton.swift +44 -0
- examples/llama.swiftui/llama.swiftui/llama_swiftuiApp.swift +10 -0
- examples/llama.vim +783 -0
- examples/lookahead/CMakeLists.txt +5 -0
- examples/lookahead/README.md +13 -0
- examples/lookahead/lookahead.cpp +483 -0
- examples/lookup/CMakeLists.txt +23 -0
- examples/lookup/README.md +12 -0
- examples/lookup/lookup-create.cpp +45 -0
- examples/lookup/lookup-merge.cpp +50 -0
- examples/lookup/lookup-stats.cpp +160 -0
- examples/lookup/lookup.cpp +251 -0
- examples/model-conversion/.gitignore +3 -0
- examples/model-conversion/Makefile +239 -0
- examples/model-conversion/README.md +408 -0
- examples/model-conversion/requirements.txt +7 -0
- examples/model-conversion/scripts/causal/compare-embeddings-logits.sh +46 -0
- examples/model-conversion/scripts/causal/compare-logits.py +87 -0
- examples/model-conversion/scripts/causal/convert-model.sh +58 -0
- examples/model-conversion/scripts/causal/modelcard.template +13 -0
- examples/model-conversion/scripts/causal/run-casual-gen-embeddings-org.py +114 -0
- examples/model-conversion/scripts/causal/run-converted-model-embeddings-logits.sh +23 -0
- examples/model-conversion/scripts/causal/run-converted-model.sh +31 -0
- examples/model-conversion/scripts/causal/run-org-model.py +172 -0
- examples/model-conversion/scripts/embedding/compare-embeddings-logits.sh +84 -0
- examples/model-conversion/scripts/embedding/convert-model.sh +39 -0
- examples/model-conversion/scripts/embedding/modelcard.template +48 -0
- examples/model-conversion/scripts/embedding/run-converted-model.sh +55 -0
- examples/model-conversion/scripts/embedding/run-original-model.py +243 -0
- examples/model-conversion/scripts/utils/__init__.py +0 -0
- examples/model-conversion/scripts/utils/check-nmse.py +177 -0
- examples/model-conversion/scripts/utils/common.py +299 -0
- examples/model-conversion/scripts/utils/compare_tokens.py +76 -0
- examples/model-conversion/scripts/utils/create-collection-add-model.sh +8 -0
- examples/model-conversion/scripts/utils/curl-embedding-server.sh +6 -0
- examples/model-conversion/scripts/utils/hf-add-model-to-collection.py +80 -0
- examples/model-conversion/scripts/utils/hf-create-collection.py +106 -0
- examples/model-conversion/scripts/utils/hf-create-model.py +78 -0
- examples/model-conversion/scripts/utils/hf-upload-gguf-model.py +58 -0
- examples/model-conversion/scripts/utils/inspect-converted-model.sh +14 -0
- examples/model-conversion/scripts/utils/inspect-org-model.py +290 -0
- examples/model-conversion/scripts/utils/perplexity-gen.sh +40 -0
- examples/model-conversion/scripts/utils/perplexity-run-simple.sh +32 -0
- examples/model-conversion/scripts/utils/perplexity-run.sh +33 -0
- examples/model-conversion/scripts/utils/quantize.sh +53 -0
- examples/model-conversion/scripts/utils/run-embedding-server.sh +27 -0
- examples/model-conversion/scripts/utils/semantic_check.py +242 -0
examples/llama.swiftui/llama.swiftui.xcodeproj/project.pbxproj
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// !$*UTF8*$!
|
| 2 |
+
{
|
| 3 |
+
archiveVersion = 1;
|
| 4 |
+
classes = {
|
| 5 |
+
};
|
| 6 |
+
objectVersion = 56;
|
| 7 |
+
objects = {
|
| 8 |
+
|
| 9 |
+
/* Begin PBXBuildFile section */
|
| 10 |
+
549479CB2AC9E16000E0F78B /* Metal.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 549479CA2AC9E16000E0F78B /* Metal.framework */; };
|
| 11 |
+
79E1D9CD2B4CD16E005F8E46 /* InputButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79E1D9CC2B4CD16E005F8E46 /* InputButton.swift */; };
|
| 12 |
+
7FA3D2B32B2EA2F600543F92 /* DownloadButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FA3D2B22B2EA2F600543F92 /* DownloadButton.swift */; };
|
| 13 |
+
8A1C83772AC328BD0096AF73 /* llama_swiftuiApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A1C83762AC328BD0096AF73 /* llama_swiftuiApp.swift */; };
|
| 14 |
+
8A1C83792AC328BD0096AF73 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A1C83782AC328BD0096AF73 /* ContentView.swift */; };
|
| 15 |
+
8A1C837B2AC328BE0096AF73 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 8A1C837A2AC328BE0096AF73 /* Assets.xcassets */; };
|
| 16 |
+
8A39BE0A2AC7601100BFEB40 /* Accelerate.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8A39BE092AC7601000BFEB40 /* Accelerate.framework */; };
|
| 17 |
+
8A3F84242AC4C891005E2EE8 /* models in Resources */ = {isa = PBXBuildFile; fileRef = 8A3F84232AC4C891005E2EE8 /* models */; };
|
| 18 |
+
8A907F332AC7138A006146EA /* LibLlama.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A907F322AC7134E006146EA /* LibLlama.swift */; };
|
| 19 |
+
8A9F7C4D2AC332EE008AE1EA /* LlamaState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A9F7C4C2AC332EE008AE1EA /* LlamaState.swift */; };
|
| 20 |
+
DD84C9FD2D747FED007778EC /* llama.xcframework in Frameworks */ = {isa = PBXBuildFile; fileRef = DD84C9FC2D747FED007778EC /* llama.xcframework */; };
|
| 21 |
+
DD84C9FE2D747FED007778EC /* llama.xcframework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = DD84C9FC2D747FED007778EC /* llama.xcframework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
|
| 22 |
+
F1FE20E22B465ECA00B45541 /* LoadCustomButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1FE20E12B465EC900B45541 /* LoadCustomButton.swift */; };
|
| 23 |
+
/* End PBXBuildFile section */
|
| 24 |
+
|
| 25 |
+
/* Begin PBXCopyFilesBuildPhase section */
|
| 26 |
+
DD84C9FF2D747FED007778EC /* Embed Frameworks */ = {
|
| 27 |
+
isa = PBXCopyFilesBuildPhase;
|
| 28 |
+
buildActionMask = 2147483647;
|
| 29 |
+
dstPath = "";
|
| 30 |
+
dstSubfolderSpec = 10;
|
| 31 |
+
files = (
|
| 32 |
+
DD84C9FE2D747FED007778EC /* llama.xcframework in Embed Frameworks */,
|
| 33 |
+
);
|
| 34 |
+
name = "Embed Frameworks";
|
| 35 |
+
runOnlyForDeploymentPostprocessing = 0;
|
| 36 |
+
};
|
| 37 |
+
/* End PBXCopyFilesBuildPhase section */
|
| 38 |
+
|
| 39 |
+
/* Begin PBXFileReference section */
|
| 40 |
+
549479CA2AC9E16000E0F78B /* Metal.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Metal.framework; path = System/Library/Frameworks/Metal.framework; sourceTree = SDKROOT; };
|
| 41 |
+
79E1D9CC2B4CD16E005F8E46 /* InputButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InputButton.swift; sourceTree = "<group>"; };
|
| 42 |
+
7FA3D2B22B2EA2F600543F92 /* DownloadButton.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DownloadButton.swift; sourceTree = "<group>"; };
|
| 43 |
+
8A1C83732AC328BD0096AF73 /* llama.swiftui.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = llama.swiftui.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
| 44 |
+
8A1C83762AC328BD0096AF73 /* llama_swiftuiApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = llama_swiftuiApp.swift; sourceTree = "<group>"; };
|
| 45 |
+
8A1C83782AC328BD0096AF73 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = "<group>"; };
|
| 46 |
+
8A1C837A2AC328BE0096AF73 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
| 47 |
+
8A39BE092AC7601000BFEB40 /* Accelerate.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Accelerate.framework; path = System/Library/Frameworks/Accelerate.framework; sourceTree = SDKROOT; };
|
| 48 |
+
8A3F84232AC4C891005E2EE8 /* models */ = {isa = PBXFileReference; lastKnownFileType = folder; name = models; path = llama.swiftui/Resources/models; sourceTree = "<group>"; };
|
| 49 |
+
8A907F322AC7134E006146EA /* LibLlama.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LibLlama.swift; sourceTree = "<group>"; };
|
| 50 |
+
8A9F7C4C2AC332EE008AE1EA /* LlamaState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LlamaState.swift; sourceTree = "<group>"; };
|
| 51 |
+
DD84C9FC2D747FED007778EC /* llama.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = llama.xcframework; path = "../../build-apple/llama.xcframework"; sourceTree = "<group>"; };
|
| 52 |
+
DF2D2FE72B4A59BE00FCB72D /* llama.cpp */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = llama.cpp; path = ../..; sourceTree = "<group>"; };
|
| 53 |
+
F1FE20E12B465EC900B45541 /* LoadCustomButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoadCustomButton.swift; sourceTree = "<group>"; };
|
| 54 |
+
/* End PBXFileReference section */
|
| 55 |
+
|
| 56 |
+
/* Begin PBXFrameworksBuildPhase section */
|
| 57 |
+
8A1C83702AC328BD0096AF73 /* Frameworks */ = {
|
| 58 |
+
isa = PBXFrameworksBuildPhase;
|
| 59 |
+
buildActionMask = 2147483647;
|
| 60 |
+
files = (
|
| 61 |
+
549479CB2AC9E16000E0F78B /* Metal.framework in Frameworks */,
|
| 62 |
+
8A39BE0A2AC7601100BFEB40 /* Accelerate.framework in Frameworks */,
|
| 63 |
+
DD84C9FD2D747FED007778EC /* llama.xcframework in Frameworks */,
|
| 64 |
+
);
|
| 65 |
+
runOnlyForDeploymentPostprocessing = 0;
|
| 66 |
+
};
|
| 67 |
+
/* End PBXFrameworksBuildPhase section */
|
| 68 |
+
|
| 69 |
+
/* Begin PBXGroup section */
|
| 70 |
+
8A1C836A2AC328BD0096AF73 = {
|
| 71 |
+
isa = PBXGroup;
|
| 72 |
+
children = (
|
| 73 |
+
DF2D2FE72B4A59BE00FCB72D /* llama.cpp */,
|
| 74 |
+
8A907F312AC7134E006146EA /* llama.cpp.swift */,
|
| 75 |
+
8A3F84232AC4C891005E2EE8 /* models */,
|
| 76 |
+
8A1C83752AC328BD0096AF73 /* llama.swiftui */,
|
| 77 |
+
8A1C83742AC328BD0096AF73 /* Products */,
|
| 78 |
+
8A39BE082AC7601000BFEB40 /* Frameworks */,
|
| 79 |
+
);
|
| 80 |
+
sourceTree = "<group>";
|
| 81 |
+
};
|
| 82 |
+
8A1C83742AC328BD0096AF73 /* Products */ = {
|
| 83 |
+
isa = PBXGroup;
|
| 84 |
+
children = (
|
| 85 |
+
8A1C83732AC328BD0096AF73 /* llama.swiftui.app */,
|
| 86 |
+
);
|
| 87 |
+
name = Products;
|
| 88 |
+
sourceTree = "<group>";
|
| 89 |
+
};
|
| 90 |
+
8A1C83752AC328BD0096AF73 /* llama.swiftui */ = {
|
| 91 |
+
isa = PBXGroup;
|
| 92 |
+
children = (
|
| 93 |
+
8A3F84102AC4BD85005E2EE8 /* Resources */,
|
| 94 |
+
8A9F7C4B2AC332DC008AE1EA /* Models */,
|
| 95 |
+
8A9F7C4A2AC332BF008AE1EA /* UI */,
|
| 96 |
+
8A1C83762AC328BD0096AF73 /* llama_swiftuiApp.swift */,
|
| 97 |
+
8A1C837A2AC328BE0096AF73 /* Assets.xcassets */,
|
| 98 |
+
);
|
| 99 |
+
path = llama.swiftui;
|
| 100 |
+
sourceTree = "<group>";
|
| 101 |
+
};
|
| 102 |
+
8A39BE082AC7601000BFEB40 /* Frameworks */ = {
|
| 103 |
+
isa = PBXGroup;
|
| 104 |
+
children = (
|
| 105 |
+
DD84C9FC2D747FED007778EC /* llama.xcframework */,
|
| 106 |
+
549479CA2AC9E16000E0F78B /* Metal.framework */,
|
| 107 |
+
8A39BE092AC7601000BFEB40 /* Accelerate.framework */,
|
| 108 |
+
);
|
| 109 |
+
name = Frameworks;
|
| 110 |
+
sourceTree = "<group>";
|
| 111 |
+
};
|
| 112 |
+
8A3F84102AC4BD85005E2EE8 /* Resources */ = {
|
| 113 |
+
isa = PBXGroup;
|
| 114 |
+
children = (
|
| 115 |
+
8A3F84112AC4BD8C005E2EE8 /* models */,
|
| 116 |
+
);
|
| 117 |
+
path = Resources;
|
| 118 |
+
sourceTree = "<group>";
|
| 119 |
+
};
|
| 120 |
+
8A3F84112AC4BD8C005E2EE8 /* models */ = {
|
| 121 |
+
isa = PBXGroup;
|
| 122 |
+
children = (
|
| 123 |
+
);
|
| 124 |
+
path = models;
|
| 125 |
+
sourceTree = "<group>";
|
| 126 |
+
};
|
| 127 |
+
8A907F312AC7134E006146EA /* llama.cpp.swift */ = {
|
| 128 |
+
isa = PBXGroup;
|
| 129 |
+
children = (
|
| 130 |
+
8A907F322AC7134E006146EA /* LibLlama.swift */,
|
| 131 |
+
);
|
| 132 |
+
path = llama.cpp.swift;
|
| 133 |
+
sourceTree = "<group>";
|
| 134 |
+
};
|
| 135 |
+
8A9F7C4A2AC332BF008AE1EA /* UI */ = {
|
| 136 |
+
isa = PBXGroup;
|
| 137 |
+
children = (
|
| 138 |
+
7FA3D2B22B2EA2F600543F92 /* DownloadButton.swift */,
|
| 139 |
+
8A1C83782AC328BD0096AF73 /* ContentView.swift */,
|
| 140 |
+
F1FE20E12B465EC900B45541 /* LoadCustomButton.swift */,
|
| 141 |
+
79E1D9CC2B4CD16E005F8E46 /* InputButton.swift */,
|
| 142 |
+
);
|
| 143 |
+
path = UI;
|
| 144 |
+
sourceTree = "<group>";
|
| 145 |
+
};
|
| 146 |
+
8A9F7C4B2AC332DC008AE1EA /* Models */ = {
|
| 147 |
+
isa = PBXGroup;
|
| 148 |
+
children = (
|
| 149 |
+
8A9F7C4C2AC332EE008AE1EA /* LlamaState.swift */,
|
| 150 |
+
);
|
| 151 |
+
path = Models;
|
| 152 |
+
sourceTree = "<group>";
|
| 153 |
+
};
|
| 154 |
+
/* End PBXGroup section */
|
| 155 |
+
|
| 156 |
+
/* Begin PBXNativeTarget section */
|
| 157 |
+
8A1C83722AC328BD0096AF73 /* llama.swiftui */ = {
|
| 158 |
+
isa = PBXNativeTarget;
|
| 159 |
+
buildConfigurationList = 8A1C83812AC328BE0096AF73 /* Build configuration list for PBXNativeTarget "llama.swiftui" */;
|
| 160 |
+
buildPhases = (
|
| 161 |
+
8A1C836F2AC328BD0096AF73 /* Sources */,
|
| 162 |
+
8A1C83702AC328BD0096AF73 /* Frameworks */,
|
| 163 |
+
8A1C83712AC328BD0096AF73 /* Resources */,
|
| 164 |
+
DD84C9FF2D747FED007778EC /* Embed Frameworks */,
|
| 165 |
+
);
|
| 166 |
+
buildRules = (
|
| 167 |
+
);
|
| 168 |
+
dependencies = (
|
| 169 |
+
);
|
| 170 |
+
name = llama.swiftui;
|
| 171 |
+
packageProductDependencies = (
|
| 172 |
+
);
|
| 173 |
+
productName = llama.swiftui;
|
| 174 |
+
productReference = 8A1C83732AC328BD0096AF73 /* llama.swiftui.app */;
|
| 175 |
+
productType = "com.apple.product-type.application";
|
| 176 |
+
};
|
| 177 |
+
/* End PBXNativeTarget section */
|
| 178 |
+
|
| 179 |
+
/* Begin PBXProject section */
|
| 180 |
+
8A1C836B2AC328BD0096AF73 /* Project object */ = {
|
| 181 |
+
isa = PBXProject;
|
| 182 |
+
attributes = {
|
| 183 |
+
BuildIndependentTargetsInParallel = 1;
|
| 184 |
+
LastSwiftUpdateCheck = 1500;
|
| 185 |
+
LastUpgradeCheck = 1500;
|
| 186 |
+
TargetAttributes = {
|
| 187 |
+
8A1C83722AC328BD0096AF73 = {
|
| 188 |
+
CreatedOnToolsVersion = 15.0;
|
| 189 |
+
LastSwiftMigration = 1500;
|
| 190 |
+
};
|
| 191 |
+
};
|
| 192 |
+
};
|
| 193 |
+
buildConfigurationList = 8A1C836E2AC328BD0096AF73 /* Build configuration list for PBXProject "llama.swiftui" */;
|
| 194 |
+
compatibilityVersion = "Xcode 14.0";
|
| 195 |
+
developmentRegion = en;
|
| 196 |
+
hasScannedForEncodings = 0;
|
| 197 |
+
knownRegions = (
|
| 198 |
+
en,
|
| 199 |
+
Base,
|
| 200 |
+
);
|
| 201 |
+
mainGroup = 8A1C836A2AC328BD0096AF73;
|
| 202 |
+
packageReferences = (
|
| 203 |
+
);
|
| 204 |
+
productRefGroup = 8A1C83742AC328BD0096AF73 /* Products */;
|
| 205 |
+
projectDirPath = "";
|
| 206 |
+
projectRoot = "";
|
| 207 |
+
targets = (
|
| 208 |
+
8A1C83722AC328BD0096AF73 /* llama.swiftui */,
|
| 209 |
+
);
|
| 210 |
+
};
|
| 211 |
+
/* End PBXProject section */
|
| 212 |
+
|
| 213 |
+
/* Begin PBXResourcesBuildPhase section */
|
| 214 |
+
8A1C83712AC328BD0096AF73 /* Resources */ = {
|
| 215 |
+
isa = PBXResourcesBuildPhase;
|
| 216 |
+
buildActionMask = 2147483647;
|
| 217 |
+
files = (
|
| 218 |
+
8A3F84242AC4C891005E2EE8 /* models in Resources */,
|
| 219 |
+
8A1C837B2AC328BE0096AF73 /* Assets.xcassets in Resources */,
|
| 220 |
+
);
|
| 221 |
+
runOnlyForDeploymentPostprocessing = 0;
|
| 222 |
+
};
|
| 223 |
+
/* End PBXResourcesBuildPhase section */
|
| 224 |
+
|
| 225 |
+
/* Begin PBXSourcesBuildPhase section */
|
| 226 |
+
8A1C836F2AC328BD0096AF73 /* Sources */ = {
|
| 227 |
+
isa = PBXSourcesBuildPhase;
|
| 228 |
+
buildActionMask = 2147483647;
|
| 229 |
+
files = (
|
| 230 |
+
F1FE20E22B465ECA00B45541 /* LoadCustomButton.swift in Sources */,
|
| 231 |
+
8A907F332AC7138A006146EA /* LibLlama.swift in Sources */,
|
| 232 |
+
8A9F7C4D2AC332EE008AE1EA /* LlamaState.swift in Sources */,
|
| 233 |
+
8A1C83792AC328BD0096AF73 /* ContentView.swift in Sources */,
|
| 234 |
+
8A1C83772AC328BD0096AF73 /* llama_swiftuiApp.swift in Sources */,
|
| 235 |
+
7FA3D2B32B2EA2F600543F92 /* DownloadButton.swift in Sources */,
|
| 236 |
+
79E1D9CD2B4CD16E005F8E46 /* InputButton.swift in Sources */,
|
| 237 |
+
);
|
| 238 |
+
runOnlyForDeploymentPostprocessing = 0;
|
| 239 |
+
};
|
| 240 |
+
/* End PBXSourcesBuildPhase section */
|
| 241 |
+
|
| 242 |
+
/* Begin XCBuildConfiguration section */
|
| 243 |
+
8A1C837F2AC328BE0096AF73 /* Debug */ = {
|
| 244 |
+
isa = XCBuildConfiguration;
|
| 245 |
+
buildSettings = {
|
| 246 |
+
ALWAYS_SEARCH_USER_PATHS = NO;
|
| 247 |
+
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
|
| 248 |
+
CLANG_ANALYZER_NONNULL = YES;
|
| 249 |
+
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
| 250 |
+
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
| 251 |
+
CLANG_ENABLE_MODULES = YES;
|
| 252 |
+
CLANG_ENABLE_OBJC_ARC = YES;
|
| 253 |
+
CLANG_ENABLE_OBJC_WEAK = YES;
|
| 254 |
+
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
| 255 |
+
CLANG_WARN_BOOL_CONVERSION = YES;
|
| 256 |
+
CLANG_WARN_COMMA = YES;
|
| 257 |
+
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
| 258 |
+
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
| 259 |
+
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
| 260 |
+
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
| 261 |
+
CLANG_WARN_EMPTY_BODY = YES;
|
| 262 |
+
CLANG_WARN_ENUM_CONVERSION = YES;
|
| 263 |
+
CLANG_WARN_INFINITE_RECURSION = YES;
|
| 264 |
+
CLANG_WARN_INT_CONVERSION = YES;
|
| 265 |
+
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
| 266 |
+
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
| 267 |
+
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
| 268 |
+
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
| 269 |
+
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
|
| 270 |
+
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
| 271 |
+
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
| 272 |
+
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
| 273 |
+
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
|
| 274 |
+
CLANG_WARN_UNREACHABLE_CODE = YES;
|
| 275 |
+
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
| 276 |
+
COPY_PHASE_STRIP = NO;
|
| 277 |
+
DEBUG_INFORMATION_FORMAT = dwarf;
|
| 278 |
+
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
| 279 |
+
ENABLE_TESTABILITY = YES;
|
| 280 |
+
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
| 281 |
+
GCC_C_LANGUAGE_STANDARD = gnu17;
|
| 282 |
+
GCC_DYNAMIC_NO_PIC = NO;
|
| 283 |
+
GCC_NO_COMMON_BLOCKS = YES;
|
| 284 |
+
GCC_OPTIMIZATION_LEVEL = 0;
|
| 285 |
+
GCC_PREPROCESSOR_DEFINITIONS = (
|
| 286 |
+
"DEBUG=1",
|
| 287 |
+
"$(inherited)",
|
| 288 |
+
);
|
| 289 |
+
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
| 290 |
+
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
| 291 |
+
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
| 292 |
+
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
| 293 |
+
GCC_WARN_UNUSED_FUNCTION = YES;
|
| 294 |
+
GCC_WARN_UNUSED_VARIABLE = YES;
|
| 295 |
+
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
| 296 |
+
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
|
| 297 |
+
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
|
| 298 |
+
MTL_FAST_MATH = YES;
|
| 299 |
+
ONLY_ACTIVE_ARCH = YES;
|
| 300 |
+
SDKROOT = iphoneos;
|
| 301 |
+
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
|
| 302 |
+
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
| 303 |
+
};
|
| 304 |
+
name = Debug;
|
| 305 |
+
};
|
| 306 |
+
8A1C83802AC328BE0096AF73 /* Release */ = {
|
| 307 |
+
isa = XCBuildConfiguration;
|
| 308 |
+
buildSettings = {
|
| 309 |
+
ALWAYS_SEARCH_USER_PATHS = NO;
|
| 310 |
+
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
|
| 311 |
+
CLANG_ANALYZER_NONNULL = YES;
|
| 312 |
+
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
| 313 |
+
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
| 314 |
+
CLANG_ENABLE_MODULES = YES;
|
| 315 |
+
CLANG_ENABLE_OBJC_ARC = YES;
|
| 316 |
+
CLANG_ENABLE_OBJC_WEAK = YES;
|
| 317 |
+
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
| 318 |
+
CLANG_WARN_BOOL_CONVERSION = YES;
|
| 319 |
+
CLANG_WARN_COMMA = YES;
|
| 320 |
+
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
| 321 |
+
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
| 322 |
+
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
| 323 |
+
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
| 324 |
+
CLANG_WARN_EMPTY_BODY = YES;
|
| 325 |
+
CLANG_WARN_ENUM_CONVERSION = YES;
|
| 326 |
+
CLANG_WARN_INFINITE_RECURSION = YES;
|
| 327 |
+
CLANG_WARN_INT_CONVERSION = YES;
|
| 328 |
+
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
| 329 |
+
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
| 330 |
+
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
| 331 |
+
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
| 332 |
+
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
|
| 333 |
+
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
| 334 |
+
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
| 335 |
+
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
| 336 |
+
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
|
| 337 |
+
CLANG_WARN_UNREACHABLE_CODE = YES;
|
| 338 |
+
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
| 339 |
+
COPY_PHASE_STRIP = NO;
|
| 340 |
+
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
| 341 |
+
ENABLE_NS_ASSERTIONS = NO;
|
| 342 |
+
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
| 343 |
+
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
| 344 |
+
GCC_C_LANGUAGE_STANDARD = gnu17;
|
| 345 |
+
GCC_NO_COMMON_BLOCKS = YES;
|
| 346 |
+
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
| 347 |
+
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
| 348 |
+
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
| 349 |
+
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
| 350 |
+
GCC_WARN_UNUSED_FUNCTION = YES;
|
| 351 |
+
GCC_WARN_UNUSED_VARIABLE = YES;
|
| 352 |
+
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
| 353 |
+
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
|
| 354 |
+
MTL_ENABLE_DEBUG_INFO = NO;
|
| 355 |
+
MTL_FAST_MATH = YES;
|
| 356 |
+
SDKROOT = iphoneos;
|
| 357 |
+
SWIFT_COMPILATION_MODE = wholemodule;
|
| 358 |
+
VALIDATE_PRODUCT = YES;
|
| 359 |
+
};
|
| 360 |
+
name = Release;
|
| 361 |
+
};
|
| 362 |
+
8A1C83822AC328BE0096AF73 /* Debug */ = {
|
| 363 |
+
isa = XCBuildConfiguration;
|
| 364 |
+
buildSettings = {
|
| 365 |
+
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
| 366 |
+
CLANG_ENABLE_MODULES = YES;
|
| 367 |
+
CODE_SIGN_STYLE = Automatic;
|
| 368 |
+
CURRENT_PROJECT_VERSION = 1;
|
| 369 |
+
DEVELOPMENT_TEAM = K5UQJPP73A;
|
| 370 |
+
ENABLE_PREVIEWS = YES;
|
| 371 |
+
GENERATE_INFOPLIST_FILE = YES;
|
| 372 |
+
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
|
| 373 |
+
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
|
| 374 |
+
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
|
| 375 |
+
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
|
| 376 |
+
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
|
| 377 |
+
IPHONEOS_DEPLOYMENT_TARGET = 16.0;
|
| 378 |
+
LD_RUNPATH_SEARCH_PATHS = (
|
| 379 |
+
"$(inherited)",
|
| 380 |
+
"@executable_path/Frameworks",
|
| 381 |
+
);
|
| 382 |
+
MARKETING_VERSION = 1.0;
|
| 383 |
+
PRODUCT_BUNDLE_IDENTIFIER = "com.bachittle.llama-swift";
|
| 384 |
+
PRODUCT_NAME = "$(TARGET_NAME)";
|
| 385 |
+
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator xros xrsimulator";
|
| 386 |
+
SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO;
|
| 387 |
+
SWIFT_EMIT_LOC_STRINGS = YES;
|
| 388 |
+
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
| 389 |
+
SWIFT_VERSION = 5.0;
|
| 390 |
+
TARGETED_DEVICE_FAMILY = "1,2,7";
|
| 391 |
+
};
|
| 392 |
+
name = Debug;
|
| 393 |
+
};
|
| 394 |
+
8A1C83832AC328BE0096AF73 /* Release */ = {
|
| 395 |
+
isa = XCBuildConfiguration;
|
| 396 |
+
buildSettings = {
|
| 397 |
+
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
| 398 |
+
CLANG_ENABLE_MODULES = YES;
|
| 399 |
+
CODE_SIGN_STYLE = Automatic;
|
| 400 |
+
CURRENT_PROJECT_VERSION = 1;
|
| 401 |
+
DEVELOPMENT_TEAM = K5UQJPP73A;
|
| 402 |
+
ENABLE_PREVIEWS = YES;
|
| 403 |
+
GENERATE_INFOPLIST_FILE = YES;
|
| 404 |
+
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
|
| 405 |
+
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
|
| 406 |
+
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
|
| 407 |
+
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
|
| 408 |
+
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
|
| 409 |
+
IPHONEOS_DEPLOYMENT_TARGET = 16.0;
|
| 410 |
+
LD_RUNPATH_SEARCH_PATHS = (
|
| 411 |
+
"$(inherited)",
|
| 412 |
+
"@executable_path/Frameworks",
|
| 413 |
+
);
|
| 414 |
+
MARKETING_VERSION = 1.0;
|
| 415 |
+
PRODUCT_BUNDLE_IDENTIFIER = "com.bachittle.llama-swift";
|
| 416 |
+
PRODUCT_NAME = "$(TARGET_NAME)";
|
| 417 |
+
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator xros xrsimulator";
|
| 418 |
+
SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO;
|
| 419 |
+
SWIFT_EMIT_LOC_STRINGS = YES;
|
| 420 |
+
SWIFT_VERSION = 5.0;
|
| 421 |
+
TARGETED_DEVICE_FAMILY = "1,2,7";
|
| 422 |
+
};
|
| 423 |
+
name = Release;
|
| 424 |
+
};
|
| 425 |
+
/* End XCBuildConfiguration section */
|
| 426 |
+
|
| 427 |
+
/* Begin XCConfigurationList section */
|
| 428 |
+
8A1C836E2AC328BD0096AF73 /* Build configuration list for PBXProject "llama.swiftui" */ = {
|
| 429 |
+
isa = XCConfigurationList;
|
| 430 |
+
buildConfigurations = (
|
| 431 |
+
8A1C837F2AC328BE0096AF73 /* Debug */,
|
| 432 |
+
8A1C83802AC328BE0096AF73 /* Release */,
|
| 433 |
+
);
|
| 434 |
+
defaultConfigurationIsVisible = 0;
|
| 435 |
+
defaultConfigurationName = Release;
|
| 436 |
+
};
|
| 437 |
+
8A1C83812AC328BE0096AF73 /* Build configuration list for PBXNativeTarget "llama.swiftui" */ = {
|
| 438 |
+
isa = XCConfigurationList;
|
| 439 |
+
buildConfigurations = (
|
| 440 |
+
8A1C83822AC328BE0096AF73 /* Debug */,
|
| 441 |
+
8A1C83832AC328BE0096AF73 /* Release */,
|
| 442 |
+
);
|
| 443 |
+
defaultConfigurationIsVisible = 0;
|
| 444 |
+
defaultConfigurationName = Release;
|
| 445 |
+
};
|
| 446 |
+
/* End XCConfigurationList section */
|
| 447 |
+
};
|
| 448 |
+
rootObject = 8A1C836B2AC328BD0096AF73 /* Project object */;
|
| 449 |
+
}
|
examples/llama.swiftui/llama.swiftui.xcodeproj/project.xcworkspace/contents.xcworkspacedata
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
| 2 |
+
<Workspace
|
| 3 |
+
version = "1.0">
|
| 4 |
+
<FileRef
|
| 5 |
+
location = "self:">
|
| 6 |
+
</FileRef>
|
| 7 |
+
</Workspace>
|
examples/llama.swiftui/llama.swiftui.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
| 2 |
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
| 3 |
+
<plist version="1.0">
|
| 4 |
+
<dict>
|
| 5 |
+
<key>IDEDidComputeMac32BitWarning</key>
|
| 6 |
+
<true/>
|
| 7 |
+
</dict>
|
| 8 |
+
</plist>
|
examples/llama.swiftui/llama.swiftui/UI/LoadCustomButton.swift
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import SwiftUI
|
| 2 |
+
import UniformTypeIdentifiers
|
| 3 |
+
|
| 4 |
+
struct LoadCustomButton: View {
|
| 5 |
+
@ObservedObject private var llamaState: LlamaState
|
| 6 |
+
@State private var showFileImporter = false
|
| 7 |
+
|
| 8 |
+
init(llamaState: LlamaState) {
|
| 9 |
+
self.llamaState = llamaState
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
var body: some View {
|
| 13 |
+
VStack {
|
| 14 |
+
Button(action: {
|
| 15 |
+
showFileImporter = true
|
| 16 |
+
}) {
|
| 17 |
+
Text("Load Custom Model")
|
| 18 |
+
}
|
| 19 |
+
}
|
| 20 |
+
.fileImporter(
|
| 21 |
+
isPresented: $showFileImporter,
|
| 22 |
+
allowedContentTypes: [UTType(filenameExtension: "gguf", conformingTo: .data)!],
|
| 23 |
+
allowsMultipleSelection: false
|
| 24 |
+
) { result in
|
| 25 |
+
switch result {
|
| 26 |
+
case .success(let files):
|
| 27 |
+
files.forEach { file in
|
| 28 |
+
let gotAccess = file.startAccessingSecurityScopedResource()
|
| 29 |
+
if !gotAccess { return }
|
| 30 |
+
|
| 31 |
+
do {
|
| 32 |
+
try llamaState.loadModel(modelUrl: file.absoluteURL)
|
| 33 |
+
} catch let err {
|
| 34 |
+
print("Error: \(err.localizedDescription)")
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
file.stopAccessingSecurityScopedResource()
|
| 38 |
+
}
|
| 39 |
+
case .failure(let error):
|
| 40 |
+
print(error)
|
| 41 |
+
}
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
}
|
examples/llama.swiftui/llama.swiftui/llama_swiftuiApp.swift
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import SwiftUI
|
| 2 |
+
|
| 3 |
+
@main
|
| 4 |
+
struct llama_swiftuiApp: App {
|
| 5 |
+
var body: some Scene {
|
| 6 |
+
WindowGroup {
|
| 7 |
+
ContentView()
|
| 8 |
+
}
|
| 9 |
+
}
|
| 10 |
+
}
|
examples/llama.vim
ADDED
|
@@ -0,0 +1,783 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
" LLM-based text completion using llama.cpp
|
| 2 |
+
"
|
| 3 |
+
" requires:
|
| 4 |
+
"
|
| 5 |
+
" - neovim or vim
|
| 6 |
+
" - curl
|
| 7 |
+
" - llama.cpp server instance
|
| 8 |
+
" - FIM-compatible model
|
| 9 |
+
"
|
| 10 |
+
" sample config:
|
| 11 |
+
"
|
| 12 |
+
" - Tab - accept the current suggestion
|
| 13 |
+
" - Shift+Tab - accept just the first line of the suggestion
|
| 14 |
+
" - Ctrl+F - toggle FIM completion manually
|
| 15 |
+
"
|
| 16 |
+
" make symlink or copy this file to ~/.config/nvim/autoload/llama.vim
|
| 17 |
+
"
|
| 18 |
+
" start the llama.cpp server with a FIM-compatible model. for example:
|
| 19 |
+
"
|
| 20 |
+
" $ llama-server -m {model.gguf} --port 8012 -ngl 99 -fa --ubatch-size 512 --batch-size 1024 --cache-reuse 256
|
| 21 |
+
"
|
| 22 |
+
" --batch-size [512, model max context]
|
| 23 |
+
"
|
| 24 |
+
" adjust the batch size to control how much of the provided local context will be used during the inference
|
| 25 |
+
" lower values will use smaller part of the context around the cursor, which will result in faster processing
|
| 26 |
+
"
|
| 27 |
+
" --ubatch-size [64, 2048]
|
| 28 |
+
"
|
| 29 |
+
" chunks the batch into smaller chunks for faster processing
|
| 30 |
+
" depends on the specific hardware. use llama-bench to profile and determine the best size
|
| 31 |
+
"
|
| 32 |
+
" --cache-reuse (ge:llama_config.n_predict, 1024]
|
| 33 |
+
"
|
| 34 |
+
" this should be either 0 (disabled) or strictly larger than g:llama_config.n_predict
|
| 35 |
+
" using non-zero value enables context reuse on the server side which dramatically improves the performance at
|
| 36 |
+
" large contexts. a value of 256 should be good for all cases
|
| 37 |
+
"
|
| 38 |
+
" run this once to initialise llama.vim:
|
| 39 |
+
"
|
| 40 |
+
" :call llama#init()
|
| 41 |
+
"
|
| 42 |
+
" more info: https://github.com/ggml-org/llama.cpp/pull/9787
|
| 43 |
+
"
|
| 44 |
+
|
| 45 |
+
" colors (adjust to your liking)
|
| 46 |
+
highlight llama_hl_hint guifg=#ff772f ctermfg=202
|
| 47 |
+
highlight llama_hl_info guifg=#77ff2f ctermfg=119
|
| 48 |
+
|
| 49 |
+
" general parameters:
|
| 50 |
+
"
|
| 51 |
+
" endpoint: llama.cpp server endpoint
|
| 52 |
+
" n_prefix: number of lines before the cursor location to include in the local prefix
|
| 53 |
+
" n_suffix: number of lines after the cursor location to include in the local suffix
|
| 54 |
+
" n_predict: max number of tokens to predict
|
| 55 |
+
" t_max_prompt_ms: max allotted time for the prompt processing (TODO: not yet supported)
|
| 56 |
+
" t_max_predict_ms: max allotted time for the prediction
|
| 57 |
+
" show_info: show extra info about the inference (0 - disabled, 1 - statusline, 2 - inline)
|
| 58 |
+
" auto_fim: trigger FIM completion automatically on cursor movement
|
| 59 |
+
" max_line_suffix: do not auto-trigger FIM completion if there are more than this number of characters to the right of the cursor
|
| 60 |
+
"
|
| 61 |
+
" ring buffer of chunks, accumulated with time upon:
|
| 62 |
+
"
|
| 63 |
+
" - completion request
|
| 64 |
+
" - yank
|
| 65 |
+
" - entering a buffer
|
| 66 |
+
" - leaving a buffer
|
| 67 |
+
" - writing a file
|
| 68 |
+
"
|
| 69 |
+
" parameters for the ring-buffer with extra context:
|
| 70 |
+
"
|
| 71 |
+
" ring_n_chunks: max number of chunks to pass as extra context to the server (0 to disable)
|
| 72 |
+
" ring_chunk_size: max size of the chunks (in number of lines)
|
| 73 |
+
" note: adjust these numbers so that you don't overrun your context
|
| 74 |
+
" at ring_n_chunks = 64 and ring_chunk_size = 64 you need ~32k context
|
| 75 |
+
" ring_scope: the range around the cursor position (in number of lines) for gathering chunks after FIM
|
| 76 |
+
" ring_update_ms: how often to process queued chunks in normal mode
|
| 77 |
+
"
|
| 78 |
+
let s:default_config = {
|
| 79 |
+
\ 'endpoint': 'http://127.0.0.1:8012/infill',
|
| 80 |
+
\ 'n_prefix': 256,
|
| 81 |
+
\ 'n_suffix': 64,
|
| 82 |
+
\ 'n_predict': 128,
|
| 83 |
+
\ 't_max_prompt_ms': 500,
|
| 84 |
+
\ 't_max_predict_ms': 3000,
|
| 85 |
+
\ 'show_info': 2,
|
| 86 |
+
\ 'auto_fim': v:true,
|
| 87 |
+
\ 'max_line_suffix': 8,
|
| 88 |
+
\ 'ring_n_chunks': 64,
|
| 89 |
+
\ 'ring_chunk_size': 64,
|
| 90 |
+
\ 'ring_scope': 1024,
|
| 91 |
+
\ 'ring_update_ms': 1000,
|
| 92 |
+
\ }
|
| 93 |
+
|
| 94 |
+
let g:llama_config = get(g:, 'llama_config', s:default_config)
|
| 95 |
+
|
| 96 |
+
function! s:get_indent(str)
|
| 97 |
+
let l:count = 0
|
| 98 |
+
for i in range(len(a:str))
|
| 99 |
+
if a:str[i] == "\t"
|
| 100 |
+
let l:count += &tabstop - 1
|
| 101 |
+
else
|
| 102 |
+
break
|
| 103 |
+
endif
|
| 104 |
+
endfor
|
| 105 |
+
return l:count
|
| 106 |
+
endfunction
|
| 107 |
+
|
| 108 |
+
function! s:rand(i0, i1) abort
|
| 109 |
+
return a:i0 + rand() % (a:i1 - a:i0 + 1)
|
| 110 |
+
endfunction
|
| 111 |
+
|
| 112 |
+
function! llama#init()
|
| 113 |
+
if !executable('curl')
|
| 114 |
+
echohl WarningMsg
|
| 115 |
+
echo 'llama.vim requires the "curl" command to be available'
|
| 116 |
+
echohl None
|
| 117 |
+
return
|
| 118 |
+
endif
|
| 119 |
+
|
| 120 |
+
let s:pos_x = 0 " cursor position upon start of completion
|
| 121 |
+
let s:pos_y = 0
|
| 122 |
+
|
| 123 |
+
let s:line_cur = ''
|
| 124 |
+
|
| 125 |
+
let s:line_cur_prefix = ''
|
| 126 |
+
let s:line_cur_suffix = ''
|
| 127 |
+
|
| 128 |
+
let s:ring_chunks = [] " current set of chunks used as extra context
|
| 129 |
+
let s:ring_queued = [] " chunks that are queued to be sent for processing
|
| 130 |
+
let s:ring_n_evict = 0
|
| 131 |
+
|
| 132 |
+
let s:hint_shown = v:false
|
| 133 |
+
let s:pos_y_pick = -9999 " last y where we picked a chunk
|
| 134 |
+
let s:pos_dx = 0
|
| 135 |
+
let s:content = []
|
| 136 |
+
let s:can_accept = v:false
|
| 137 |
+
|
| 138 |
+
let s:timer_fim = -1
|
| 139 |
+
let s:t_fim_start = reltime() " used to measure total FIM time
|
| 140 |
+
let s:t_last_move = reltime() " last time the cursor moved
|
| 141 |
+
|
| 142 |
+
let s:current_job = v:null
|
| 143 |
+
|
| 144 |
+
let s:ghost_text_nvim = exists('*nvim_buf_get_mark')
|
| 145 |
+
let s:ghost_text_vim = has('textprop')
|
| 146 |
+
|
| 147 |
+
if s:ghost_text_vim
|
| 148 |
+
let s:hlgroup_hint = 'llama_hl_hint'
|
| 149 |
+
let s:hlgroup_info = 'llama_hl_info'
|
| 150 |
+
|
| 151 |
+
if empty(prop_type_get(s:hlgroup_hint))
|
| 152 |
+
call prop_type_add(s:hlgroup_hint, {'highlight': s:hlgroup_hint})
|
| 153 |
+
endif
|
| 154 |
+
if empty(prop_type_get(s:hlgroup_info))
|
| 155 |
+
call prop_type_add(s:hlgroup_info, {'highlight': s:hlgroup_info})
|
| 156 |
+
endif
|
| 157 |
+
endif
|
| 158 |
+
|
| 159 |
+
augroup llama
|
| 160 |
+
autocmd!
|
| 161 |
+
autocmd InsertEnter * inoremap <expr> <silent> <C-F> llama#fim_inline(v:false)
|
| 162 |
+
autocmd InsertLeavePre * call llama#fim_cancel()
|
| 163 |
+
|
| 164 |
+
autocmd CursorMoved * call s:on_move()
|
| 165 |
+
autocmd CursorMovedI * call s:on_move()
|
| 166 |
+
autocmd CompleteChanged * call llama#fim_cancel()
|
| 167 |
+
|
| 168 |
+
if g:llama_config.auto_fim
|
| 169 |
+
autocmd CursorMovedI * call llama#fim(v:true)
|
| 170 |
+
endif
|
| 171 |
+
|
| 172 |
+
" gather chunks upon yanking
|
| 173 |
+
autocmd TextYankPost * if v:event.operator ==# 'y' | call s:pick_chunk(v:event.regcontents, v:false, v:true) | endif
|
| 174 |
+
|
| 175 |
+
" gather chunks upon entering/leaving a buffer
|
| 176 |
+
autocmd BufEnter * call timer_start(100, {-> s:pick_chunk(getline(max([1, line('.') - g:llama_config.ring_chunk_size/2]), min([line('.') + g:llama_config.ring_chunk_size/2, line('$')])), v:true, v:true)})
|
| 177 |
+
autocmd BufLeave * call s:pick_chunk(getline(max([1, line('.') - g:llama_config.ring_chunk_size/2]), min([line('.') + g:llama_config.ring_chunk_size/2, line('$')])), v:true, v:true)
|
| 178 |
+
|
| 179 |
+
" gather chunk upon saving the file
|
| 180 |
+
autocmd BufWritePost * call s:pick_chunk(getline(max([1, line('.') - g:llama_config.ring_chunk_size/2]), min([line('.') + g:llama_config.ring_chunk_size/2, line('$')])), v:true, v:true)
|
| 181 |
+
augroup END
|
| 182 |
+
|
| 183 |
+
silent! call llama#fim_cancel()
|
| 184 |
+
|
| 185 |
+
" init background update of the ring buffer
|
| 186 |
+
if g:llama_config.ring_n_chunks > 0
|
| 187 |
+
call s:ring_update()
|
| 188 |
+
endif
|
| 189 |
+
endfunction
|
| 190 |
+
|
| 191 |
+
" compute how similar two chunks of text are
|
| 192 |
+
" 0 - no similarity, 1 - high similarity
|
| 193 |
+
" TODO: figure out something better
|
| 194 |
+
function! s:chunk_sim(c0, c1)
|
| 195 |
+
let l:lines0 = len(a:c0)
|
| 196 |
+
let l:lines1 = len(a:c1)
|
| 197 |
+
|
| 198 |
+
let l:common = 0
|
| 199 |
+
|
| 200 |
+
for l:line0 in a:c0
|
| 201 |
+
for l:line1 in a:c1
|
| 202 |
+
if l:line0 == l:line1
|
| 203 |
+
let l:common += 1
|
| 204 |
+
break
|
| 205 |
+
endif
|
| 206 |
+
endfor
|
| 207 |
+
endfor
|
| 208 |
+
|
| 209 |
+
return 2.0 * l:common / (l:lines0 + l:lines1)
|
| 210 |
+
endfunction
|
| 211 |
+
|
| 212 |
+
" pick a random chunk of size g:llama_config.ring_chunk_size from the provided text and queue it for processing
|
| 213 |
+
"
|
| 214 |
+
" no_mod - do not pick chunks from buffers with pending changes
|
| 215 |
+
" do_evict - evict chunks that are very similar to the new one
|
| 216 |
+
"
|
| 217 |
+
function! s:pick_chunk(text, no_mod, do_evict)
|
| 218 |
+
" do not pick chunks from buffers with pending changes or buffers that are not files
|
| 219 |
+
if a:no_mod && (getbufvar(bufnr('%'), '&modified') || !buflisted(bufnr('%')) || !filereadable(expand('%')))
|
| 220 |
+
return
|
| 221 |
+
endif
|
| 222 |
+
|
| 223 |
+
" if the extra context option is disabled - do nothing
|
| 224 |
+
if g:llama_config.ring_n_chunks <= 0
|
| 225 |
+
return
|
| 226 |
+
endif
|
| 227 |
+
|
| 228 |
+
" don't pick very small chunks
|
| 229 |
+
if len(a:text) < 3
|
| 230 |
+
return
|
| 231 |
+
endif
|
| 232 |
+
|
| 233 |
+
if len(a:text) + 1 < g:llama_config.ring_chunk_size
|
| 234 |
+
let l:chunk = a:text
|
| 235 |
+
else
|
| 236 |
+
let l:l0 = s:rand(0, max([0, len(a:text) - g:llama_config.ring_chunk_size/2]))
|
| 237 |
+
let l:l1 = min([l:l0 + g:llama_config.ring_chunk_size/2, len(a:text)])
|
| 238 |
+
|
| 239 |
+
let l:chunk = a:text[l:l0:l:l1]
|
| 240 |
+
endif
|
| 241 |
+
|
| 242 |
+
let l:chunk_str = join(l:chunk, "\n") . "\n"
|
| 243 |
+
|
| 244 |
+
" check if this chunk is already added
|
| 245 |
+
let l:exist = v:false
|
| 246 |
+
|
| 247 |
+
for i in range(len(s:ring_chunks))
|
| 248 |
+
if s:ring_chunks[i].data == l:chunk
|
| 249 |
+
let l:exist = v:true
|
| 250 |
+
break
|
| 251 |
+
endif
|
| 252 |
+
endfor
|
| 253 |
+
|
| 254 |
+
for i in range(len(s:ring_queued))
|
| 255 |
+
if s:ring_queued[i].data == l:chunk
|
| 256 |
+
let l:exist = v:true
|
| 257 |
+
break
|
| 258 |
+
endif
|
| 259 |
+
endfor
|
| 260 |
+
|
| 261 |
+
if l:exist
|
| 262 |
+
return
|
| 263 |
+
endif
|
| 264 |
+
|
| 265 |
+
" evict queued chunks that are very similar to the new one
|
| 266 |
+
for i in range(len(s:ring_queued) - 1, 0, -1)
|
| 267 |
+
if s:chunk_sim(s:ring_queued[i].data, l:chunk) > 0.9
|
| 268 |
+
if a:do_evict
|
| 269 |
+
call remove(s:ring_queued, i)
|
| 270 |
+
let s:ring_n_evict += 1
|
| 271 |
+
else
|
| 272 |
+
return
|
| 273 |
+
endif
|
| 274 |
+
endif
|
| 275 |
+
endfor
|
| 276 |
+
|
| 277 |
+
" also from s:ring_chunks
|
| 278 |
+
for i in range(len(s:ring_chunks) - 1, 0, -1)
|
| 279 |
+
if s:chunk_sim(s:ring_chunks[i].data, l:chunk) > 0.9
|
| 280 |
+
if a:do_evict
|
| 281 |
+
call remove(s:ring_chunks, i)
|
| 282 |
+
let s:ring_n_evict += 1
|
| 283 |
+
else
|
| 284 |
+
return
|
| 285 |
+
endif
|
| 286 |
+
endif
|
| 287 |
+
endfor
|
| 288 |
+
|
| 289 |
+
" TODO: become parameter ?
|
| 290 |
+
if len(s:ring_queued) == 16
|
| 291 |
+
call remove(s:ring_queued, 0)
|
| 292 |
+
endif
|
| 293 |
+
|
| 294 |
+
call add(s:ring_queued, {'data': l:chunk, 'str': l:chunk_str, 'time': reltime(), 'filename': expand('%')})
|
| 295 |
+
|
| 296 |
+
"let &statusline = 'extra context: ' . len(s:ring_chunks) . ' / ' . len(s:ring_queued)
|
| 297 |
+
endfunction
|
| 298 |
+
|
| 299 |
+
" picks a queued chunk, sends it for processing and adds it to s:ring_chunks
|
| 300 |
+
" called every g:llama_config.ring_update_ms
|
| 301 |
+
function! s:ring_update()
|
| 302 |
+
call timer_start(g:llama_config.ring_update_ms, {-> s:ring_update()})
|
| 303 |
+
|
| 304 |
+
" update only if in normal mode or if the cursor hasn't moved for a while
|
| 305 |
+
if mode() !=# 'n' && reltimefloat(reltime(s:t_last_move)) < 3.0
|
| 306 |
+
return
|
| 307 |
+
endif
|
| 308 |
+
|
| 309 |
+
if len(s:ring_queued) == 0
|
| 310 |
+
return
|
| 311 |
+
endif
|
| 312 |
+
|
| 313 |
+
" move the first queued chunk to the ring buffer
|
| 314 |
+
if len(s:ring_chunks) == g:llama_config.ring_n_chunks
|
| 315 |
+
call remove(s:ring_chunks, 0)
|
| 316 |
+
endif
|
| 317 |
+
|
| 318 |
+
call add(s:ring_chunks, remove(s:ring_queued, 0))
|
| 319 |
+
|
| 320 |
+
"let &statusline = 'updated context: ' . len(s:ring_chunks) . ' / ' . len(s:ring_queued)
|
| 321 |
+
|
| 322 |
+
" send asynchronous job with the new extra context so that it is ready for the next FIM
|
| 323 |
+
let l:extra_context = []
|
| 324 |
+
for l:chunk in s:ring_chunks
|
| 325 |
+
call add(l:extra_context, {
|
| 326 |
+
\ 'text': l:chunk.str,
|
| 327 |
+
\ 'time': l:chunk.time,
|
| 328 |
+
\ 'filename': l:chunk.filename
|
| 329 |
+
\ })
|
| 330 |
+
endfor
|
| 331 |
+
|
| 332 |
+
" no samplers needed here
|
| 333 |
+
let l:request = json_encode({
|
| 334 |
+
\ 'input_prefix': "",
|
| 335 |
+
\ 'input_suffix': "",
|
| 336 |
+
\ 'input_extra': l:extra_context,
|
| 337 |
+
\ 'prompt': "",
|
| 338 |
+
\ 'n_predict': 1,
|
| 339 |
+
\ 'temperature': 0.0,
|
| 340 |
+
\ 'stream': v:false,
|
| 341 |
+
\ 'samplers': ["temperature"],
|
| 342 |
+
\ 'cache_prompt': v:true,
|
| 343 |
+
\ 't_max_prompt_ms': 1,
|
| 344 |
+
\ 't_max_predict_ms': 1
|
| 345 |
+
\ })
|
| 346 |
+
|
| 347 |
+
let l:curl_command = [
|
| 348 |
+
\ "curl",
|
| 349 |
+
\ "--silent",
|
| 350 |
+
\ "--no-buffer",
|
| 351 |
+
\ "--request", "POST",
|
| 352 |
+
\ "--url", g:llama_config.endpoint,
|
| 353 |
+
\ "--header", "Content-Type: application/json",
|
| 354 |
+
\ "--data", l:request
|
| 355 |
+
\ ]
|
| 356 |
+
|
| 357 |
+
" no callbacks because we don't need to process the response
|
| 358 |
+
if s:ghost_text_nvim
|
| 359 |
+
call jobstart(l:curl_command, {})
|
| 360 |
+
elseif s:ghost_text_vim
|
| 361 |
+
call job_start(l:curl_command, {})
|
| 362 |
+
endif
|
| 363 |
+
endfunction
|
| 364 |
+
|
| 365 |
+
" necessary for 'inoremap <expr>'
|
| 366 |
+
function! llama#fim_inline(is_auto) abort
|
| 367 |
+
call llama#fim(a:is_auto)
|
| 368 |
+
return ''
|
| 369 |
+
endfunction
|
| 370 |
+
|
| 371 |
+
" the main FIM call
|
| 372 |
+
" takes local context around the cursor and sends it together with the extra context to the server for completion
|
| 373 |
+
function! llama#fim(is_auto) abort
|
| 374 |
+
" we already have a suggestion for the current cursor position
|
| 375 |
+
if s:hint_shown && !a:is_auto
|
| 376 |
+
call llama#fim_cancel()
|
| 377 |
+
return
|
| 378 |
+
endif
|
| 379 |
+
|
| 380 |
+
call llama#fim_cancel()
|
| 381 |
+
|
| 382 |
+
" avoid sending repeated requests too fast
|
| 383 |
+
if reltimefloat(reltime(s:t_fim_start)) < 0.6
|
| 384 |
+
if s:timer_fim != -1
|
| 385 |
+
call timer_stop(s:timer_fim)
|
| 386 |
+
let s:timer_fim = -1
|
| 387 |
+
endif
|
| 388 |
+
|
| 389 |
+
let s:t_fim_start = reltime()
|
| 390 |
+
let s:timer_fim = timer_start(600, {-> llama#fim(v:true)})
|
| 391 |
+
return
|
| 392 |
+
endif
|
| 393 |
+
|
| 394 |
+
let s:t_fim_start = reltime()
|
| 395 |
+
|
| 396 |
+
let s:content = []
|
| 397 |
+
let s:can_accept = v:false
|
| 398 |
+
|
| 399 |
+
let s:pos_x = col('.') - 1
|
| 400 |
+
let s:pos_y = line('.')
|
| 401 |
+
let l:max_y = line('$')
|
| 402 |
+
|
| 403 |
+
let l:lines_prefix = getline(max([1, s:pos_y - g:llama_config.n_prefix]), s:pos_y - 1)
|
| 404 |
+
let l:lines_suffix = getline(s:pos_y + 1, min([l:max_y, s:pos_y + g:llama_config.n_suffix]))
|
| 405 |
+
|
| 406 |
+
let s:line_cur = getline('.')
|
| 407 |
+
|
| 408 |
+
let s:line_cur_prefix = strpart(s:line_cur, 0, s:pos_x)
|
| 409 |
+
let s:line_cur_suffix = strpart(s:line_cur, s:pos_x)
|
| 410 |
+
|
| 411 |
+
if a:is_auto && len(s:line_cur_suffix) > g:llama_config.max_line_suffix
|
| 412 |
+
return
|
| 413 |
+
endif
|
| 414 |
+
|
| 415 |
+
let l:prefix = ""
|
| 416 |
+
\ . join(l:lines_prefix, "\n")
|
| 417 |
+
\ . "\n"
|
| 418 |
+
|
| 419 |
+
let l:prompt = ""
|
| 420 |
+
\ . s:line_cur_prefix
|
| 421 |
+
|
| 422 |
+
let l:suffix = ""
|
| 423 |
+
\ . s:line_cur_suffix
|
| 424 |
+
\ . "\n"
|
| 425 |
+
\ . join(l:lines_suffix, "\n")
|
| 426 |
+
\ . "\n"
|
| 427 |
+
|
| 428 |
+
" prepare the extra context data
|
| 429 |
+
let l:extra_context = []
|
| 430 |
+
for l:chunk in s:ring_chunks
|
| 431 |
+
call add(l:extra_context, {
|
| 432 |
+
\ 'text': l:chunk.str,
|
| 433 |
+
\ 'time': l:chunk.time,
|
| 434 |
+
\ 'filename': l:chunk.filename
|
| 435 |
+
\ })
|
| 436 |
+
endfor
|
| 437 |
+
|
| 438 |
+
" the indentation of the current line
|
| 439 |
+
let l:indent = strlen(matchstr(s:line_cur_prefix, '^\s*'))
|
| 440 |
+
|
| 441 |
+
let l:request = json_encode({
|
| 442 |
+
\ 'input_prefix': l:prefix,
|
| 443 |
+
\ 'input_suffix': l:suffix,
|
| 444 |
+
\ 'input_extra': l:extra_context,
|
| 445 |
+
\ 'prompt': l:prompt,
|
| 446 |
+
\ 'n_predict': g:llama_config.n_predict,
|
| 447 |
+
\ 'n_indent': l:indent,
|
| 448 |
+
\ 'top_k': 40,
|
| 449 |
+
\ 'top_p': 0.99,
|
| 450 |
+
\ 'stream': v:false,
|
| 451 |
+
\ 'samplers': ["top_k", "top_p", "infill"],
|
| 452 |
+
\ 'cache_prompt': v:true,
|
| 453 |
+
\ 't_max_prompt_ms': g:llama_config.t_max_prompt_ms,
|
| 454 |
+
\ 't_max_predict_ms': g:llama_config.t_max_predict_ms
|
| 455 |
+
\ })
|
| 456 |
+
|
| 457 |
+
let l:curl_command = [
|
| 458 |
+
\ "curl",
|
| 459 |
+
\ "--silent",
|
| 460 |
+
\ "--no-buffer",
|
| 461 |
+
\ "--request", "POST",
|
| 462 |
+
\ "--url", g:llama_config.endpoint,
|
| 463 |
+
\ "--header", "Content-Type: application/json",
|
| 464 |
+
\ "--data", l:request
|
| 465 |
+
\ ]
|
| 466 |
+
|
| 467 |
+
if s:current_job != v:null
|
| 468 |
+
if s:ghost_text_nvim
|
| 469 |
+
call jobstop(s:current_job)
|
| 470 |
+
elseif s:ghost_text_vim
|
| 471 |
+
call job_stop(s:current_job)
|
| 472 |
+
endif
|
| 473 |
+
endif
|
| 474 |
+
|
| 475 |
+
" send the request asynchronously
|
| 476 |
+
if s:ghost_text_nvim
|
| 477 |
+
let s:current_job = jobstart(l:curl_command, {
|
| 478 |
+
\ 'on_stdout': function('s:fim_on_stdout', [s:pos_x, s:pos_y, a:is_auto]),
|
| 479 |
+
\ 'on_exit': function('s:fim_on_exit'),
|
| 480 |
+
\ 'stdout_buffered': v:true
|
| 481 |
+
\ })
|
| 482 |
+
elseif s:ghost_text_vim
|
| 483 |
+
let s:current_job = job_start(l:curl_command, {
|
| 484 |
+
\ 'out_cb': function('s:fim_on_stdout', [s:pos_x, s:pos_y, a:is_auto]),
|
| 485 |
+
\ 'exit_cb': function('s:fim_on_exit')
|
| 486 |
+
\ })
|
| 487 |
+
endif
|
| 488 |
+
|
| 489 |
+
" TODO: per-file location
|
| 490 |
+
let l:delta_y = abs(s:pos_y - s:pos_y_pick)
|
| 491 |
+
|
| 492 |
+
" gather some extra context nearby and process it in the background
|
| 493 |
+
" only gather chunks if the cursor has moved a lot
|
| 494 |
+
" TODO: something more clever? reranking?
|
| 495 |
+
if a:is_auto && l:delta_y > 32
|
| 496 |
+
" expand the prefix even further
|
| 497 |
+
call s:pick_chunk(getline(max([1, s:pos_y - g:llama_config.ring_scope]), max([1, s:pos_y - g:llama_config.n_prefix])), v:false, v:false)
|
| 498 |
+
|
| 499 |
+
" pick a suffix chunk
|
| 500 |
+
call s:pick_chunk(getline(min([l:max_y, s:pos_y + g:llama_config.n_suffix]), min([l:max_y, s:pos_y + g:llama_config.n_suffix + g:llama_config.ring_chunk_size])), v:false, v:false)
|
| 501 |
+
|
| 502 |
+
let s:pos_y_pick = s:pos_y
|
| 503 |
+
endif
|
| 504 |
+
endfunction
|
| 505 |
+
|
| 506 |
+
" if first_line == v:true accept only the first line of the response
|
| 507 |
+
function! llama#fim_accept(first_line)
|
| 508 |
+
" insert the suggestion at the cursor location
|
| 509 |
+
if s:can_accept && len(s:content) > 0
|
| 510 |
+
call setline(s:pos_y, s:line_cur[:(s:pos_x - 1)] . s:content[0])
|
| 511 |
+
if len(s:content) > 1
|
| 512 |
+
if !a:first_line
|
| 513 |
+
call append(s:pos_y, s:content[1:-1])
|
| 514 |
+
endif
|
| 515 |
+
endif
|
| 516 |
+
|
| 517 |
+
" move the cursor to the end of the accepted text
|
| 518 |
+
if !a:first_line && len(s:content) > 1
|
| 519 |
+
call cursor(s:pos_y + len(s:content) - 1, s:pos_x + s:pos_dx + 1)
|
| 520 |
+
else
|
| 521 |
+
call cursor(s:pos_y, s:pos_x + len(s:content[0]))
|
| 522 |
+
endif
|
| 523 |
+
endif
|
| 524 |
+
|
| 525 |
+
call llama#fim_cancel()
|
| 526 |
+
endfunction
|
| 527 |
+
|
| 528 |
+
function! llama#fim_cancel()
|
| 529 |
+
let s:hint_shown = v:false
|
| 530 |
+
|
| 531 |
+
" clear the virtual text
|
| 532 |
+
let l:bufnr = bufnr('%')
|
| 533 |
+
|
| 534 |
+
if s:ghost_text_nvim
|
| 535 |
+
let l:id_vt_fim = nvim_create_namespace('vt_fim')
|
| 536 |
+
call nvim_buf_clear_namespace(l:bufnr, l:id_vt_fim, 0, -1)
|
| 537 |
+
elseif s:ghost_text_vim
|
| 538 |
+
call prop_remove({'type': s:hlgroup_hint, 'all': v:true})
|
| 539 |
+
call prop_remove({'type': s:hlgroup_info, 'all': v:true})
|
| 540 |
+
endif
|
| 541 |
+
|
| 542 |
+
" remove the mappings
|
| 543 |
+
silent! iunmap <buffer> <Tab>
|
| 544 |
+
silent! iunmap <buffer> <S-Tab>
|
| 545 |
+
silent! iunmap <buffer> <Esc>
|
| 546 |
+
endfunction
|
| 547 |
+
|
| 548 |
+
function! s:on_move()
|
| 549 |
+
let s:t_last_move = reltime()
|
| 550 |
+
|
| 551 |
+
call llama#fim_cancel()
|
| 552 |
+
endfunction
|
| 553 |
+
|
| 554 |
+
" callback that processes the FIM result from the server and displays the suggestion
|
| 555 |
+
function! s:fim_on_stdout(pos_x, pos_y, is_auto, job_id, data, event = v:null)
|
| 556 |
+
if s:ghost_text_nvim
|
| 557 |
+
let l:raw = join(a:data, "\n")
|
| 558 |
+
elseif s:ghost_text_vim
|
| 559 |
+
let l:raw = a:data
|
| 560 |
+
endif
|
| 561 |
+
|
| 562 |
+
if len(l:raw) == 0
|
| 563 |
+
return
|
| 564 |
+
endif
|
| 565 |
+
|
| 566 |
+
if a:pos_x != col('.') - 1 || a:pos_y != line('.')
|
| 567 |
+
return
|
| 568 |
+
endif
|
| 569 |
+
|
| 570 |
+
" show the suggestion only in insert mode
|
| 571 |
+
if mode() !=# 'i'
|
| 572 |
+
return
|
| 573 |
+
endif
|
| 574 |
+
|
| 575 |
+
let s:pos_x = a:pos_x
|
| 576 |
+
let s:pos_y = a:pos_y
|
| 577 |
+
|
| 578 |
+
let s:can_accept = v:true
|
| 579 |
+
let l:has_info = v:false
|
| 580 |
+
|
| 581 |
+
if s:can_accept && v:shell_error
|
| 582 |
+
if !a:is_auto
|
| 583 |
+
call add(s:content, "<| curl error: is the server on? |>")
|
| 584 |
+
endif
|
| 585 |
+
let s:can_accept = v:false
|
| 586 |
+
endif
|
| 587 |
+
|
| 588 |
+
let l:n_prompt = 0
|
| 589 |
+
let l:t_prompt_ms = 1.0
|
| 590 |
+
let l:s_prompt = 0
|
| 591 |
+
|
| 592 |
+
let l:n_predict = 0
|
| 593 |
+
let l:t_predict_ms = 1.0
|
| 594 |
+
let l:s_predict = 0
|
| 595 |
+
|
| 596 |
+
" get the generated suggestion
|
| 597 |
+
if s:can_accept
|
| 598 |
+
let l:response = json_decode(l:raw)
|
| 599 |
+
|
| 600 |
+
for l:part in split(get(l:response, 'content', ''), "\n", 1)
|
| 601 |
+
call add(s:content, l:part)
|
| 602 |
+
endfor
|
| 603 |
+
|
| 604 |
+
" remove trailing new lines
|
| 605 |
+
while len(s:content) > 0 && s:content[-1] == ""
|
| 606 |
+
call remove(s:content, -1)
|
| 607 |
+
endwhile
|
| 608 |
+
|
| 609 |
+
let l:generation_settings = get(l:response, 'generation_settings', {})
|
| 610 |
+
let l:n_ctx = get(l:generation_settings, 'n_ctx', 0)
|
| 611 |
+
|
| 612 |
+
let l:n_cached = get(l:response, 'tokens_cached', 0)
|
| 613 |
+
let l:truncated = get(l:response, 'truncated', v:false)
|
| 614 |
+
|
| 615 |
+
" if response.timings is available
|
| 616 |
+
if len(get(l:response, 'timings', {})) > 0
|
| 617 |
+
let l:has_info = v:true
|
| 618 |
+
let l:timings = get(l:response, 'timings', {})
|
| 619 |
+
|
| 620 |
+
let l:n_prompt = get(l:timings, 'prompt_n', 0)
|
| 621 |
+
let l:t_prompt_ms = get(l:timings, 'prompt_ms', 1)
|
| 622 |
+
let l:s_prompt = get(l:timings, 'prompt_per_second', 0)
|
| 623 |
+
|
| 624 |
+
let l:n_predict = get(l:timings, 'predicted_n', 0)
|
| 625 |
+
let l:t_predict_ms = get(l:timings, 'predicted_ms', 1)
|
| 626 |
+
let l:s_predict = get(l:timings, 'predicted_per_second', 0)
|
| 627 |
+
endif
|
| 628 |
+
endif
|
| 629 |
+
|
| 630 |
+
if len(s:content) == 0
|
| 631 |
+
call add(s:content, "")
|
| 632 |
+
let s:can_accept = v:false
|
| 633 |
+
endif
|
| 634 |
+
|
| 635 |
+
if len(s:content) == 0
|
| 636 |
+
return
|
| 637 |
+
endif
|
| 638 |
+
|
| 639 |
+
" NOTE: the following is logic for discarding predictions that repeat existing text
|
| 640 |
+
" the code is quite ugly and there is very likely a simpler and more canonical way to implement this
|
| 641 |
+
"
|
| 642 |
+
" still, I wonder if there is some better way that avoids having to do these special hacks?
|
| 643 |
+
" on one hand, the LLM 'sees' the contents of the file before we start editing, so it is normal that it would
|
| 644 |
+
" start generating whatever we have given it via the extra context. but on the other hand, it's not very
|
| 645 |
+
" helpful to re-generate the same code that is already there
|
| 646 |
+
|
| 647 |
+
" truncate the suggestion if the first line is empty
|
| 648 |
+
if len(s:content) == 1 && s:content[0] == ""
|
| 649 |
+
let s:content = [""]
|
| 650 |
+
endif
|
| 651 |
+
|
| 652 |
+
" ... and the next lines are repeated
|
| 653 |
+
if len(s:content) > 1 && s:content[0] == "" && s:content[1:] == getline(s:pos_y + 1, s:pos_y + len(s:content) - 1)
|
| 654 |
+
let s:content = [""]
|
| 655 |
+
endif
|
| 656 |
+
|
| 657 |
+
" truncate the suggestion if it repeats the suffix
|
| 658 |
+
if len(s:content) == 1 && s:content[0] == s:line_cur_suffix
|
| 659 |
+
let s:content = [""]
|
| 660 |
+
endif
|
| 661 |
+
|
| 662 |
+
" find the first non-empty line (strip whitespace)
|
| 663 |
+
let l:cmp_y = s:pos_y + 1
|
| 664 |
+
while l:cmp_y < line('$') && getline(l:cmp_y) =~? '^\s*$'
|
| 665 |
+
let l:cmp_y += 1
|
| 666 |
+
endwhile
|
| 667 |
+
|
| 668 |
+
if (s:line_cur_prefix . s:content[0]) == getline(l:cmp_y)
|
| 669 |
+
" truncate the suggestion if it repeats the next line
|
| 670 |
+
if len(s:content) == 1
|
| 671 |
+
let s:content = [""]
|
| 672 |
+
endif
|
| 673 |
+
|
| 674 |
+
" ... or if the second line of the suggestion is the prefix of line l:cmp_y + 1
|
| 675 |
+
if len(s:content) == 2 && s:content[-1] == getline(l:cmp_y + 1)[:len(s:content[-1]) - 1]
|
| 676 |
+
let s:content = [""]
|
| 677 |
+
endif
|
| 678 |
+
|
| 679 |
+
" ... or if the middle chunk of lines of the suggestion is the same as [l:cmp_y + 1, l:cmp_y + len(s:content) - 1)
|
| 680 |
+
if len(s:content) > 2 && join(s:content[1:-1], "\n") == join(getline(l:cmp_y + 1, l:cmp_y + len(s:content) - 1), "\n")
|
| 681 |
+
let s:content = [""]
|
| 682 |
+
endif
|
| 683 |
+
endif
|
| 684 |
+
|
| 685 |
+
" keep only lines that have the same or larger whitespace prefix as s:line_cur_prefix
|
| 686 |
+
"let l:indent = strlen(matchstr(s:line_cur_prefix, '^\s*'))
|
| 687 |
+
"for i in range(1, len(s:content) - 1)
|
| 688 |
+
" if strlen(matchstr(s:content[i], '^\s*')) < l:indent
|
| 689 |
+
" let s:content = s:content[:i - 1]
|
| 690 |
+
" break
|
| 691 |
+
" endif
|
| 692 |
+
"endfor
|
| 693 |
+
|
| 694 |
+
let s:pos_dx = len(s:content[-1])
|
| 695 |
+
|
| 696 |
+
let s:content[-1] .= s:line_cur_suffix
|
| 697 |
+
|
| 698 |
+
call llama#fim_cancel()
|
| 699 |
+
|
| 700 |
+
" display virtual text with the suggestion
|
| 701 |
+
let l:bufnr = bufnr('%')
|
| 702 |
+
|
| 703 |
+
if s:ghost_text_nvim
|
| 704 |
+
let l:id_vt_fim = nvim_create_namespace('vt_fim')
|
| 705 |
+
endif
|
| 706 |
+
|
| 707 |
+
" construct the info message
|
| 708 |
+
if g:llama_config.show_info > 0 && l:has_info
|
| 709 |
+
let l:prefix = ' '
|
| 710 |
+
|
| 711 |
+
if l:truncated
|
| 712 |
+
let l:info = printf("%s | WARNING: the context is full: %d / %d, increase the server context size or reduce g:llama_config.ring_n_chunks",
|
| 713 |
+
\ g:llama_config.show_info == 2 ? l:prefix : 'llama.vim',
|
| 714 |
+
\ l:n_cached, l:n_ctx
|
| 715 |
+
\ )
|
| 716 |
+
else
|
| 717 |
+
let l:info = printf("%s | c: %d / %d, r: %d / %d, e: %d, q: %d / 16 | p: %d (%.2f ms, %.2f t/s) | g: %d (%.2f ms, %.2f t/s) | t: %.2f ms",
|
| 718 |
+
\ g:llama_config.show_info == 2 ? l:prefix : 'llama.vim',
|
| 719 |
+
\ l:n_cached, l:n_ctx, len(s:ring_chunks), g:llama_config.ring_n_chunks, s:ring_n_evict, len(s:ring_queued),
|
| 720 |
+
\ l:n_prompt, l:t_prompt_ms, l:s_prompt,
|
| 721 |
+
\ l:n_predict, l:t_predict_ms, l:s_predict,
|
| 722 |
+
\ 1000.0 * reltimefloat(reltime(s:t_fim_start))
|
| 723 |
+
\ )
|
| 724 |
+
endif
|
| 725 |
+
|
| 726 |
+
if g:llama_config.show_info == 1
|
| 727 |
+
" display the info in the statusline
|
| 728 |
+
let &statusline = l:info
|
| 729 |
+
let l:info = ''
|
| 730 |
+
endif
|
| 731 |
+
endif
|
| 732 |
+
|
| 733 |
+
" display the suggestion and append the info to the end of the first line
|
| 734 |
+
if s:ghost_text_nvim
|
| 735 |
+
call nvim_buf_set_extmark(l:bufnr, l:id_vt_fim, s:pos_y - 1, s:pos_x - 1, {
|
| 736 |
+
\ 'virt_text': [[s:content[0], 'llama_hl_hint'], [l:info, 'llama_hl_info']],
|
| 737 |
+
\ 'virt_text_win_col': virtcol('.') - 1
|
| 738 |
+
\ })
|
| 739 |
+
|
| 740 |
+
call nvim_buf_set_extmark(l:bufnr, l:id_vt_fim, s:pos_y - 1, 0, {
|
| 741 |
+
\ 'virt_lines': map(s:content[1:], {idx, val -> [[val, 'llama_hl_hint']]}),
|
| 742 |
+
\ 'virt_text_win_col': virtcol('.')
|
| 743 |
+
\ })
|
| 744 |
+
elseif s:ghost_text_vim
|
| 745 |
+
let l:new_suffix = s:content[0]
|
| 746 |
+
if !empty(l:new_suffix)
|
| 747 |
+
call prop_add(s:pos_y, s:pos_x + 1, {
|
| 748 |
+
\ 'type': s:hlgroup_hint,
|
| 749 |
+
\ 'text': l:new_suffix
|
| 750 |
+
\ })
|
| 751 |
+
endif
|
| 752 |
+
for line in s:content[1:]
|
| 753 |
+
call prop_add(s:pos_y, 0, {
|
| 754 |
+
\ 'type': s:hlgroup_hint,
|
| 755 |
+
\ 'text': line,
|
| 756 |
+
\ 'text_padding_left': s:get_indent(line),
|
| 757 |
+
\ 'text_align': 'below'
|
| 758 |
+
\ })
|
| 759 |
+
endfor
|
| 760 |
+
if !empty(l:info)
|
| 761 |
+
call prop_add(s:pos_y, 0, {
|
| 762 |
+
\ 'type': s:hlgroup_info,
|
| 763 |
+
\ 'text': l:info,
|
| 764 |
+
\ 'text_padding_left': col('$'),
|
| 765 |
+
\ 'text_wrap': 'truncate'
|
| 766 |
+
\ })
|
| 767 |
+
endif
|
| 768 |
+
endif
|
| 769 |
+
|
| 770 |
+
" setup accept shortcuts
|
| 771 |
+
inoremap <buffer> <Tab> <C-O>:call llama#fim_accept(v:false)<CR>
|
| 772 |
+
inoremap <buffer> <S-Tab> <C-O>:call llama#fim_accept(v:true)<CR>
|
| 773 |
+
|
| 774 |
+
let s:hint_shown = v:true
|
| 775 |
+
endfunction
|
| 776 |
+
|
| 777 |
+
function! s:fim_on_exit(job_id, exit_code, event = v:null)
|
| 778 |
+
if a:exit_code != 0
|
| 779 |
+
echom "Job failed with exit code: " . a:exit_code
|
| 780 |
+
endif
|
| 781 |
+
|
| 782 |
+
let s:current_job = v:null
|
| 783 |
+
endfunction
|
examples/lookahead/CMakeLists.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
set(TARGET llama-lookahead)
|
| 2 |
+
add_executable(${TARGET} lookahead.cpp)
|
| 3 |
+
install(TARGETS ${TARGET} RUNTIME)
|
| 4 |
+
target_link_libraries(${TARGET} PRIVATE llama-common llama ${CMAKE_THREAD_LIBS_INIT})
|
| 5 |
+
target_compile_features(${TARGET} PRIVATE cxx_std_17)
|
examples/lookahead/README.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# llama.cpp/examples/lookahead
|
| 2 |
+
|
| 3 |
+
Demonstration of lookahead decoding technique:
|
| 4 |
+
|
| 5 |
+
https://lmsys.org/blog/2023-11-21-lookahead-decoding/
|
| 6 |
+
|
| 7 |
+
More info: https://github.com/ggml-org/llama.cpp/pull/4207
|
| 8 |
+
|
| 9 |
+
Sample command:
|
| 10 |
+
|
| 11 |
+
```bash
|
| 12 |
+
llama-lookahead -hf ggml-org/Qwen2.5-Coder-3B-Q8_0-GGUF -p "// network server implemented in C\n// author: Peter Hacker\n\n#include" -e -ngl 99 -t 4 -n 512 -c 4096 -kvu
|
| 13 |
+
```
|
examples/lookahead/lookahead.cpp
ADDED
|
@@ -0,0 +1,483 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "arg.h"
|
| 2 |
+
#include "common.h"
|
| 3 |
+
#include "sampling.h"
|
| 4 |
+
#include "log.h"
|
| 5 |
+
#include "llama.h"
|
| 6 |
+
|
| 7 |
+
#include <algorithm>
|
| 8 |
+
#include <clocale>
|
| 9 |
+
#include <cstdio>
|
| 10 |
+
#include <string>
|
| 11 |
+
#include <vector>
|
| 12 |
+
|
| 13 |
+
struct ngram_data {
|
| 14 |
+
bool active = false;
|
| 15 |
+
|
| 16 |
+
llama_seq_id seq_id = -1;
|
| 17 |
+
|
| 18 |
+
std::vector<int> i_batch;
|
| 19 |
+
|
| 20 |
+
std::vector<llama_token> tokens;
|
| 21 |
+
};
|
| 22 |
+
|
| 23 |
+
// n-gram container
|
| 24 |
+
struct ngram_container {
|
| 25 |
+
ngram_container(int n_vocab, int N, int G) {
|
| 26 |
+
cnt.resize(n_vocab);
|
| 27 |
+
head.resize(n_vocab);
|
| 28 |
+
tokens.resize(n_vocab * G * (N - 1));
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
int n_total = 0;
|
| 32 |
+
|
| 33 |
+
std::vector<int> cnt;
|
| 34 |
+
std::vector<int> head;
|
| 35 |
+
|
| 36 |
+
// [n_vocab][G][N - 1]
|
| 37 |
+
// for each token of the vocab, keep a ring-buffer of capacity G of n-grams of size N - 1
|
| 38 |
+
std::vector<llama_token> tokens;
|
| 39 |
+
};
|
| 40 |
+
|
| 41 |
+
int main(int argc, char ** argv) {
|
| 42 |
+
std::setlocale(LC_NUMERIC, "C");
|
| 43 |
+
|
| 44 |
+
common_params params;
|
| 45 |
+
|
| 46 |
+
common_init();
|
| 47 |
+
|
| 48 |
+
if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_COMMON)) {
|
| 49 |
+
return 1;
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
const int W = 15; // lookahead window
|
| 53 |
+
const int N = 5; // n-gram size
|
| 54 |
+
const int G = 15; // max verification n-grams
|
| 55 |
+
|
| 56 |
+
// lookahead requires W + G + 1 sequences for parallel Jacobi decoding
|
| 57 |
+
params.n_parallel = W + G + 1;
|
| 58 |
+
|
| 59 |
+
// unified KV cache is required for coupled sequences in batch splitting
|
| 60 |
+
params.kv_unified = true;
|
| 61 |
+
|
| 62 |
+
// init llama.cpp
|
| 63 |
+
llama_backend_init();
|
| 64 |
+
llama_numa_init(params.numa);
|
| 65 |
+
|
| 66 |
+
// load the target model
|
| 67 |
+
auto llama_init = common_init_from_params(params);
|
| 68 |
+
|
| 69 |
+
auto * model = llama_init->model();
|
| 70 |
+
auto * ctx = llama_init->context();
|
| 71 |
+
|
| 72 |
+
auto * mem = llama_get_memory(ctx);
|
| 73 |
+
|
| 74 |
+
const llama_vocab * vocab = llama_model_get_vocab(model);
|
| 75 |
+
|
| 76 |
+
// Tokenize the prompt
|
| 77 |
+
std::vector<llama_token> inp;
|
| 78 |
+
std::vector<llama_token> all;
|
| 79 |
+
|
| 80 |
+
inp = common_tokenize(ctx, params.prompt, true, true);
|
| 81 |
+
all = inp;
|
| 82 |
+
|
| 83 |
+
const int max_context_size = llama_n_ctx(ctx);
|
| 84 |
+
const int max_tokens_list_size = max_context_size - 4;
|
| 85 |
+
|
| 86 |
+
if ((int) inp.size() > max_tokens_list_size) {
|
| 87 |
+
LOG_ERR("%s: prompt too long (%d tokens, max %d)\n", __func__, (int) inp.size(), max_tokens_list_size);
|
| 88 |
+
return 1;
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
LOG("\n\n");
|
| 92 |
+
|
| 93 |
+
for (auto id : inp) {
|
| 94 |
+
LOG("%s", common_token_to_piece(ctx, id).c_str());
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
fflush(stderr);
|
| 98 |
+
|
| 99 |
+
const int n_input = inp.size();
|
| 100 |
+
|
| 101 |
+
const auto t_enc_start = ggml_time_us();
|
| 102 |
+
|
| 103 |
+
// eval the prompt
|
| 104 |
+
llama_decode(ctx, llama_batch_get_one( inp.data(), n_input - 1));
|
| 105 |
+
llama_decode(ctx, llama_batch_get_one(&inp.back(), 1));
|
| 106 |
+
|
| 107 |
+
for (int s = 1; s < W + G + 1; ++s) {
|
| 108 |
+
llama_memory_seq_cp(mem, 0, s, -1, -1);
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
const auto t_enc_end = ggml_time_us();
|
| 112 |
+
|
| 113 |
+
int n_predict = 0;
|
| 114 |
+
int n_accept = 0;
|
| 115 |
+
|
| 116 |
+
int n_past = inp.size();
|
| 117 |
+
|
| 118 |
+
llama_token id = 0;
|
| 119 |
+
|
| 120 |
+
// used to determine end of generation
|
| 121 |
+
bool has_eos = false;
|
| 122 |
+
|
| 123 |
+
// for each decoded batch, we have at most W + G + 1 distinct sequences:
|
| 124 |
+
// seq_id == 0 : the current input token
|
| 125 |
+
// seq_id [1, W] : tokens from the past N - 1 Jacobi iterations
|
| 126 |
+
// seq_id [W + 1, W + G] : verification n-grams
|
| 127 |
+
llama_batch batch = llama_batch_init(llama_n_ctx(ctx), 0, W + G + 1);
|
| 128 |
+
|
| 129 |
+
// target model sampling context
|
| 130 |
+
struct common_sampler * smpl = common_sampler_init(model, params.sampling);
|
| 131 |
+
|
| 132 |
+
// verification n-grams
|
| 133 |
+
std::vector<ngram_data> ngrams_cur(G);
|
| 134 |
+
|
| 135 |
+
// tokens for the past N - 1 Jacobi iterations
|
| 136 |
+
std::vector<llama_token> tokens_j_prev(W);
|
| 137 |
+
std::vector<std::vector<llama_token>> tokens_j(N - 1);
|
| 138 |
+
for (int j = 0; j < N - 1; j++) {
|
| 139 |
+
tokens_j[j].resize(W);
|
| 140 |
+
|
| 141 |
+
for (int i = 0; i < W; i++) {
|
| 142 |
+
// there are different ways to init these tokens
|
| 143 |
+
if (0) {
|
| 144 |
+
// initialize randomly from the prompt tokens
|
| 145 |
+
tokens_j[j][i] = all[1 + rand() % (all.size() - 1)];
|
| 146 |
+
} else {
|
| 147 |
+
// initialize with a sequence of increasing numbers
|
| 148 |
+
tokens_j[j][i] = 100 + i;
|
| 149 |
+
}
|
| 150 |
+
}
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
std::vector<llama_seq_id> seq_id_look;
|
| 154 |
+
|
| 155 |
+
// the input token belongs both to all sequences
|
| 156 |
+
std::vector<llama_seq_id> seq_id_all(W + G + 1);
|
| 157 |
+
for (int i = 0; i < W + G + 1; i++) {
|
| 158 |
+
seq_id_all[i] = i;
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
// here we keep adding new n-grams as we go
|
| 162 |
+
ngram_container ngrams_observed(llama_vocab_n_tokens(vocab), N, G);
|
| 163 |
+
|
| 164 |
+
const auto t_dec_start = ggml_time_us();
|
| 165 |
+
|
| 166 |
+
// sample first token
|
| 167 |
+
{
|
| 168 |
+
id = common_sampler_sample(smpl, ctx, 0);
|
| 169 |
+
|
| 170 |
+
common_sampler_accept(smpl, id, true);
|
| 171 |
+
|
| 172 |
+
{
|
| 173 |
+
const std::string token_str = common_token_to_piece(ctx, id);
|
| 174 |
+
|
| 175 |
+
LOG("%s", token_str.c_str());
|
| 176 |
+
fflush(stdout);
|
| 177 |
+
}
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
while (true) {
|
| 181 |
+
// build the mask from https://lmsys.org/blog/2023-11-21-lookahead-decoding/
|
| 182 |
+
//
|
| 183 |
+
// Example for W = 5, N = 4, G = 2:
|
| 184 |
+
// (I = input, L = lookahead, V = verification)
|
| 185 |
+
//
|
| 186 |
+
// Batch: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
| 187 |
+
// T: -2 -2 -2 -2 -1 -1 -1 -1 -1 0 0 0 0 0 0
|
| 188 |
+
// Info: I L L L L L L L L L L L L L L V V V V V V
|
| 189 |
+
// Pos: 0 1 2 3 4 1 2 3 4 5 2 3 4 5 6 1 2 3 1 2 3 (+ n_past)
|
| 190 |
+
// Logits: 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1
|
| 191 |
+
// ---------------------------------------------------------------------
|
| 192 |
+
// Seq: 0
|
| 193 |
+
// 1 1 1
|
| 194 |
+
// 2 2 2 2
|
| 195 |
+
// 3 3 3 3 3
|
| 196 |
+
// 4 4 4 4 4 4
|
| 197 |
+
// 5 5 5 5 5 5 5
|
| 198 |
+
// 6 6 6 6
|
| 199 |
+
// 7 7 7 7
|
| 200 |
+
// ---------------------------------------------------------------------
|
| 201 |
+
// | | | | | | | | | | |
|
| 202 |
+
// V V V V V | | | | | |
|
| 203 |
+
// j_tokens | | | | | |
|
| 204 |
+
// V V V V V V
|
| 205 |
+
// id
|
| 206 |
+
{
|
| 207 |
+
common_batch_clear(batch);
|
| 208 |
+
|
| 209 |
+
// current token - first token of the first level
|
| 210 |
+
common_batch_add(batch, id, n_past, seq_id_all, true);
|
| 211 |
+
|
| 212 |
+
// verification n-grams - queue this before the lookahead tokens for less KV cache fragmentation
|
| 213 |
+
{
|
| 214 |
+
const int g_cur = ngrams_observed.cnt[id];
|
| 215 |
+
|
| 216 |
+
ngrams_cur.resize(g_cur);
|
| 217 |
+
for (int g = 0; g < g_cur; g++) {
|
| 218 |
+
ngrams_cur[g].active = true;
|
| 219 |
+
ngrams_cur[g].tokens.resize(N);
|
| 220 |
+
ngrams_cur[g].i_batch.resize(N);
|
| 221 |
+
ngrams_cur[g].seq_id = W + 1 + g;
|
| 222 |
+
ngrams_cur[g].i_batch[0] = 0;
|
| 223 |
+
ngrams_cur[g].tokens [0] = id;
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
for (int j = 0; j < N - 1; j++) {
|
| 227 |
+
for (int g = 0; g < g_cur; g++) {
|
| 228 |
+
const int idx = id*(N - 1)*G + g*(N - 1);
|
| 229 |
+
|
| 230 |
+
const llama_token t = ngrams_observed.tokens[idx + j];
|
| 231 |
+
|
| 232 |
+
ngrams_cur[g].tokens [j + 1] = t;
|
| 233 |
+
ngrams_cur[g].i_batch[j + 1] = batch.n_tokens;
|
| 234 |
+
|
| 235 |
+
common_batch_add(batch, t, n_past + j + 1, { W + 1 + g }, true);
|
| 236 |
+
}
|
| 237 |
+
}
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
// fill the remaining W - 1 tokens for the first level
|
| 241 |
+
for (int i = 1; i < W; i++) {
|
| 242 |
+
seq_id_look.resize(W - i);
|
| 243 |
+
for (int j = 0; j < W - i; j++) {
|
| 244 |
+
seq_id_look[j] = i + j + 1;
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
common_batch_add(batch, tokens_j[0][i], n_past + i, seq_id_look, false);
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
// fill the rest of the levels
|
| 251 |
+
for (int j = 1; j < N - 1; j++) {
|
| 252 |
+
for (int i = 0; i < W; i++) {
|
| 253 |
+
common_batch_add(batch, tokens_j[j][i], n_past + j + i, { i + 1 }, j == N - 2);
|
| 254 |
+
}
|
| 255 |
+
}
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
if (llama_decode(ctx, batch) != 0) {
|
| 259 |
+
LOG_ERR("\n\n%s: llama_decode failed - increase KV cache size\n", __func__);
|
| 260 |
+
return 1;
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
int seq_id_best = 0;
|
| 264 |
+
|
| 265 |
+
for (int v = 0; v < N; ++v) {
|
| 266 |
+
int i_batch = 0;
|
| 267 |
+
|
| 268 |
+
// if no active ngrams are left, it means the sampled token does not pass the verification
|
| 269 |
+
if (v > 0) {
|
| 270 |
+
for (int g = 0; g < (int) ngrams_cur.size(); g++) {
|
| 271 |
+
if (ngrams_cur[g].active) {
|
| 272 |
+
i_batch = ngrams_cur[g].i_batch[v];
|
| 273 |
+
seq_id_best = ngrams_cur[g].seq_id;
|
| 274 |
+
|
| 275 |
+
++n_accept;
|
| 276 |
+
break;
|
| 277 |
+
}
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
// no more matches -> create a new batch
|
| 281 |
+
if (i_batch == 0) {
|
| 282 |
+
break;
|
| 283 |
+
}
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
// sample the next token
|
| 287 |
+
id = common_sampler_sample(smpl, ctx, i_batch);
|
| 288 |
+
|
| 289 |
+
common_sampler_accept(smpl, id, true);
|
| 290 |
+
|
| 291 |
+
// print
|
| 292 |
+
{
|
| 293 |
+
const std::string token_str = common_token_to_piece(ctx, id);
|
| 294 |
+
|
| 295 |
+
if (v == 0) {
|
| 296 |
+
LOG("%s", token_str.c_str());
|
| 297 |
+
} else {
|
| 298 |
+
// print light cyan
|
| 299 |
+
LOG("\033[0;96m%s\033[0m", token_str.c_str());
|
| 300 |
+
}
|
| 301 |
+
fflush(stdout);
|
| 302 |
+
|
| 303 |
+
if (llama_vocab_is_eog(vocab, id)) {
|
| 304 |
+
has_eos = true;
|
| 305 |
+
}
|
| 306 |
+
|
| 307 |
+
all.push_back(id);
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
++n_predict;
|
| 311 |
+
++n_past;
|
| 312 |
+
|
| 313 |
+
if ((params.n_predict >= 0 && n_predict > params.n_predict) || has_eos) {
|
| 314 |
+
break;
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
// verify across active n-grams
|
| 318 |
+
for (int g = 0; g < (int) ngrams_cur.size(); g++) {
|
| 319 |
+
if (ngrams_cur[g].active) {
|
| 320 |
+
if (v == N - 1) {
|
| 321 |
+
ngrams_cur[g].active = false;
|
| 322 |
+
} else {
|
| 323 |
+
if (id != ngrams_cur[g].tokens[v + 1]) {
|
| 324 |
+
ngrams_cur[g].active = false;
|
| 325 |
+
}
|
| 326 |
+
}
|
| 327 |
+
}
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
+
// print known n-grams starting with token id (debug)
|
| 331 |
+
if (0 && v == 0) {
|
| 332 |
+
if (ngrams_observed.cnt[id] > 0) {
|
| 333 |
+
LOG("\n - %d n-grams starting with '%s'\n", ngrams_observed.cnt[id], common_token_to_piece(ctx, id).c_str());
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
for (int i = 0; i < ngrams_observed.cnt[id]; i++) {
|
| 337 |
+
LOG(" - ngram %2d: ", i);
|
| 338 |
+
|
| 339 |
+
const int idx = id*(N - 1)*G + i*(N - 1);
|
| 340 |
+
|
| 341 |
+
for (int j = 0; j < N - 1; j++) {
|
| 342 |
+
const std::string token_str = common_token_to_piece(ctx, ngrams_observed.tokens[idx + j]);
|
| 343 |
+
|
| 344 |
+
LOG("%s", token_str.c_str());
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
LOG("\n");
|
| 348 |
+
}
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
// update lookahead tokens
|
| 352 |
+
{
|
| 353 |
+
for (int i = 0; i < W; i++) {
|
| 354 |
+
tokens_j_prev[i] = tokens_j[0][i];
|
| 355 |
+
}
|
| 356 |
+
|
| 357 |
+
for (int j = 0; j < N - 2; j++) {
|
| 358 |
+
tokens_j[j] = tokens_j[j + 1];
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
if (v == 0) {
|
| 362 |
+
// sample from the last level
|
| 363 |
+
for (int i = 0; i < W; i++) {
|
| 364 |
+
tokens_j[N - 2][i] = common_sampler_sample(smpl, ctx, ngrams_cur.size()*(N-1) + W*(N - 2) + i);
|
| 365 |
+
}
|
| 366 |
+
} else {
|
| 367 |
+
for (int i = 0; i < W; i++) {
|
| 368 |
+
// there are different ways to init these tokens
|
| 369 |
+
if (0) {
|
| 370 |
+
// random init
|
| 371 |
+
tokens_j[N - 2][i] = all[1 + rand() % (all.size() - 1)];
|
| 372 |
+
} else {
|
| 373 |
+
// init from the previous level
|
| 374 |
+
tokens_j[N - 2][i] = tokens_j[0][i];
|
| 375 |
+
}
|
| 376 |
+
}
|
| 377 |
+
}
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
// update observed ngrams
|
| 381 |
+
if (v == 0) {
|
| 382 |
+
// the first token of the n-gram is determined by the index in the container so it is not stored
|
| 383 |
+
std::vector<llama_token> ngram(N - 1);
|
| 384 |
+
|
| 385 |
+
// n-gram generation
|
| 386 |
+
// ref: https://github.com/hao-ai-lab/LookaheadDecoding/issues/14#issuecomment-1826198518
|
| 387 |
+
for (int f = 0; f < W; ++f) {
|
| 388 |
+
const int ft = tokens_j_prev[f]; // first token of the n-gram
|
| 389 |
+
|
| 390 |
+
for (int j = 0; j < N - 1; ++j) {
|
| 391 |
+
ngram[j] = tokens_j[j][f];
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
// filter-out repeating n-grams
|
| 395 |
+
{
|
| 396 |
+
bool is_unique = true;
|
| 397 |
+
|
| 398 |
+
for (int k = 0; k < ngrams_observed.cnt[ft]; ++k) {
|
| 399 |
+
const int idx = ft*(N - 1)*G + k*(N - 1);
|
| 400 |
+
|
| 401 |
+
bool is_match = true;
|
| 402 |
+
for (int j = 0; j < N - 1; ++j) {
|
| 403 |
+
if (ngrams_observed.tokens[idx + j] != ngram[j]) {
|
| 404 |
+
is_match = false;
|
| 405 |
+
break;
|
| 406 |
+
}
|
| 407 |
+
}
|
| 408 |
+
|
| 409 |
+
if (is_match) {
|
| 410 |
+
is_unique = false;
|
| 411 |
+
break;
|
| 412 |
+
}
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
if (!is_unique) {
|
| 416 |
+
continue;
|
| 417 |
+
}
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
const int head = ngrams_observed.head[ft];
|
| 421 |
+
const int idx = ft*(N - 1)*G + head*(N - 1);
|
| 422 |
+
|
| 423 |
+
for (int i = 0; i < N - 1; i++) {
|
| 424 |
+
ngrams_observed.tokens[idx + i] = ngram[i];
|
| 425 |
+
}
|
| 426 |
+
|
| 427 |
+
ngrams_observed.cnt[ft] = std::min(G, ngrams_observed.cnt[ft] + 1);
|
| 428 |
+
ngrams_observed.head[ft] = (head + 1) % G;
|
| 429 |
+
|
| 430 |
+
ngrams_observed.n_total++;
|
| 431 |
+
}
|
| 432 |
+
}
|
| 433 |
+
}
|
| 434 |
+
|
| 435 |
+
if ((params.n_predict >= 0 && n_predict > params.n_predict) || has_eos) {
|
| 436 |
+
break;
|
| 437 |
+
}
|
| 438 |
+
|
| 439 |
+
// KV cache management
|
| 440 |
+
// if no verification token matched, we simply remove all cells from this batch -> no fragmentation
|
| 441 |
+
llama_memory_seq_rm(mem, -1, n_past, -1);
|
| 442 |
+
|
| 443 |
+
if (seq_id_best != 0) {
|
| 444 |
+
// if a verification token matched, we keep the best sequence and remove the rest
|
| 445 |
+
// this leads to some KV cache fragmentation
|
| 446 |
+
llama_memory_seq_keep(mem, seq_id_best);
|
| 447 |
+
llama_memory_seq_cp (mem, seq_id_best, 0, -1, -1);
|
| 448 |
+
llama_memory_seq_rm (mem, seq_id_best, -1, -1);
|
| 449 |
+
|
| 450 |
+
for (int s = 1; s < W + G + 1; ++s) {
|
| 451 |
+
llama_memory_seq_cp(mem, 0, s, -1, -1);
|
| 452 |
+
}
|
| 453 |
+
}
|
| 454 |
+
}
|
| 455 |
+
|
| 456 |
+
auto t_dec_end = ggml_time_us();
|
| 457 |
+
|
| 458 |
+
LOG("\n\n");
|
| 459 |
+
|
| 460 |
+
LOG_INF("encoded %4d tokens in %8.3f seconds, speed: %8.3f t/s\n", n_input, (t_enc_end - t_enc_start) / 1e6f, inp.size() / ((t_enc_end - t_enc_start) / 1e6f));
|
| 461 |
+
LOG_INF("decoded %4d tokens in %8.3f seconds, speed: %8.3f t/s\n", n_predict, (t_dec_end - t_dec_start) / 1e6f, n_predict / ((t_dec_end - t_dec_start) / 1e6f));
|
| 462 |
+
|
| 463 |
+
LOG_INF("\n");
|
| 464 |
+
LOG_INF("W = %2d\n", W);
|
| 465 |
+
LOG_INF("N = %2d\n", N);
|
| 466 |
+
LOG_INF("G = %2d\n", G);
|
| 467 |
+
LOG_INF("\n");
|
| 468 |
+
LOG_INF("n_predict = %d\n", n_predict);
|
| 469 |
+
LOG_INF("n_accept = %d\n", n_accept);
|
| 470 |
+
|
| 471 |
+
LOG_INF("\n");
|
| 472 |
+
common_perf_print(ctx, smpl);
|
| 473 |
+
|
| 474 |
+
common_sampler_free(smpl);
|
| 475 |
+
|
| 476 |
+
llama_batch_free(batch);
|
| 477 |
+
|
| 478 |
+
llama_backend_free();
|
| 479 |
+
|
| 480 |
+
LOG("\n\n");
|
| 481 |
+
|
| 482 |
+
return 0;
|
| 483 |
+
}
|
examples/lookup/CMakeLists.txt
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
set(TARGET llama-lookup)
|
| 2 |
+
add_executable(${TARGET} lookup.cpp)
|
| 3 |
+
install(TARGETS ${TARGET} RUNTIME)
|
| 4 |
+
target_link_libraries(${TARGET} PRIVATE llama-common llama ${CMAKE_THREAD_LIBS_INIT})
|
| 5 |
+
target_compile_features(${TARGET} PRIVATE cxx_std_17)
|
| 6 |
+
|
| 7 |
+
set(TARGET llama-lookup-create)
|
| 8 |
+
add_executable(${TARGET} lookup-create.cpp)
|
| 9 |
+
install(TARGETS ${TARGET} RUNTIME)
|
| 10 |
+
target_link_libraries(${TARGET} PRIVATE llama-common llama ${CMAKE_THREAD_LIBS_INIT})
|
| 11 |
+
target_compile_features(${TARGET} PRIVATE cxx_std_17)
|
| 12 |
+
|
| 13 |
+
set(TARGET llama-lookup-merge)
|
| 14 |
+
add_executable(${TARGET} lookup-merge.cpp)
|
| 15 |
+
install(TARGETS ${TARGET} RUNTIME)
|
| 16 |
+
target_link_libraries(${TARGET} PRIVATE llama-common llama ${CMAKE_THREAD_LIBS_INIT})
|
| 17 |
+
target_compile_features(${TARGET} PRIVATE cxx_std_17)
|
| 18 |
+
|
| 19 |
+
set(TARGET llama-lookup-stats)
|
| 20 |
+
add_executable(${TARGET} lookup-stats.cpp)
|
| 21 |
+
install(TARGETS ${TARGET} RUNTIME)
|
| 22 |
+
target_link_libraries(${TARGET} PRIVATE llama-common llama ${CMAKE_THREAD_LIBS_INIT})
|
| 23 |
+
target_compile_features(${TARGET} PRIVATE cxx_std_17)
|
examples/lookup/README.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# llama.cpp/examples/lookup
|
| 2 |
+
|
| 3 |
+
Demonstration of Prompt Lookup Decoding
|
| 4 |
+
|
| 5 |
+
https://github.com/apoorvumang/prompt-lookup-decoding
|
| 6 |
+
|
| 7 |
+
The key parameters for lookup decoding are `ngram_min`, `ngram_max` and `n_draft`. The first two determine the size of the ngrams to search for in the prompt for a match. The latter specifies how many subsequent tokens to draft if a match is found.
|
| 8 |
+
|
| 9 |
+
More info:
|
| 10 |
+
|
| 11 |
+
https://github.com/ggml-org/llama.cpp/pull/4484
|
| 12 |
+
https://github.com/ggml-org/llama.cpp/issues/4226
|
examples/lookup/lookup-create.cpp
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "arg.h"
|
| 2 |
+
#include "common.h"
|
| 3 |
+
#include "ngram-cache.h"
|
| 4 |
+
#include "llama.h"
|
| 5 |
+
|
| 6 |
+
#include <clocale>
|
| 7 |
+
#include <string>
|
| 8 |
+
#include <vector>
|
| 9 |
+
|
| 10 |
+
int main(int argc, char ** argv){
|
| 11 |
+
std::setlocale(LC_NUMERIC, "C");
|
| 12 |
+
|
| 13 |
+
common_params params;
|
| 14 |
+
|
| 15 |
+
common_init();
|
| 16 |
+
|
| 17 |
+
if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_LOOKUP)) {
|
| 18 |
+
return 1;
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
// init llama.cpp
|
| 22 |
+
llama_backend_init();
|
| 23 |
+
llama_numa_init(params.numa);
|
| 24 |
+
|
| 25 |
+
// load the model
|
| 26 |
+
auto llama_init = common_init_from_params(params);
|
| 27 |
+
|
| 28 |
+
auto * model = llama_init->model();
|
| 29 |
+
auto * ctx = llama_init->context();
|
| 30 |
+
|
| 31 |
+
GGML_ASSERT(model != nullptr);
|
| 32 |
+
|
| 33 |
+
// tokenize the prompt
|
| 34 |
+
std::vector<llama_token> inp;
|
| 35 |
+
inp = common_tokenize(ctx, params.prompt, true, true);
|
| 36 |
+
fprintf(stderr, "%s: tokenization done\n", __func__);
|
| 37 |
+
|
| 38 |
+
common_ngram_cache ngram_cache;
|
| 39 |
+
common_ngram_cache_update(ngram_cache, LLAMA_NGRAM_STATIC, LLAMA_NGRAM_STATIC, inp, inp.size(), true);
|
| 40 |
+
fprintf(stderr, "%s: hashing done, writing file to %s\n", __func__, params.speculative.ngram_cache.lookup_cache_static.c_str());
|
| 41 |
+
|
| 42 |
+
common_ngram_cache_save(ngram_cache, params.speculative.ngram_cache.lookup_cache_static);
|
| 43 |
+
|
| 44 |
+
return 0;
|
| 45 |
+
}
|
examples/lookup/lookup-merge.cpp
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "ggml.h"
|
| 2 |
+
#include "llama.h"
|
| 3 |
+
#include "common.h"
|
| 4 |
+
#include "ngram-cache.h"
|
| 5 |
+
|
| 6 |
+
#include <clocale>
|
| 7 |
+
#include <cstdint>
|
| 8 |
+
#include <cstdio>
|
| 9 |
+
#include <fstream>
|
| 10 |
+
#include <iostream>
|
| 11 |
+
#include <string>
|
| 12 |
+
#include <unordered_map>
|
| 13 |
+
#include <vector>
|
| 14 |
+
|
| 15 |
+
static void print_usage(char* argv0) {
|
| 16 |
+
fprintf(stderr, "Merges multiple lookup cache files into a single one.\n");
|
| 17 |
+
fprintf(stderr, "Usage: %s [--help] lookup_part_1.bin lookup_part_2.bin ... lookup_merged.bin\n", argv0);
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
int main(int argc, char ** argv){
|
| 21 |
+
std::setlocale(LC_NUMERIC, "C");
|
| 22 |
+
|
| 23 |
+
if (argc < 3) {
|
| 24 |
+
print_usage(argv[0]);
|
| 25 |
+
exit(1);
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
std::vector<std::string> args;
|
| 29 |
+
args.resize(argc-1);
|
| 30 |
+
for (int i = 0; i < argc-1; ++i) {
|
| 31 |
+
args[i] = argv[i+1];
|
| 32 |
+
if (args[i] == "-h" || args[i] == "--help") {
|
| 33 |
+
print_usage(argv[0]);
|
| 34 |
+
exit(0);
|
| 35 |
+
}
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
fprintf(stderr, "lookup-merge: loading file %s\n", args[0].c_str());
|
| 39 |
+
common_ngram_cache ngram_cache_merged = common_ngram_cache_load(args[0]);
|
| 40 |
+
|
| 41 |
+
for (size_t i = 1; i < args.size()-1; ++i) {
|
| 42 |
+
fprintf(stderr, "lookup-merge: loading file %s\n", args[i].c_str());
|
| 43 |
+
common_ngram_cache ngram_cache = common_ngram_cache_load(args[i]);
|
| 44 |
+
|
| 45 |
+
common_ngram_cache_merge(ngram_cache_merged, ngram_cache);
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
fprintf(stderr, "lookup-merge: saving file %s\n", args.back().c_str());
|
| 49 |
+
common_ngram_cache_save(ngram_cache_merged, args.back());
|
| 50 |
+
}
|
examples/lookup/lookup-stats.cpp
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "arg.h"
|
| 2 |
+
#include "common.h"
|
| 3 |
+
#include "log.h"
|
| 4 |
+
#include "ngram-cache.h"
|
| 5 |
+
#include "llama.h"
|
| 6 |
+
#include "ggml.h"
|
| 7 |
+
|
| 8 |
+
#include <cinttypes>
|
| 9 |
+
#include <clocale>
|
| 10 |
+
#include <cstdint>
|
| 11 |
+
#include <cstdio>
|
| 12 |
+
#include <fstream>
|
| 13 |
+
#include <string>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
int main(int argc, char ** argv){
|
| 17 |
+
std::setlocale(LC_NUMERIC, "C");
|
| 18 |
+
|
| 19 |
+
common_params params;
|
| 20 |
+
|
| 21 |
+
common_init();
|
| 22 |
+
|
| 23 |
+
if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_LOOKUP)) {
|
| 24 |
+
return 1;
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
const int n_draft = params.speculative.draft.n_max;
|
| 28 |
+
|
| 29 |
+
// init llama.cpp
|
| 30 |
+
llama_backend_init();
|
| 31 |
+
llama_numa_init(params.numa);
|
| 32 |
+
|
| 33 |
+
// load the model
|
| 34 |
+
auto llama_init = common_init_from_params(params);
|
| 35 |
+
|
| 36 |
+
llama_context * ctx = llama_init->context();
|
| 37 |
+
|
| 38 |
+
// tokenize the prompt
|
| 39 |
+
std::vector<llama_token> inp;
|
| 40 |
+
inp = common_tokenize(ctx, params.prompt, true, true);
|
| 41 |
+
|
| 42 |
+
common_ngram_cache ngram_cache_context;
|
| 43 |
+
common_ngram_cache ngram_cache_dynamic;
|
| 44 |
+
common_ngram_cache ngram_cache_static;
|
| 45 |
+
|
| 46 |
+
int64_t t_draft_flat_us = 0;
|
| 47 |
+
int64_t t_draft_us = 0;
|
| 48 |
+
|
| 49 |
+
{
|
| 50 |
+
const int64_t t_start_draft_us = ggml_time_us();
|
| 51 |
+
|
| 52 |
+
if (!params.speculative.ngram_cache.lookup_cache_static.empty()) {
|
| 53 |
+
try {
|
| 54 |
+
ngram_cache_static = common_ngram_cache_load(params.speculative.ngram_cache.lookup_cache_static);
|
| 55 |
+
} catch (std::ifstream::failure const &) {
|
| 56 |
+
LOG_ERR("failed to open static lookup cache: %s", params.speculative.ngram_cache.lookup_cache_static.c_str());
|
| 57 |
+
exit(1);
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
if (!params.speculative.ngram_cache.lookup_cache_dynamic.empty()) {
|
| 62 |
+
try {
|
| 63 |
+
ngram_cache_dynamic = common_ngram_cache_load(params.speculative.ngram_cache.lookup_cache_dynamic);
|
| 64 |
+
} catch (std::ifstream::failure const &) {} // if the file does not exist it will simply be created at the end of the program
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
t_draft_flat_us += ggml_time_us() - t_start_draft_us;
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
const int n_input = inp.size();
|
| 71 |
+
const int n_ctx = llama_n_ctx(ctx);
|
| 72 |
+
|
| 73 |
+
int n_drafted = 0;
|
| 74 |
+
int n_accept = 0;
|
| 75 |
+
|
| 76 |
+
const int64_t t_start_ms = ggml_time_ms();
|
| 77 |
+
|
| 78 |
+
// Iterate over input tokens in chunks of size n_ctx.
|
| 79 |
+
// Each chunk is treated as if a sequential generation but with pre-determined tokens to ensure reproducibility.
|
| 80 |
+
for (int i_start = 0; i_start + n_ctx < n_input; i_start += n_ctx) {
|
| 81 |
+
const std::vector<llama_token> inp_slice(inp.begin() + i_start, inp.begin() + i_start + n_ctx);
|
| 82 |
+
std::vector<llama_token> pseudo_output;
|
| 83 |
+
pseudo_output.push_back(inp_slice[0]);
|
| 84 |
+
|
| 85 |
+
while ((int) pseudo_output.size() < n_ctx) {
|
| 86 |
+
// Simulate drafting and decoding from draft:
|
| 87 |
+
std::vector<llama_token> draft;
|
| 88 |
+
draft.push_back(pseudo_output.back());
|
| 89 |
+
|
| 90 |
+
{
|
| 91 |
+
const int64_t t_start_draft_us = ggml_time_us();
|
| 92 |
+
common_ngram_cache_draft(pseudo_output, draft, n_draft, LLAMA_NGRAM_MIN, LLAMA_NGRAM_MAX, ngram_cache_context, ngram_cache_dynamic, ngram_cache_static);
|
| 93 |
+
t_draft_us += ggml_time_us() - t_start_draft_us;
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
n_drafted += draft.size() - 1;
|
| 97 |
+
|
| 98 |
+
for (size_t j = 1; j < draft.size() && (int) pseudo_output.size() < n_ctx; ++j) {
|
| 99 |
+
const llama_token ground_truth = inp_slice[pseudo_output.size()];
|
| 100 |
+
const llama_token drafted = draft[j];
|
| 101 |
+
|
| 102 |
+
if (ground_truth != drafted) {
|
| 103 |
+
break;
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
++n_accept;
|
| 107 |
+
pseudo_output.push_back(ground_truth);
|
| 108 |
+
|
| 109 |
+
{
|
| 110 |
+
const int64_t t_start_draft_us = ggml_time_us();
|
| 111 |
+
common_ngram_cache_update(ngram_cache_context, LLAMA_NGRAM_MIN, LLAMA_NGRAM_MAX, pseudo_output, 1, false);
|
| 112 |
+
t_draft_us += ggml_time_us() - t_start_draft_us;
|
| 113 |
+
}
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
// After each simulated batch decoding simulate the sampling of a single token:
|
| 117 |
+
if ((int) pseudo_output.size() < n_ctx) {
|
| 118 |
+
pseudo_output.push_back(inp_slice[pseudo_output.size()]);
|
| 119 |
+
{
|
| 120 |
+
const int64_t t_start_draft_us = ggml_time_us();
|
| 121 |
+
common_ngram_cache_update(ngram_cache_context, LLAMA_NGRAM_MIN, LLAMA_NGRAM_MAX, pseudo_output, 1, false);
|
| 122 |
+
t_draft_us += ggml_time_us() - t_start_draft_us;
|
| 123 |
+
}
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
draft.erase(draft.begin());
|
| 127 |
+
|
| 128 |
+
}
|
| 129 |
+
if (i_start > 0 && i_start / 100000 != (i_start - n_ctx) / 100000) {
|
| 130 |
+
const int64_t t_now_ms = ggml_time_ms();
|
| 131 |
+
const int64_t eta_ms = (n_input - i_start) * (t_now_ms - t_start_ms) / i_start;
|
| 132 |
+
const int64_t eta_min = eta_ms / (60*1000);
|
| 133 |
+
const int64_t eta_s = (eta_ms - 60*1000*eta_min) / 1000;
|
| 134 |
+
|
| 135 |
+
LOG_INF("lookup-stats: %d/%d done, ETA: %02" PRId64 ":%02" PRId64 "\n", i_start, n_input, eta_min, eta_s);
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
// After each chunk, update the dynamic ngram cache with the context ngram cache:
|
| 139 |
+
common_ngram_cache_merge(ngram_cache_dynamic, ngram_cache_context);
|
| 140 |
+
ngram_cache_context.clear();
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
LOG("\n");
|
| 144 |
+
|
| 145 |
+
LOG_INF("\n");
|
| 146 |
+
LOG_INF("n_draft = %d\n", n_draft);
|
| 147 |
+
LOG_INF("n_predict = %d\n", n_input - n_input % n_ctx);
|
| 148 |
+
LOG_INF("n_drafted = %d\n", n_drafted);
|
| 149 |
+
LOG_INF("t_draft_flat = %.2f ms\n", t_draft_flat_us*1e-3);
|
| 150 |
+
LOG_INF("t_draft = %.2f ms, %.2f us per token, %.2f tokens per second\n",
|
| 151 |
+
t_draft_us*1e-3, 1.0f*t_draft_us/n_drafted, n_drafted/(1e-6*t_draft_us));
|
| 152 |
+
LOG_INF("n_accept = %d\n", n_accept);
|
| 153 |
+
LOG_INF("accept = %.3f%%\n", 100.0f * n_accept / n_drafted);
|
| 154 |
+
|
| 155 |
+
llama_backend_free();
|
| 156 |
+
|
| 157 |
+
LOG("\n\n");
|
| 158 |
+
|
| 159 |
+
return 0;
|
| 160 |
+
}
|
examples/lookup/lookup.cpp
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "arg.h"
|
| 2 |
+
#include "ggml.h"
|
| 3 |
+
#include "common.h"
|
| 4 |
+
#include "ngram-cache.h"
|
| 5 |
+
#include "sampling.h"
|
| 6 |
+
#include "speculative.h"
|
| 7 |
+
#include "log.h"
|
| 8 |
+
#include "llama.h"
|
| 9 |
+
|
| 10 |
+
#include <algorithm>
|
| 11 |
+
#include <clocale>
|
| 12 |
+
#include <cstdint>
|
| 13 |
+
#include <cstdio>
|
| 14 |
+
#include <fstream>
|
| 15 |
+
#include <string>
|
| 16 |
+
#include <vector>
|
| 17 |
+
|
| 18 |
+
int main(int argc, char ** argv){
|
| 19 |
+
std::setlocale(LC_NUMERIC, "C");
|
| 20 |
+
|
| 21 |
+
common_params params;
|
| 22 |
+
|
| 23 |
+
common_init();
|
| 24 |
+
|
| 25 |
+
if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_LOOKUP)) {
|
| 26 |
+
return 1;
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
// max. number of additional tokens to draft if match is found
|
| 30 |
+
const int n_draft = params.speculative.draft.n_max;
|
| 31 |
+
|
| 32 |
+
const auto output_limits = common_speculative_get_output_limits(params.n_batch, params.n_parallel, n_draft);
|
| 33 |
+
params.n_outputs_max = output_limits.total;
|
| 34 |
+
params.n_outputs_max_per_seq = output_limits.per_seq;
|
| 35 |
+
|
| 36 |
+
// init llama.cpp
|
| 37 |
+
llama_backend_init();
|
| 38 |
+
llama_numa_init(params.numa);
|
| 39 |
+
|
| 40 |
+
// load the model
|
| 41 |
+
auto llama_init = common_init_from_params(params);
|
| 42 |
+
|
| 43 |
+
auto * model = llama_init->model();
|
| 44 |
+
auto * ctx = llama_init->context();
|
| 45 |
+
|
| 46 |
+
const llama_vocab * vocab = llama_model_get_vocab(model);
|
| 47 |
+
|
| 48 |
+
// tokenize the prompt
|
| 49 |
+
std::vector<llama_token> inp;
|
| 50 |
+
inp = common_tokenize(ctx, params.prompt, true, true);
|
| 51 |
+
|
| 52 |
+
common_ngram_cache ngram_cache_context;
|
| 53 |
+
common_ngram_cache ngram_cache_dynamic;
|
| 54 |
+
common_ngram_cache ngram_cache_static;
|
| 55 |
+
int64_t t_draft_flat_us = 0;
|
| 56 |
+
int64_t t_draft_us = 0;
|
| 57 |
+
|
| 58 |
+
{
|
| 59 |
+
// Fill up context ngram cache with tokens from user input:
|
| 60 |
+
const int64_t t_start_draft_us = ggml_time_us();
|
| 61 |
+
common_ngram_cache_update(ngram_cache_context, LLAMA_NGRAM_MIN, LLAMA_NGRAM_MAX, inp, inp.size(), false);
|
| 62 |
+
|
| 63 |
+
if (!params.speculative.ngram_cache.lookup_cache_static.empty()) {
|
| 64 |
+
try {
|
| 65 |
+
ngram_cache_static = common_ngram_cache_load(params.speculative.ngram_cache.lookup_cache_static);
|
| 66 |
+
} catch (std::ifstream::failure const &) {
|
| 67 |
+
LOG_ERR("failed to open static lookup cache: %s", params.speculative.ngram_cache.lookup_cache_static.c_str());
|
| 68 |
+
exit(1);
|
| 69 |
+
}
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
if (!params.speculative.ngram_cache.lookup_cache_dynamic.empty()) {
|
| 73 |
+
try {
|
| 74 |
+
ngram_cache_dynamic = common_ngram_cache_load(params.speculative.ngram_cache.lookup_cache_dynamic);
|
| 75 |
+
} catch (std::ifstream::failure const &) {} // if the file does not exist it will simply be created at the end of the program
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
t_draft_flat_us += ggml_time_us() - t_start_draft_us;
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
const int max_context_size = llama_n_ctx(ctx);
|
| 82 |
+
const int max_tokens_list_size = max_context_size - 4;
|
| 83 |
+
|
| 84 |
+
if ((int) inp.size() > max_tokens_list_size) {
|
| 85 |
+
LOG_ERR("%s: prompt too long (%d tokens, max %d)\n", __func__, (int) inp.size(), max_tokens_list_size);
|
| 86 |
+
return 1;
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
LOG("\n\n");
|
| 90 |
+
|
| 91 |
+
for (auto id : inp) {
|
| 92 |
+
LOG("%s", common_token_to_piece(ctx, id).c_str());
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
fflush(stderr);
|
| 96 |
+
|
| 97 |
+
const int n_input = inp.size();
|
| 98 |
+
|
| 99 |
+
const auto t_enc_start = ggml_time_us();
|
| 100 |
+
|
| 101 |
+
llama_decode(ctx, llama_batch_get_one( inp.data(), n_input - 1));
|
| 102 |
+
llama_decode(ctx, llama_batch_get_one(&inp.back(), 1));
|
| 103 |
+
|
| 104 |
+
const auto t_enc_end = ggml_time_us();
|
| 105 |
+
|
| 106 |
+
int n_predict = 0;
|
| 107 |
+
int n_drafted = 0;
|
| 108 |
+
int n_accept = 0;
|
| 109 |
+
|
| 110 |
+
int n_past = inp.size();
|
| 111 |
+
|
| 112 |
+
bool has_eos = false;
|
| 113 |
+
|
| 114 |
+
struct common_sampler * smpl = common_sampler_init(model, params.sampling);
|
| 115 |
+
|
| 116 |
+
std::vector<llama_token> draft;
|
| 117 |
+
|
| 118 |
+
llama_batch batch_tgt = llama_batch_init(llama_n_ctx(ctx), 0, 1);
|
| 119 |
+
|
| 120 |
+
const auto t_dec_start = ggml_time_us();
|
| 121 |
+
|
| 122 |
+
while (true) {
|
| 123 |
+
// print current draft sequence
|
| 124 |
+
LOG_DBG("drafted %s\n", string_from(ctx, draft).c_str());
|
| 125 |
+
|
| 126 |
+
int i_dft = 0;
|
| 127 |
+
while (true) {
|
| 128 |
+
// sample from the target model
|
| 129 |
+
llama_token id = common_sampler_sample(smpl, ctx, i_dft);
|
| 130 |
+
|
| 131 |
+
common_sampler_accept(smpl, id, true);
|
| 132 |
+
|
| 133 |
+
const std::string token_str = common_token_to_piece(ctx, id);
|
| 134 |
+
|
| 135 |
+
if (!params.use_color) {
|
| 136 |
+
LOG("%s", token_str.c_str());
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
if (llama_vocab_is_eog(vocab, id)) {
|
| 140 |
+
has_eos = true;
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
++n_predict;
|
| 144 |
+
|
| 145 |
+
// check if the target token matches the draft
|
| 146 |
+
if (i_dft < (int) draft.size() && id == draft[i_dft]) {
|
| 147 |
+
LOG_DBG("the sampled target token matches the %dth drafted token (%d, '%s') - accepted\n", i_dft, id, token_str.c_str());
|
| 148 |
+
++n_accept;
|
| 149 |
+
++n_past;
|
| 150 |
+
++i_dft;
|
| 151 |
+
inp.push_back(id);
|
| 152 |
+
{
|
| 153 |
+
// Update context ngram cache with the newly accepted token:
|
| 154 |
+
const int64_t t_start_draft_us = ggml_time_us();
|
| 155 |
+
common_ngram_cache_update(ngram_cache_context, LLAMA_NGRAM_MIN, LLAMA_NGRAM_MAX, inp, 1, false);
|
| 156 |
+
t_draft_us += ggml_time_us() - t_start_draft_us;
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
if (params.use_color) {
|
| 160 |
+
// color accepted draft token
|
| 161 |
+
LOG("\033[34m%s\033[0m", token_str.c_str());
|
| 162 |
+
fflush(stdout);
|
| 163 |
+
}
|
| 164 |
+
continue;
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
if (params.use_color) {
|
| 168 |
+
LOG("%s", token_str.c_str());
|
| 169 |
+
}
|
| 170 |
+
fflush(stdout);
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
LOG_DBG("the sampled target token (%d, '%s') did not match, or we ran out of drafted tokens\n", id, token_str.c_str());
|
| 174 |
+
|
| 175 |
+
draft.clear();
|
| 176 |
+
draft.push_back(id);
|
| 177 |
+
inp.push_back(id);
|
| 178 |
+
{
|
| 179 |
+
// Update context ngram cache with the newly accepted token:
|
| 180 |
+
const int64_t t_start_draft_us = ggml_time_us();
|
| 181 |
+
common_ngram_cache_update(ngram_cache_context, LLAMA_NGRAM_MIN, LLAMA_NGRAM_MAX, inp, 1, false);
|
| 182 |
+
t_draft_us += ggml_time_us() - t_start_draft_us;
|
| 183 |
+
}
|
| 184 |
+
break;
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
if ((params.n_predict > 0 && n_predict > params.n_predict) || has_eos) {
|
| 188 |
+
break;
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
// KV cache management
|
| 192 |
+
// clean the cache of draft tokens that weren't accepted
|
| 193 |
+
llama_memory_seq_rm(llama_get_memory(ctx), 0, n_past, -1);
|
| 194 |
+
|
| 195 |
+
common_batch_clear(batch_tgt);
|
| 196 |
+
common_batch_add(batch_tgt, draft[0], n_past, { 0 }, true);
|
| 197 |
+
|
| 198 |
+
// Draft already contains a single token sampled from the model:
|
| 199 |
+
GGML_ASSERT(draft.size() == 1);
|
| 200 |
+
GGML_ASSERT(draft[0] == inp.back());
|
| 201 |
+
const int64_t t_start_draft_us = ggml_time_us();
|
| 202 |
+
|
| 203 |
+
common_ngram_cache_draft(inp, draft, n_draft, LLAMA_NGRAM_MIN, LLAMA_NGRAM_MAX, ngram_cache_context, ngram_cache_dynamic, ngram_cache_static);
|
| 204 |
+
|
| 205 |
+
for (size_t i = 1; i < draft.size(); ++i) {
|
| 206 |
+
common_batch_add(batch_tgt, draft[i], n_past + i, { 0 }, true);
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
t_draft_us += ggml_time_us() - t_start_draft_us;
|
| 210 |
+
n_drafted += draft.size() - 1;
|
| 211 |
+
|
| 212 |
+
llama_decode(ctx, batch_tgt);
|
| 213 |
+
++n_past;
|
| 214 |
+
|
| 215 |
+
draft.erase(draft.begin());
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
auto t_dec_end = ggml_time_us();
|
| 219 |
+
|
| 220 |
+
// Update dynamic ngram cache with context ngram cache and save it to disk:
|
| 221 |
+
common_ngram_cache_merge(ngram_cache_dynamic, ngram_cache_context);
|
| 222 |
+
common_ngram_cache_save(ngram_cache_dynamic, params.speculative.ngram_cache.lookup_cache_dynamic);
|
| 223 |
+
|
| 224 |
+
LOG("\n\n");
|
| 225 |
+
|
| 226 |
+
LOG_INF("encoded %4d tokens in %8.3f seconds, speed: %8.3f t/s\n", n_input, (t_enc_end - t_enc_start) / 1e6f, inp.size() / ((t_enc_end - t_enc_start) / 1e6f));
|
| 227 |
+
LOG_INF("decoded %4d tokens in %8.3f seconds, speed: %8.3f t/s\n", n_predict, (t_dec_end - t_dec_start) / 1e6f, n_predict / ((t_dec_end - t_dec_start) / 1e6f));
|
| 228 |
+
|
| 229 |
+
LOG_INF("\n");
|
| 230 |
+
LOG_INF("n_draft = %d\n", n_draft);
|
| 231 |
+
LOG_INF("n_predict = %d\n", n_predict);
|
| 232 |
+
LOG_INF("n_drafted = %d\n", n_drafted);
|
| 233 |
+
LOG_INF("t_draft_flat = %.2f ms\n", t_draft_flat_us*1e-3);
|
| 234 |
+
LOG_INF("t_draft = %.2f ms, %.2f us per token, %.2f tokens per second\n",
|
| 235 |
+
t_draft_us*1e-3, 1.0f*t_draft_us/n_drafted, n_drafted/(1e-6*t_draft_us));
|
| 236 |
+
LOG_INF("n_accept = %d\n", n_accept);
|
| 237 |
+
LOG_INF("accept = %.3f%%\n", 100.0f * n_accept / n_drafted);
|
| 238 |
+
|
| 239 |
+
LOG_INF("\ntarget:\n\n");
|
| 240 |
+
common_perf_print(ctx, smpl);
|
| 241 |
+
|
| 242 |
+
common_sampler_free(smpl);
|
| 243 |
+
|
| 244 |
+
llama_batch_free(batch_tgt);
|
| 245 |
+
|
| 246 |
+
llama_backend_free();
|
| 247 |
+
|
| 248 |
+
LOG("\n\n");
|
| 249 |
+
|
| 250 |
+
return 0;
|
| 251 |
+
}
|
examples/model-conversion/.gitignore
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.model_name
|
| 2 |
+
data
|
| 3 |
+
ppl
|
examples/model-conversion/Makefile
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MAKEFLAGS += --no-print-directory
|
| 2 |
+
|
| 3 |
+
define validate_model_path
|
| 4 |
+
@if [ -z "$(MODEL_PATH)" ]; then \
|
| 5 |
+
echo "Error: MODEL_PATH must be provided either as:"; \
|
| 6 |
+
echo " 1. Environment variable: export MODEL_PATH=/path/to/model"; \
|
| 7 |
+
echo " 2. Command line argument: make $(1) MODEL_PATH=/path/to/model"; \
|
| 8 |
+
exit 1; \
|
| 9 |
+
fi
|
| 10 |
+
endef
|
| 11 |
+
|
| 12 |
+
define validate_embedding_model_path
|
| 13 |
+
@if [ -z "$(EMBEDDING_MODEL_PATH)" ]; then \
|
| 14 |
+
echo "Error: EMBEDDING_MODEL_PATH must be provided either as:"; \
|
| 15 |
+
echo " 1. Environment variable: export EMBEDDING_MODEL_PATH=/path/to/model"; \
|
| 16 |
+
echo " 2. Command line argument: make $(1) EMBEDDING_MODEL_PATH=/path/to/model"; \
|
| 17 |
+
exit 1; \
|
| 18 |
+
fi
|
| 19 |
+
endef
|
| 20 |
+
|
| 21 |
+
define quantize_model
|
| 22 |
+
@CONVERTED_MODEL="$(1)" QUANTIZED_TYPE="$(QUANTIZED_TYPE)" \
|
| 23 |
+
TOKEN_EMBD_TYPE="$(TOKEN_EMBD_TYPE)" OUTPUT_TYPE="$(OUTPUT_TYPE)" \
|
| 24 |
+
./scripts/utils/quantize.sh "$(1)" "$(QUANTIZED_TYPE)" "$(TOKEN_EMBD_TYPE)" "$(OUTPUT_TYPE)"
|
| 25 |
+
@echo "Export the quantized model path to $(2) variable in your environment"
|
| 26 |
+
endef
|
| 27 |
+
|
| 28 |
+
DEVICE ?= auto
|
| 29 |
+
|
| 30 |
+
###
|
| 31 |
+
### Casual Model targets/recipes
|
| 32 |
+
###
|
| 33 |
+
causal-convert-model-bf16: OUTTYPE=bf16
|
| 34 |
+
causal-convert-model-bf16: causal-convert-model
|
| 35 |
+
|
| 36 |
+
causal-convert-model-debug: DEBUG=--debug
|
| 37 |
+
causal-convert-model-debug: causal-convert-model
|
| 38 |
+
|
| 39 |
+
causal-convert-model:
|
| 40 |
+
$(call validate_model_path,causal-convert-model)
|
| 41 |
+
@MODEL_NAME="$(MODEL_NAME)" OUTTYPE="$(OUTTYPE)" MODEL_PATH="$(MODEL_PATH)" \
|
| 42 |
+
METADATA_OVERRIDE="$(METADATA_OVERRIDE)" \
|
| 43 |
+
./scripts/causal/convert-model.sh $(DEBUG)
|
| 44 |
+
|
| 45 |
+
causal-convert-mm-model-bf16: OUTTYPE=bf16
|
| 46 |
+
causal-convert-mm-model-bf16: MM_OUTTYPE=f16
|
| 47 |
+
causal-convert-mm-model-bf16: causal-convert-mm-model
|
| 48 |
+
|
| 49 |
+
causal-convert-mm-model:
|
| 50 |
+
$(call validate_model_path,causal-convert-mm-model)
|
| 51 |
+
@MODEL_NAME="$(MODEL_NAME)" OUTTYPE="$(OUTTYPE)" MODEL_PATH="$(MODEL_PATH)" \
|
| 52 |
+
METADATA_OVERRIDE="$(METADATA_OVERRIDE)" \
|
| 53 |
+
./scripts/causal/convert-model.sh
|
| 54 |
+
|
| 55 |
+
$(MAKE) causal-convert-mmproj MM_OUTTYPE="$(MM_OUTTYPE)"
|
| 56 |
+
|
| 57 |
+
causal-convert-mmproj:
|
| 58 |
+
$(call validate_model_path,causal-convert-mmproj)
|
| 59 |
+
@MODEL_NAME="$(MODEL_NAME)" OUTTYPE="$(MM_OUTTYPE)" MODEL_PATH="$(MODEL_PATH)" \
|
| 60 |
+
METADATA_OVERRIDE="$(METADATA_OVERRIDE)" \
|
| 61 |
+
./scripts/causal/convert-model.sh --mmproj
|
| 62 |
+
|
| 63 |
+
causal-run-original-model:
|
| 64 |
+
$(call validate_model_path,causal-run-original-model)
|
| 65 |
+
@MODEL_PATH="$(MODEL_PATH)" ./scripts/causal/run-org-model.py --device "$(DEVICE)"
|
| 66 |
+
|
| 67 |
+
causal-run-converted-model:
|
| 68 |
+
@CONVERTED_MODEL="$(CONVERTED_MODEL)" ./scripts/causal/run-converted-model.sh
|
| 69 |
+
|
| 70 |
+
causal-verify-logits: causal-run-original-model causal-run-converted-model
|
| 71 |
+
@MODEL_PATH="$(MODEL_PATH)" ./scripts/causal/compare-logits.py
|
| 72 |
+
@MODEL_PATH="$(MODEL_PATH)" ./scripts/utils/check-nmse.py -m ${MODEL_PATH}
|
| 73 |
+
|
| 74 |
+
causal-run-original-embeddings:
|
| 75 |
+
@./scripts/causal/run-casual-gen-embeddings-org.py
|
| 76 |
+
|
| 77 |
+
causal-run-converted-embeddings:
|
| 78 |
+
@./scripts/causal/run-converted-model-embeddings-logits.sh
|
| 79 |
+
|
| 80 |
+
causal-verify-embeddings: causal-run-original-embeddings causal-run-converted-embeddings
|
| 81 |
+
@./scripts/causal/compare-embeddings-logits.sh
|
| 82 |
+
|
| 83 |
+
causal-inspect-original-model:
|
| 84 |
+
@./scripts/utils/inspect-org-model.py --list-all -s
|
| 85 |
+
|
| 86 |
+
causal-list-original-model-tensors:
|
| 87 |
+
@./scripts/utils/inspect-org-model.py --list-all-short -s
|
| 88 |
+
|
| 89 |
+
causal-inspect-converted-model:
|
| 90 |
+
@./scripts/utils/inspect-converted-model.sh
|
| 91 |
+
|
| 92 |
+
causal-start-embedding-server:
|
| 93 |
+
@./scripts/utils/run-embedding-server.sh ${CONVERTED_MODEL}
|
| 94 |
+
|
| 95 |
+
causal-curl-embedding-endpoint: causal-run-original-embeddings
|
| 96 |
+
@./scripts/utils/curl-embedding-server.sh | ./scripts/causal/compare-embeddings-logits.sh
|
| 97 |
+
|
| 98 |
+
causal-quantize-Q8_0: QUANTIZED_TYPE = Q8_0
|
| 99 |
+
causal-quantize-Q8_0: causal-quantize-model
|
| 100 |
+
|
| 101 |
+
causal-quantize-Q4_0: QUANTIZED_TYPE = Q4_0
|
| 102 |
+
causal-quantize-Q4_0: causal-quantize-model
|
| 103 |
+
|
| 104 |
+
# For Quantization Aware Trained (QAT) models in Q4_0 we explicitly set the
|
| 105 |
+
# token embedding and output types to Q8_0 instead of the default Q6_K.
|
| 106 |
+
causal-quantize-qat-Q4_0: QUANTIZED_TYPE = Q4_0
|
| 107 |
+
causal-quantize-qat-Q4_0: TOKEN_EMBD_TYPE = Q8_0
|
| 108 |
+
causal-quantize-qat-Q4_0: OUTPUT_TYPE = Q8_0
|
| 109 |
+
causal-quantize-qat-Q4_0: causal-quantize-model
|
| 110 |
+
|
| 111 |
+
causal-quantize-model:
|
| 112 |
+
$(call quantize_model,$(CONVERTED_MODEL),QUANTIZED_MODEL)
|
| 113 |
+
|
| 114 |
+
causal-run-quantized-model:
|
| 115 |
+
@QUANTIZED_MODEL="$(QUANTIZED_MODEL)" ./scripts/causal/run-converted-model.sh ${QUANTIZED_MODEL}
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
###
|
| 119 |
+
### Embedding Model targets/recipes
|
| 120 |
+
###
|
| 121 |
+
|
| 122 |
+
embedding-convert-model-bf16: OUTTYPE=bf16
|
| 123 |
+
embedding-convert-model-bf16: embedding-convert-model
|
| 124 |
+
|
| 125 |
+
embedding-convert-model:
|
| 126 |
+
$(call validate_embedding_model_path,embedding-convert-model)
|
| 127 |
+
@MODEL_NAME="$(MODEL_NAME)" OUTTYPE="$(OUTTYPE)" MODEL_PATH="$(EMBEDDING_MODEL_PATH)" \
|
| 128 |
+
METADATA_OVERRIDE="$(METADATA_OVERRIDE)" \
|
| 129 |
+
./scripts/embedding/convert-model.sh
|
| 130 |
+
|
| 131 |
+
embedding-convert-model-st:
|
| 132 |
+
$(call validate_embedding_model_path,embedding-convert-model-st)
|
| 133 |
+
@MODEL_NAME="$(MODEL_NAME)" OUTTYPE="$(OUTTYPE)" MODEL_PATH="$(EMBEDDING_MODEL_PATH)" \
|
| 134 |
+
METADATA_OVERRIDE="$(METADATA_OVERRIDE)" \
|
| 135 |
+
./scripts/embedding/convert-model.sh -st
|
| 136 |
+
|
| 137 |
+
embedding-run-original-model:
|
| 138 |
+
$(call validate_embedding_model_path,embedding-run-original-model)
|
| 139 |
+
@EMBEDDING_MODEL_PATH="$(EMBEDDING_MODEL_PATH)" \
|
| 140 |
+
USE_SENTENCE_TRANSFORMERS="$(USE_SENTENCE_TRANSFORMERS)" \
|
| 141 |
+
./scripts/embedding/run-original-model.py \
|
| 142 |
+
$(if $(PROMPTS_FILE),--prompts-file "$(PROMPTS_FILE)") \
|
| 143 |
+
$(if $(USE_SENTENCE_TRANSFORMERS),--use-sentence-transformers)
|
| 144 |
+
|
| 145 |
+
embedding-run-original-model-st: USE_SENTENCE_TRANSFORMERS=1
|
| 146 |
+
embedding-run-original-model-st: embedding-run-original-model
|
| 147 |
+
|
| 148 |
+
embedding-run-converted-model:
|
| 149 |
+
@./scripts/embedding/run-converted-model.sh $(CONVERTED_EMBEDDING_MODEL) \
|
| 150 |
+
$(if $(PROMPTS_FILE),--prompts-file "$(PROMPTS_FILE)") \
|
| 151 |
+
$(if $(EMBD_NORMALIZE),--embd-normalize "$(EMBD_NORMALIZE)")
|
| 152 |
+
|
| 153 |
+
embedding-verify-logits: embedding-run-original-model embedding-run-converted-model
|
| 154 |
+
@./scripts/embedding/compare-embeddings-logits.sh \
|
| 155 |
+
$(if $(PROMPTS_FILE),--prompts-file "$(PROMPTS_FILE)")
|
| 156 |
+
|
| 157 |
+
embedding-verify-logits-st: embedding-run-original-model-st embedding-run-converted-model
|
| 158 |
+
@./scripts/embedding/compare-embeddings-logits.sh \
|
| 159 |
+
$(if $(PROMPTS_FILE),--prompts-file "$(PROMPTS_FILE)")
|
| 160 |
+
|
| 161 |
+
embedding-inspect-original-model:
|
| 162 |
+
$(call validate_embedding_model_path,embedding-inspect-original-model)
|
| 163 |
+
@EMBEDDING_MODEL_PATH="$(EMBEDDING_MODEL_PATH)" ./scripts/utils/inspect-org-model.py -m ${EMBEDDING_MODEL_PATH} --list-all -s
|
| 164 |
+
|
| 165 |
+
embedding-inspect-converted-model:
|
| 166 |
+
@CONVERTED_EMBEDDING_MODEL="$(CONVERTED_EMBEDDING_MODEL)" ./scripts/utils/inspect-converted-model.sh ${CONVERTED_EMBEDDING_MODEL}
|
| 167 |
+
|
| 168 |
+
embedding-start-embedding-server:
|
| 169 |
+
@./scripts/utils/run-embedding-server.sh ${CONVERTED_EMBEDDING_MODEL}
|
| 170 |
+
|
| 171 |
+
embedding-curl-embedding-endpoint:
|
| 172 |
+
@./scripts/utils/curl-embedding-server.sh | ./scripts/embedding/compare-embeddings-logits.sh
|
| 173 |
+
|
| 174 |
+
embedding-quantize-Q8_0: QUANTIZED_TYPE = Q8_0
|
| 175 |
+
embedding-quantize-Q8_0: embedding-quantize-model
|
| 176 |
+
|
| 177 |
+
embedding-quantize-Q4_0: QUANTIZED_TYPE = Q4_0
|
| 178 |
+
embedding-quantize-Q4_0: embedding-quantize-model
|
| 179 |
+
|
| 180 |
+
# For Quantization Aware Trained (QAT) models in Q4_0 we explicitly set the
|
| 181 |
+
# token embedding and output types to Q8_0 instead of the default Q6_K.
|
| 182 |
+
embedding-quantize-qat-Q4_0: QUANTIZED_TYPE = Q4_0
|
| 183 |
+
embedding-quantize-qat-Q4_0: TOKEN_EMBD_TYPE = Q8_0
|
| 184 |
+
embedding-quantize-qat-Q4_0: OUTPUT_TYPE = Q8_0
|
| 185 |
+
embedding-quantize-qat-Q4_0: embedding-quantize-model
|
| 186 |
+
|
| 187 |
+
embedding-quantize-model:
|
| 188 |
+
$(call quantize_model,$(CONVERTED_EMBEDDING_MODEL),QUANTIZED_EMBEDDING_MODEL)
|
| 189 |
+
|
| 190 |
+
embedding-run-quantized-model:
|
| 191 |
+
@./scripts/embedding/run-converted-model.sh $(QUANTIZED_EMBEDDING_MODEL) \
|
| 192 |
+
$(if $(PROMPTS_FILE),--prompts-file "$(PROMPTS_FILE)")
|
| 193 |
+
|
| 194 |
+
###
|
| 195 |
+
### Perplexity targets/recipes
|
| 196 |
+
###
|
| 197 |
+
perplexity-data-gen:
|
| 198 |
+
CONVERTED_MODEL="$(CONVERTED_MODEL)" ./scripts/utils/perplexity-gen.sh
|
| 199 |
+
|
| 200 |
+
perplexity-run-full:
|
| 201 |
+
QUANTIZED_MODEL="$(QUANTIZED_MODEL)" LOOGITS_FILE="$(LOGITS_FILE)" \
|
| 202 |
+
./scripts/utils/perplexity-run.sh
|
| 203 |
+
|
| 204 |
+
perplexity-run:
|
| 205 |
+
QUANTIZED_MODEL="$(QUANTIZED_MODEL)" ./scripts/utils/perplexity-run-simple.sh
|
| 206 |
+
|
| 207 |
+
###
|
| 208 |
+
### HuggingFace targets/recipes
|
| 209 |
+
###
|
| 210 |
+
|
| 211 |
+
hf-create-model:
|
| 212 |
+
@./scripts/utils/hf-create-model.py -m "${MODEL_NAME}" -ns "${NAMESPACE}" -b "${ORIGINAL_BASE_MODEL}"
|
| 213 |
+
|
| 214 |
+
hf-create-model-dry-run:
|
| 215 |
+
@./scripts/utils/hf-create-model.py -m "${MODEL_NAME}" -ns "${NAMESPACE}" -b "${ORIGINAL_BASE_MODEL}" -d
|
| 216 |
+
|
| 217 |
+
hf-create-model-embedding:
|
| 218 |
+
@./scripts/utils/hf-create-model.py -m "${MODEL_NAME}" -ns "${NAMESPACE}" -b "${ORIGINAL_BASE_MODEL}" -e
|
| 219 |
+
|
| 220 |
+
hf-create-model-embedding-dry-run:
|
| 221 |
+
@./scripts/utils/hf-create-model.py -m "${MODEL_NAME}" -ns "${NAMESPACE}" -b "${ORIGINAL_BASE_MODEL}" -e -d
|
| 222 |
+
|
| 223 |
+
hf-create-model-private:
|
| 224 |
+
@./scripts/utils/hf-create-model.py -m "${MODEL_NAME}" -ns "${NAMESPACE}" -b "${ORIGINAL_BASE_MODEL}" -p
|
| 225 |
+
|
| 226 |
+
hf-upload-gguf-to-model:
|
| 227 |
+
@./scripts/utils/hf-upload-gguf-model.py -m "${MODEL_PATH}" -r "${REPO_ID}" -o "${NAME_IN_REPO}"
|
| 228 |
+
|
| 229 |
+
hf-create-collection:
|
| 230 |
+
@./scripts/utils/hf-create-collection.py -n "${NAME}" -d "${DESCRIPTION}" -ns "${NAMESPACE}"
|
| 231 |
+
|
| 232 |
+
hf-add-model-to-collection:
|
| 233 |
+
@./scripts/utils/hf-add-model-to-collection.py -c "${COLLECTION}" -m "${MODEL}"
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
.PHONY: clean
|
| 237 |
+
clean:
|
| 238 |
+
@${RM} -rf data .converted_embedding_model.txt .converted_model.txt .embedding_model_name.txt .model_name.txt
|
| 239 |
+
|
examples/model-conversion/README.md
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Model Conversion Example
|
| 2 |
+
This directory contains scripts and code to help in the process of converting
|
| 3 |
+
HuggingFace PyTorch models to GGUF format.
|
| 4 |
+
|
| 5 |
+
The motivation for having this is that the conversion process can often be an
|
| 6 |
+
iterative process, where the original model is inspected, converted, updates
|
| 7 |
+
made to llama.cpp, converted again, etc. Once the model has been converted it
|
| 8 |
+
needs to be verified against the original model, and then optionally quantified,
|
| 9 |
+
and in some cases perplexity checked of the quantized model. And finally the
|
| 10 |
+
model/models need to the ggml-org on Hugging Face. This tool/example tries to
|
| 11 |
+
help with this process.
|
| 12 |
+
|
| 13 |
+
> 📝 **Note:** When adding a new model from an existing family, verify the
|
| 14 |
+
> previous version passes logits verification first. Existing models can have
|
| 15 |
+
> subtle numerical differences that don't affect generation quality but cause
|
| 16 |
+
> logits mismatches. Identifying these upfront whether they exist in llama.cpp,
|
| 17 |
+
> the conversion script, or in an upstream implementation, can save significant
|
| 18 |
+
> debugging time.
|
| 19 |
+
|
| 20 |
+
### Overview
|
| 21 |
+
The idea is that the makefile targets and scripts here can be used in the
|
| 22 |
+
development/conversion process assisting with things like:
|
| 23 |
+
|
| 24 |
+
* inspect/run the original model to figure out how it works
|
| 25 |
+
* convert the original model to GGUF format
|
| 26 |
+
* inspect/run the converted model
|
| 27 |
+
* verify the logits produced by the original model and the converted model
|
| 28 |
+
* quantize the model to GGUF format
|
| 29 |
+
* run perplexity evaluation to verify that the quantized model is performing
|
| 30 |
+
as expected
|
| 31 |
+
* upload the model to HuggingFace to make it available for others
|
| 32 |
+
|
| 33 |
+
## Setup
|
| 34 |
+
Create virtual python environment
|
| 35 |
+
```console
|
| 36 |
+
$ python3.11 -m venv venv
|
| 37 |
+
$ source venv/bin/activate
|
| 38 |
+
(venv) $ pip install -r requirements.txt
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
## Causal Language Model Conversion
|
| 42 |
+
This section describes the steps to convert a causal language model to GGUF and
|
| 43 |
+
to verify that the conversion was successful.
|
| 44 |
+
|
| 45 |
+
### Download the original model
|
| 46 |
+
First, clone the original model to some local directory:
|
| 47 |
+
```console
|
| 48 |
+
$ mkdir models && cd models
|
| 49 |
+
$ git clone https://huggingface.co/user/model_name
|
| 50 |
+
$ cd model_name
|
| 51 |
+
$ git lfs install
|
| 52 |
+
$ git lfs pull
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
### Set the MODEL_PATH
|
| 56 |
+
The path to the downloaded model can be provided in two ways:
|
| 57 |
+
|
| 58 |
+
**Option 1: Environment variable (recommended for iterative development)**
|
| 59 |
+
```console
|
| 60 |
+
export MODEL_PATH=~/work/ai/models/some_model
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
**Option 2: Command line argument (for one-off tasks)**
|
| 64 |
+
```console
|
| 65 |
+
make causal-convert-model MODEL_PATH=~/work/ai/models/some_model
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
Command line arguments take precedence over environment variables when both are provided.
|
| 69 |
+
|
| 70 |
+
In cases where the transformer implementation for the model has not been released
|
| 71 |
+
yet it is possible to set the environment variable `UNRELEASED_MODEL_NAME` which
|
| 72 |
+
will then cause the transformer implementation to be loaded explicitly and not
|
| 73 |
+
use AutoModelForCausalLM:
|
| 74 |
+
```
|
| 75 |
+
export UNRELEASED_MODEL_NAME=SomeNewModel
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
### Inspecting the original tensors
|
| 79 |
+
```console
|
| 80 |
+
# Using environment variable
|
| 81 |
+
(venv) $ make causal-inspect-original-model
|
| 82 |
+
|
| 83 |
+
# Or using command line argument
|
| 84 |
+
(venv) $ make causal-inspect-original-model MODEL_PATH=~/work/ai/models/some_model
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
### Running the original model
|
| 88 |
+
This is mainly to verify that the original model works, and to compare the output
|
| 89 |
+
from the converted model.
|
| 90 |
+
```console
|
| 91 |
+
# Using environment variable
|
| 92 |
+
(venv) $ make causal-run-original-model
|
| 93 |
+
|
| 94 |
+
# Or using command line argument
|
| 95 |
+
(venv) $ make causal-run-original-model MODEL_PATH=~/work/ai/models/some_model
|
| 96 |
+
```
|
| 97 |
+
This command will save two files to the `data` directory, one is a binary file
|
| 98 |
+
containing logits which will be used for comparison with the converted model
|
| 99 |
+
later, and the other is a text file which allows for manual visual inspection.
|
| 100 |
+
|
| 101 |
+
### Model conversion
|
| 102 |
+
After updates have been made to [gguf-py](../../gguf-py) to add support for the
|
| 103 |
+
new model, the model can be converted to GGUF format using the following command:
|
| 104 |
+
```console
|
| 105 |
+
# Using environment variable
|
| 106 |
+
(venv) $ make causal-convert-model
|
| 107 |
+
|
| 108 |
+
# Or using command line argument
|
| 109 |
+
(venv) $ make causal-convert-model MODEL_PATH=~/work/ai/models/some_model
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
### Inspecting the converted model
|
| 113 |
+
The converted model can be inspected using the following command:
|
| 114 |
+
```console
|
| 115 |
+
(venv) $ make causal-inspect-converted-model
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
### Running the converted model
|
| 119 |
+
```console
|
| 120 |
+
(venv) $ make causal-run-converted-model
|
| 121 |
+
```
|
| 122 |
+
|
| 123 |
+
### Model logits verification
|
| 124 |
+
The following target will run the original model and the converted model and
|
| 125 |
+
compare the logits:
|
| 126 |
+
```console
|
| 127 |
+
(venv) $ make causal-verify-logits
|
| 128 |
+
```
|
| 129 |
+
|
| 130 |
+
### Quantizing the model
|
| 131 |
+
The causal model can be quantized to GGUF format using the following command:
|
| 132 |
+
```console
|
| 133 |
+
(venv) $ make causal-quantize-Q8_0
|
| 134 |
+
Quantized model saved to: /path/to/quantized/model-Q8_0.gguf
|
| 135 |
+
Export the quantized model path to QUANTIZED_MODEL variable in your environment
|
| 136 |
+
```
|
| 137 |
+
This will show the path to the quantized model in the terminal, which can then
|
| 138 |
+
be used to set the `QUANTIZED_MODEL` environment variable:
|
| 139 |
+
```console
|
| 140 |
+
export QUANTIZED_MODEL=/path/to/quantized/model-Q8_0.gguf
|
| 141 |
+
```
|
| 142 |
+
Then the quantized model can be run using the following command:
|
| 143 |
+
```console
|
| 144 |
+
(venv) $ make causal-run-quantized-model
|
| 145 |
+
```
|
| 146 |
+
|
| 147 |
+
### Quantizing QAT (Quantization Aware Training) models
|
| 148 |
+
When quantizing to `Q4_0`, the default data type for the token embedding weights
|
| 149 |
+
will be `Q6_K`. For models that are going to be uploaded to ggml-org it is
|
| 150 |
+
recommended to use `Q8_0` instead for the embeddings and output tensors.
|
| 151 |
+
The reason is that although `Q6_K` is smaller in size, it requires more compute
|
| 152 |
+
to unpack, which can hurt performance during output generation when the entire
|
| 153 |
+
embedding matrix must be dequantized to compute vocabulary logits. `Q8_0`
|
| 154 |
+
provides practically full quality with better computational efficiency.
|
| 155 |
+
```console
|
| 156 |
+
(venv) $ make causal-quantize-qat-Q4_0
|
| 157 |
+
```
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
## Embedding Language Model Conversion
|
| 161 |
+
|
| 162 |
+
### Download the original model
|
| 163 |
+
```console
|
| 164 |
+
$ mkdir models && cd models
|
| 165 |
+
$ git clone https://huggingface.co/user/model_name
|
| 166 |
+
$ cd model_name
|
| 167 |
+
$ git lfs install
|
| 168 |
+
$ git lfs pull
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
The path to the embedding model can be provided in two ways:
|
| 172 |
+
|
| 173 |
+
**Option 1: Environment variable (recommended for iterative development)**
|
| 174 |
+
```console
|
| 175 |
+
export EMBEDDING_MODEL_PATH=~/path/to/embedding_model
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
**Option 2: Command line argument (for one-off tasks)**
|
| 179 |
+
```console
|
| 180 |
+
make embedding-convert-model EMBEDDING_MODEL_PATH=~/path/to/embedding_model
|
| 181 |
+
```
|
| 182 |
+
|
| 183 |
+
Command line arguments take precedence over environment variables when both are provided.
|
| 184 |
+
|
| 185 |
+
### Running the original model
|
| 186 |
+
This is mainly to verify that the original model works and to compare the output
|
| 187 |
+
with the output from the converted model.
|
| 188 |
+
```console
|
| 189 |
+
# Using environment variable
|
| 190 |
+
(venv) $ make embedding-run-original-model
|
| 191 |
+
|
| 192 |
+
# Or using command line argument
|
| 193 |
+
(venv) $ make embedding-run-original-model EMBEDDING_MODEL_PATH=~/path/to/embedding_model
|
| 194 |
+
```
|
| 195 |
+
This command will save two files to the `data` directory, one is a binary
|
| 196 |
+
file containing logits which will be used for comparison with the converted
|
| 197 |
+
model, and the other is a text file which allows for manual visual inspection.
|
| 198 |
+
|
| 199 |
+
#### Using SentenceTransformer with numbered layers
|
| 200 |
+
For models that have numbered SentenceTransformer layers (01_Pooling, 02_Dense,
|
| 201 |
+
03_Dense, 04_Normalize), these will be applied automatically when running the
|
| 202 |
+
converted model but currently there is a separate target to run the original
|
| 203 |
+
version:
|
| 204 |
+
|
| 205 |
+
```console
|
| 206 |
+
# Run original model with SentenceTransformer (applies all numbered layers)
|
| 207 |
+
(venv) $ make embedding-run-original-model-st
|
| 208 |
+
```
|
| 209 |
+
|
| 210 |
+
This will use the SentenceTransformer library to load and run the model, which
|
| 211 |
+
automatically applies all the numbered layers in the correct order. This is
|
| 212 |
+
particularly useful when comparing with models that should include these
|
| 213 |
+
additional transformation layers beyond just the base model output.
|
| 214 |
+
|
| 215 |
+
The type of normalization can be specified for the converted model but is not
|
| 216 |
+
strictly necessary as the verification uses cosine similarity and the magnitude
|
| 217 |
+
of the output vectors does not affect this. But the normalization type can be
|
| 218 |
+
specified as an argument to the target which might be useful for manual
|
| 219 |
+
inspection:
|
| 220 |
+
```console
|
| 221 |
+
(venv) $ make embedding-verify-logits-st EMBD_NORMALIZE=1
|
| 222 |
+
```
|
| 223 |
+
The original model will apply the normalization according to the normalization
|
| 224 |
+
layer specified in the modules.json configuration file.
|
| 225 |
+
|
| 226 |
+
### Model conversion
|
| 227 |
+
After updates have been made to [gguf-py](../../gguf-py) to add support for the
|
| 228 |
+
new model the model can be converted to GGUF format using the following command:
|
| 229 |
+
```console
|
| 230 |
+
(venv) $ make embedding-convert-model
|
| 231 |
+
```
|
| 232 |
+
|
| 233 |
+
### Run the converted model
|
| 234 |
+
```console
|
| 235 |
+
(venv) $ make embedding-run-converted-model
|
| 236 |
+
```
|
| 237 |
+
|
| 238 |
+
### Model logits verification
|
| 239 |
+
The following target will run the original model and the converted model (which
|
| 240 |
+
was done manually in the previous steps) and compare the logits:
|
| 241 |
+
```console
|
| 242 |
+
(venv) $ make embedding-verify-logits
|
| 243 |
+
```
|
| 244 |
+
|
| 245 |
+
For models with SentenceTransformer layers, use the `-st` verification target:
|
| 246 |
+
```console
|
| 247 |
+
(venv) $ make embedding-verify-logits-st
|
| 248 |
+
```
|
| 249 |
+
This convenience target automatically runs both the original model with SentenceTransformer
|
| 250 |
+
and the converted model with pooling enabled, then compares the results.
|
| 251 |
+
|
| 252 |
+
### llama-server verification
|
| 253 |
+
To verify that the converted model works with llama-server, the following
|
| 254 |
+
command can be used:
|
| 255 |
+
```console
|
| 256 |
+
(venv) $ make embedding-start-embedding-server
|
| 257 |
+
```
|
| 258 |
+
Then open another terminal and set the `EMBEDDINGS_MODEL_PATH` environment
|
| 259 |
+
variable as this will not be inherited by the new terminal:
|
| 260 |
+
```console
|
| 261 |
+
(venv) $ make embedding-curl-embedding-endpoint
|
| 262 |
+
```
|
| 263 |
+
This will call the `embedding` endpoing and the output will be piped into
|
| 264 |
+
the same verification script as used by the target `embedding-verify-logits`.
|
| 265 |
+
|
| 266 |
+
The causal model can also be used to produce embeddings and this can be verified
|
| 267 |
+
using the following commands:
|
| 268 |
+
```console
|
| 269 |
+
(venv) $ make causal-start-embedding-server
|
| 270 |
+
```
|
| 271 |
+
Then open another terminal and set the `MODEL_PATH` environment
|
| 272 |
+
variable as this will not be inherited by the new terminal:
|
| 273 |
+
```console
|
| 274 |
+
(venv) $ make casual-curl-embedding-endpoint
|
| 275 |
+
```
|
| 276 |
+
|
| 277 |
+
### Quantizing the model
|
| 278 |
+
The embedding model can be quantized to GGUF format using the following command:
|
| 279 |
+
```console
|
| 280 |
+
(venv) $ make embedding-quantize-Q8_0
|
| 281 |
+
Quantized model saved to: /path/to/quantized/model-Q8_0.gguf
|
| 282 |
+
Export the quantized model path to QUANTIZED_EMBEDDING_MODEL variable in your environment
|
| 283 |
+
```
|
| 284 |
+
This will show the path to the quantized model in the terminal, which can then
|
| 285 |
+
be used to set the `QUANTIZED_EMBEDDING_MODEL` environment variable:
|
| 286 |
+
```console
|
| 287 |
+
export QUANTIZED_EMBEDDING_MODEL=/path/to/quantized/model-Q8_0.gguf
|
| 288 |
+
```
|
| 289 |
+
Then the quantized model can be run using the following command:
|
| 290 |
+
```console
|
| 291 |
+
(venv) $ make embedding-run-quantized-model
|
| 292 |
+
```
|
| 293 |
+
|
| 294 |
+
### Quantizing QAT (Quantization Aware Training) models
|
| 295 |
+
When quantizing to `Q4_0`, the default data type for the token embedding weights
|
| 296 |
+
will be `Q6_K`. For models that are going to be uploaded to ggml-org it is
|
| 297 |
+
recommended to use `Q8_0` instead for the embeddings and output tensors.
|
| 298 |
+
The reason is that although `Q6_K` is smaller in size, it requires more compute
|
| 299 |
+
to unpack, which can hurt performance during output generation when the entire
|
| 300 |
+
embedding matrix must be dequantized to compute vocabulary logits. `Q8_0`
|
| 301 |
+
provides practically full quality with better computational efficiency.
|
| 302 |
+
```console
|
| 303 |
+
(venv) $ make embedding-quantize-qat-Q4_0
|
| 304 |
+
```
|
| 305 |
+
|
| 306 |
+
## Perplexity Evaluation
|
| 307 |
+
|
| 308 |
+
### Simple perplexity evaluation
|
| 309 |
+
This allows to run the perplexity evaluation without having to generate a
|
| 310 |
+
token/logits file:
|
| 311 |
+
```console
|
| 312 |
+
(venv) $ make perplexity-run QUANTIZED_MODEL=~/path/to/quantized/model.gguf
|
| 313 |
+
```
|
| 314 |
+
This will use the wikitext dataset to run the perplexity evaluation and
|
| 315 |
+
output the perplexity score to the terminal. This value can then be compared
|
| 316 |
+
with the perplexity score of the unquantized model.
|
| 317 |
+
|
| 318 |
+
### Full perplexity evaluation
|
| 319 |
+
First use the converted, non-quantized, model to generate the perplexity evaluation
|
| 320 |
+
dataset using the following command:
|
| 321 |
+
```console
|
| 322 |
+
$ make perplexity-data-gen CONVERTED_MODEL=~/path/to/converted/model.gguf
|
| 323 |
+
```
|
| 324 |
+
This will generate a file in the `data` directory named after the model and with
|
| 325 |
+
a `.kld` suffix which contains the tokens and the logits for the wikitext dataset.
|
| 326 |
+
|
| 327 |
+
After the dataset has been generated, the perplexity evaluation can be run using
|
| 328 |
+
the quantized model:
|
| 329 |
+
```console
|
| 330 |
+
$ make perplexity-run-full QUANTIZED_MODEL=~/path/to/quantized/model-Qxx.gguf LOGITS_FILE=data/model.gguf.ppl
|
| 331 |
+
```
|
| 332 |
+
|
| 333 |
+
> 📝 **Note:** The `LOGITS_FILE` is the file generated by the previous command
|
| 334 |
+
> can be very large, so make sure you have enough disk space available.
|
| 335 |
+
|
| 336 |
+
## HuggingFace utilities
|
| 337 |
+
The following targets are useful for creating collections and model repositories
|
| 338 |
+
on Hugging Face in the ggml-org. These can be used when preparing a release
|
| 339 |
+
to script the process for new model releases.
|
| 340 |
+
|
| 341 |
+
For the following targets a `HF_TOKEN` environment variable is required.
|
| 342 |
+
|
| 343 |
+
> 📝 **Note:** Don't forget to logout from Hugging Face after running these
|
| 344 |
+
> commands, otherwise you might have issues pulling/cloning repositories as
|
| 345 |
+
> the token will still be in use:
|
| 346 |
+
> $ huggingface-cli logout
|
| 347 |
+
> $ unset HF_TOKEN
|
| 348 |
+
|
| 349 |
+
### Create a new Hugging Face Model (model repository)
|
| 350 |
+
This will create a new model repository on Hugging Face with the specified
|
| 351 |
+
model name.
|
| 352 |
+
```console
|
| 353 |
+
(venv) $ make hf-create-model MODEL_NAME='TestModel' NAMESPACE="danbev" ORIGINAL_BASE_MODEL="some-base-model"
|
| 354 |
+
Repository ID: danbev/TestModel-GGUF
|
| 355 |
+
Repository created: https://huggingface.co/danbev/TestModel-GGUF
|
| 356 |
+
```
|
| 357 |
+
Note that we append a `-GGUF` suffix to the model name to ensure a consistent
|
| 358 |
+
naming convention for GGUF models.
|
| 359 |
+
|
| 360 |
+
An embedding model can be created using the following command:
|
| 361 |
+
```console
|
| 362 |
+
(venv) $ make hf-create-model-embedding MODEL_NAME='TestEmbeddingModel' NAMESPACE="danbev" ORIGINAL_BASE_MODEL="some-base-model"
|
| 363 |
+
```
|
| 364 |
+
The only difference is that the model card for an embedding model will be different
|
| 365 |
+
with regards to the llama-server command and also how to access/call the embedding
|
| 366 |
+
endpoint.
|
| 367 |
+
|
| 368 |
+
### Upload a GGUF model to model repository
|
| 369 |
+
The following target uploads a model to an existing Hugging Face model repository.
|
| 370 |
+
```console
|
| 371 |
+
(venv) $ make hf-upload-gguf-to-model MODEL_PATH=dummy-model1.gguf REPO_ID=danbev/TestModel-GGUF
|
| 372 |
+
📤 Uploading dummy-model1.gguf to danbev/TestModel-GGUF/dummy-model1.gguf
|
| 373 |
+
✅ Upload successful!
|
| 374 |
+
🔗 File available at: https://huggingface.co/danbev/TestModel-GGUF/blob/main/dummy-model1.gguf
|
| 375 |
+
```
|
| 376 |
+
This command can also be used to update an existing model file in a repository.
|
| 377 |
+
|
| 378 |
+
### Create a new Collection
|
| 379 |
+
```console
|
| 380 |
+
(venv) $ make hf-new-collection NAME=TestCollection DESCRIPTION="Collection for testing scripts" NAMESPACE=danbev
|
| 381 |
+
🚀 Creating Hugging Face Collection
|
| 382 |
+
Title: TestCollection
|
| 383 |
+
Description: Collection for testing scripts
|
| 384 |
+
Namespace: danbev
|
| 385 |
+
Private: False
|
| 386 |
+
✅ Authenticated as: danbev
|
| 387 |
+
📚 Creating collection: 'TestCollection'...
|
| 388 |
+
✅ Collection created successfully!
|
| 389 |
+
���� Collection slug: danbev/testcollection-68930fcf73eb3fc200b9956d
|
| 390 |
+
🔗 Collection URL: https://huggingface.co/collections/danbev/testcollection-68930fcf73eb3fc200b9956d
|
| 391 |
+
|
| 392 |
+
🎉 Collection created successfully!
|
| 393 |
+
Use this slug to add models: danbev/testcollection-68930fcf73eb3fc200b9956d
|
| 394 |
+
```
|
| 395 |
+
|
| 396 |
+
### Add model to a Collection
|
| 397 |
+
```console
|
| 398 |
+
(venv) $ make hf-add-model-to-collection COLLECTION=danbev/testcollection-68930fcf73eb3fc200b9956d MODEL=danbev/TestModel-GGUF
|
| 399 |
+
✅ Authenticated as: danbev
|
| 400 |
+
🔍 Checking if model exists: danbev/TestModel-GGUF
|
| 401 |
+
✅ Model found: danbev/TestModel-GGUF
|
| 402 |
+
📚 Adding model to collection...
|
| 403 |
+
✅ Model added to collection successfully!
|
| 404 |
+
🔗 Collection URL: https://huggingface.co/collections/danbev/testcollection-68930fcf73eb3fc200b9956d
|
| 405 |
+
|
| 406 |
+
🎉 Model added successfully!
|
| 407 |
+
|
| 408 |
+
```
|
examples/model-conversion/requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 2 |
+
torch
|
| 3 |
+
torchvision
|
| 4 |
+
transformers
|
| 5 |
+
huggingface-hub
|
| 6 |
+
accelerate
|
| 7 |
+
sentence-transformers
|
examples/model-conversion/scripts/causal/compare-embeddings-logits.sh
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
|
| 3 |
+
set -e
|
| 4 |
+
|
| 5 |
+
MODEL_PATH="${1:-"$MODEL_PATH"}"
|
| 6 |
+
MODEL_NAME="${2:-$(basename "$MODEL_PATH")}"
|
| 7 |
+
|
| 8 |
+
CONVERTED_MODEL_PATH="${1:-"$CONVERTED_MODEL"}"
|
| 9 |
+
CONVERTED_MODEL_NAME="${2:-$(basename "$CONVERTED_MODEL_PATH" ".gguf")}"
|
| 10 |
+
|
| 11 |
+
if [ -t 0 ]; then
|
| 12 |
+
CPP_EMBEDDINGS="data/llamacpp-${CONVERTED_MODEL_NAME}-embeddings.bin"
|
| 13 |
+
else
|
| 14 |
+
# Process piped JSON data and convert to binary (matching logits.cpp format)
|
| 15 |
+
TEMP_FILE=$(mktemp /tmp/tmp.XXXXXX.binn)
|
| 16 |
+
python3 -c "
|
| 17 |
+
import json
|
| 18 |
+
import sys
|
| 19 |
+
import struct
|
| 20 |
+
|
| 21 |
+
data = json.load(sys.stdin)
|
| 22 |
+
|
| 23 |
+
# Flatten all embeddings completely
|
| 24 |
+
flattened = []
|
| 25 |
+
for item in data:
|
| 26 |
+
embedding = item['embedding']
|
| 27 |
+
for token_embedding in embedding:
|
| 28 |
+
flattened.extend(token_embedding)
|
| 29 |
+
|
| 30 |
+
print(f'Total embedding values: {len(flattened)}', file=sys.stderr)
|
| 31 |
+
|
| 32 |
+
# Write as binary floats - matches logitc.cpp fwrite format
|
| 33 |
+
with open('$TEMP_FILE', 'wb') as f:
|
| 34 |
+
for value in flattened:
|
| 35 |
+
f.write(struct.pack('f', value))
|
| 36 |
+
"
|
| 37 |
+
CPP_EMBEDDINGS="$TEMP_FILE"
|
| 38 |
+
trap "rm -f $TEMP_FILE" EXIT
|
| 39 |
+
fi
|
| 40 |
+
|
| 41 |
+
python scripts/utils/semantic_check.py --model-path $MODEL_PATH \
|
| 42 |
+
--python-embeddings data/pytorch-${MODEL_NAME}-embeddings.bin \
|
| 43 |
+
--cpp-embeddings $CPP_EMBEDDINGS \
|
| 44 |
+
--prompt "Hello world today" \
|
| 45 |
+
--causal
|
| 46 |
+
|
examples/model-conversion/scripts/causal/compare-logits.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
import numpy as np
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
# Add utils directory to path for direct script execution
|
| 9 |
+
sys.path.insert(0, str(Path(__file__).parent.parent / "utils"))
|
| 10 |
+
from common import get_model_name_from_env_path, compare_tokens, exit_with_warning # type: ignore[import-not-found, ty:unresolved-import]
|
| 11 |
+
|
| 12 |
+
def quick_logits_check(pytorch_file, llamacpp_file):
|
| 13 |
+
"""Lightweight sanity check before NMSE"""
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
pytorch_logits = np.fromfile(pytorch_file, dtype=np.float32)
|
| 17 |
+
llamacpp_logits = np.fromfile(llamacpp_file, dtype=np.float32)
|
| 18 |
+
except Exception as e:
|
| 19 |
+
print(f"❌ NOK: Failed to load files - {e}")
|
| 20 |
+
return False
|
| 21 |
+
|
| 22 |
+
# Check shapes match
|
| 23 |
+
if pytorch_logits.shape != llamacpp_logits.shape:
|
| 24 |
+
print(f"❌ NOK: Shape mismatch - PyTorch: {pytorch_logits.shape}, llama.cpp: {llamacpp_logits.shape}")
|
| 25 |
+
return False
|
| 26 |
+
|
| 27 |
+
# Calculate key metrics
|
| 28 |
+
diff = pytorch_logits - llamacpp_logits
|
| 29 |
+
abs_diff = np.abs(diff)
|
| 30 |
+
max_diff = np.max(abs_diff)
|
| 31 |
+
|
| 32 |
+
# Get top 10 predictions from both models
|
| 33 |
+
pytorch_top10 = np.argsort(pytorch_logits)[-10:][::-1]
|
| 34 |
+
llamacpp_top10 = np.argsort(llamacpp_logits)[-10:][::-1]
|
| 35 |
+
print(f"Top 10 PyTorch logits: {pytorch_logits[pytorch_top10]}")
|
| 36 |
+
print(f"Top 10 llama.cpp logits: {llamacpp_logits[llamacpp_top10]}")
|
| 37 |
+
print(f"Max absolute difference: {max_diff:.4f}")
|
| 38 |
+
|
| 39 |
+
return True
|
| 40 |
+
|
| 41 |
+
def main():
|
| 42 |
+
model_path = os.environ.get('MODEL_PATH')
|
| 43 |
+
model_name = get_model_name_from_env_path('MODEL_PATH')
|
| 44 |
+
data_dir = Path("data")
|
| 45 |
+
pytorch_file = data_dir / f"pytorch-{model_name}.bin"
|
| 46 |
+
|
| 47 |
+
llamacpp_model_name = get_model_name_from_env_path('CONVERTED_MODEL')
|
| 48 |
+
print(f"Using converted model: {llamacpp_model_name}")
|
| 49 |
+
llamacpp_file = data_dir / f"llamacpp-{llamacpp_model_name}.bin"
|
| 50 |
+
|
| 51 |
+
if not pytorch_file.exists():
|
| 52 |
+
print(f"Error: PyTorch logits file not found: {pytorch_file}")
|
| 53 |
+
print("Please run scripts/run-org-model.sh first to generate this file.")
|
| 54 |
+
sys.exit(1)
|
| 55 |
+
|
| 56 |
+
if not llamacpp_file.exists():
|
| 57 |
+
print(f"Error: llama.cpp logits file not found: {llamacpp_file}")
|
| 58 |
+
print("Please run scripts/run-converted-model.sh first to generate this file.")
|
| 59 |
+
sys.exit(1)
|
| 60 |
+
|
| 61 |
+
print("Checked all required files were found. Proceeding...\n")
|
| 62 |
+
|
| 63 |
+
# Verify tokens as they are a prerequisite for logits comparison.
|
| 64 |
+
print("🔍 Token Comparison Check")
|
| 65 |
+
print("=" * 40)
|
| 66 |
+
if not compare_tokens(f"pytorch-{model_name}", f"llamacpp-{llamacpp_model_name}"):
|
| 67 |
+
exit_with_warning("\n❌ Token mismatch detected", model_path)
|
| 68 |
+
print()
|
| 69 |
+
|
| 70 |
+
print("🔍 GGML Model Validation for model ", model_name)
|
| 71 |
+
print("=" * 40)
|
| 72 |
+
print(f"PyTorch logits : {pytorch_file}")
|
| 73 |
+
print(f"llama.cpp logits: {llamacpp_file}")
|
| 74 |
+
print()
|
| 75 |
+
|
| 76 |
+
success = quick_logits_check(pytorch_file, llamacpp_file)
|
| 77 |
+
|
| 78 |
+
# Exit with appropriate code
|
| 79 |
+
if success:
|
| 80 |
+
print("✅ OK: Lightweight model check successful!")
|
| 81 |
+
print(" Ok to proceed with NMSE check...")
|
| 82 |
+
sys.exit(0)
|
| 83 |
+
else:
|
| 84 |
+
exit_with_warning(f"❌ NOK: Top 10 predictions don't match - generation will differ", model_path)
|
| 85 |
+
|
| 86 |
+
if __name__ == "__main__":
|
| 87 |
+
main()
|
examples/model-conversion/scripts/causal/convert-model.sh
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
|
| 3 |
+
set -e
|
| 4 |
+
|
| 5 |
+
# Parse command line arguments
|
| 6 |
+
MMPROJ=""
|
| 7 |
+
DEBUG=""
|
| 8 |
+
while [[ $# -gt 0 ]]; do
|
| 9 |
+
case $1 in
|
| 10 |
+
--mmproj)
|
| 11 |
+
MMPROJ="--mmproj"
|
| 12 |
+
shift
|
| 13 |
+
;;
|
| 14 |
+
--debug)
|
| 15 |
+
DEBUG="1"
|
| 16 |
+
shift
|
| 17 |
+
;;
|
| 18 |
+
*)
|
| 19 |
+
shift
|
| 20 |
+
;;
|
| 21 |
+
esac
|
| 22 |
+
done
|
| 23 |
+
|
| 24 |
+
MODEL_NAME="${MODEL_NAME:-$(basename "$MODEL_PATH")}"
|
| 25 |
+
OUTPUT_DIR="${OUTPUT_DIR:-../../models}"
|
| 26 |
+
TYPE="${OUTTYPE:-f16}"
|
| 27 |
+
METADATA_OVERRIDE="${METADATA_OVERRIDE:-}"
|
| 28 |
+
if [[ -n "$MMPROJ" ]]; then
|
| 29 |
+
CONVERTED_MODEL="${OUTPUT_DIR}/mmproj-${MODEL_NAME}.gguf"
|
| 30 |
+
else
|
| 31 |
+
CONVERTED_MODEL="${OUTPUT_DIR}/${MODEL_NAME}.gguf"
|
| 32 |
+
fi
|
| 33 |
+
|
| 34 |
+
echo "Model path: ${MODEL_PATH}"
|
| 35 |
+
echo "Model name: ${MODEL_NAME}"
|
| 36 |
+
echo "Data type: ${TYPE}"
|
| 37 |
+
echo "Converted model path:: ${CONVERTED_MODEL}"
|
| 38 |
+
echo "Metadata override: ${METADATA_OVERRIDE}"
|
| 39 |
+
|
| 40 |
+
if [[ -n "$DEBUG" ]]; then
|
| 41 |
+
CMD_ARGS=("python" "-m" "pdb")
|
| 42 |
+
else
|
| 43 |
+
CMD_ARGS=("python")
|
| 44 |
+
fi
|
| 45 |
+
|
| 46 |
+
CMD_ARGS+=("../../convert_hf_to_gguf.py" "--verbose")
|
| 47 |
+
CMD_ARGS+=("${MODEL_PATH}")
|
| 48 |
+
CMD_ARGS+=("--outfile" "${CONVERTED_MODEL}")
|
| 49 |
+
CMD_ARGS+=("--outtype" "${TYPE}")
|
| 50 |
+
CMD_ARGS+=("--model-name" "${MODEL_NAME}")
|
| 51 |
+
[[ -n "$METADATA_OVERRIDE" ]] && CMD_ARGS+=("--metadata" "${METADATA_OVERRIDE}")
|
| 52 |
+
[[ -n "$MMPROJ" ]] && CMD_ARGS+=("${MMPROJ}")
|
| 53 |
+
|
| 54 |
+
"${CMD_ARGS[@]}"
|
| 55 |
+
|
| 56 |
+
echo ""
|
| 57 |
+
echo "The environment variable CONVERTED_MODEL can be set to this path using:"
|
| 58 |
+
echo "export CONVERTED_MODEL=$(realpath ${CONVERTED_MODEL})"
|
examples/model-conversion/scripts/causal/modelcard.template
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
base_model:
|
| 3 |
+
- {base_model}
|
| 4 |
+
---
|
| 5 |
+
# {model_name} GGUF
|
| 6 |
+
|
| 7 |
+
Recommended way to run this model:
|
| 8 |
+
|
| 9 |
+
```sh
|
| 10 |
+
llama-server -hf {namespace}/{model_name}-GGUF
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
Then, access http://localhost:8080
|
examples/model-conversion/scripts/causal/run-casual-gen-embeddings-org.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import os
|
| 5 |
+
import importlib
|
| 6 |
+
import torch
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
from transformers import AutoTokenizer, AutoConfig, AutoModelForCausalLM
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
unreleased_model_name = os.getenv('UNRELEASED_MODEL_NAME')
|
| 13 |
+
|
| 14 |
+
parser = argparse.ArgumentParser(description='Process model with specified path')
|
| 15 |
+
parser.add_argument('--model-path', '-m', help='Path to the model')
|
| 16 |
+
args = parser.parse_args()
|
| 17 |
+
|
| 18 |
+
model_path = os.environ.get('MODEL_PATH', args.model_path)
|
| 19 |
+
if model_path is None:
|
| 20 |
+
parser.error("Model path must be specified either via --model-path argument or MODEL_PATH environment variable")
|
| 21 |
+
|
| 22 |
+
config = AutoConfig.from_pretrained(model_path)
|
| 23 |
+
|
| 24 |
+
print("Model type: ", config.model_type)
|
| 25 |
+
print("Vocab size: ", config.vocab_size)
|
| 26 |
+
print("Hidden size: ", config.hidden_size)
|
| 27 |
+
print("Number of layers: ", config.num_hidden_layers)
|
| 28 |
+
print("BOS token id: ", config.bos_token_id)
|
| 29 |
+
print("EOS token id: ", config.eos_token_id)
|
| 30 |
+
|
| 31 |
+
print("Loading model and tokenizer using AutoTokenizer:", model_path)
|
| 32 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path)
|
| 33 |
+
|
| 34 |
+
if unreleased_model_name:
|
| 35 |
+
model_name_lower = unreleased_model_name.lower()
|
| 36 |
+
unreleased_module_path = f"transformers.models.{model_name_lower}.modular_{model_name_lower}"
|
| 37 |
+
class_name = f"{unreleased_model_name}ForCausalLM"
|
| 38 |
+
print(f"Importing unreleased model module: {unreleased_module_path}")
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
model_class = getattr(importlib.import_module(unreleased_module_path), class_name)
|
| 42 |
+
model = model_class.from_pretrained(model_path)
|
| 43 |
+
except (ImportError, AttributeError) as e:
|
| 44 |
+
print(f"Failed to import or load model: {e}")
|
| 45 |
+
print("Falling back to AutoModelForCausalLM")
|
| 46 |
+
model = AutoModelForCausalLM.from_pretrained(model_path)
|
| 47 |
+
else:
|
| 48 |
+
model = AutoModelForCausalLM.from_pretrained(model_path)
|
| 49 |
+
print(f"Model class: {type(model)}")
|
| 50 |
+
#print(f"Model file: {type(model).__module__}")
|
| 51 |
+
|
| 52 |
+
model_name = os.path.basename(model_path)
|
| 53 |
+
print(f"Model name: {model_name}")
|
| 54 |
+
|
| 55 |
+
prompt = "Hello world today"
|
| 56 |
+
input_ids = tokenizer(prompt, return_tensors="pt").input_ids # ty: ignore[call-non-callable]
|
| 57 |
+
print(f"Input tokens: {input_ids}")
|
| 58 |
+
print(f"Input text: {repr(prompt)}")
|
| 59 |
+
print(f"Tokenized: {tokenizer.convert_ids_to_tokens(input_ids[0])}") # ty: ignore[unresolved-attribute]
|
| 60 |
+
|
| 61 |
+
with torch.no_grad():
|
| 62 |
+
outputs = model(input_ids, output_hidden_states=True)
|
| 63 |
+
|
| 64 |
+
# Extract hidden states from the last layer
|
| 65 |
+
# outputs.hidden_states is a tuple of (num_layers + 1) tensors
|
| 66 |
+
# Index -1 gets the last layer, shape: [batch_size, seq_len, hidden_size]
|
| 67 |
+
last_hidden_states = outputs.hidden_states[-1]
|
| 68 |
+
|
| 69 |
+
# Get embeddings for all tokens
|
| 70 |
+
token_embeddings = last_hidden_states[0].float().cpu().numpy() # Remove batch dimension
|
| 71 |
+
|
| 72 |
+
print(f"Hidden states shape: {last_hidden_states.shape}")
|
| 73 |
+
print(f"Token embeddings shape: {token_embeddings.shape}")
|
| 74 |
+
print(f"Hidden dimension: {token_embeddings.shape[-1]}")
|
| 75 |
+
print(f"Number of tokens: {token_embeddings.shape[0]}")
|
| 76 |
+
|
| 77 |
+
# Save raw token embeddings
|
| 78 |
+
data_dir = Path("data")
|
| 79 |
+
data_dir.mkdir(exist_ok=True)
|
| 80 |
+
bin_filename = data_dir / f"pytorch-{model_name}-embeddings.bin"
|
| 81 |
+
txt_filename = data_dir / f"pytorch-{model_name}-embeddings.txt"
|
| 82 |
+
|
| 83 |
+
# Save all token embeddings as binary
|
| 84 |
+
print(token_embeddings)
|
| 85 |
+
token_embeddings.astype(np.float32).tofile(bin_filename)
|
| 86 |
+
|
| 87 |
+
# Save as text for inspection
|
| 88 |
+
with open(txt_filename, "w") as f:
|
| 89 |
+
for i, embedding in enumerate(token_embeddings):
|
| 90 |
+
for j, val in enumerate(embedding):
|
| 91 |
+
f.write(f"{i} {j} {val:.6f}\n")
|
| 92 |
+
|
| 93 |
+
# Print embeddings per token in the requested format
|
| 94 |
+
print("\nToken embeddings:")
|
| 95 |
+
tokens = tokenizer.convert_ids_to_tokens(input_ids[0]) # ty: ignore[unresolved-attribute]
|
| 96 |
+
for i, embedding in enumerate(token_embeddings):
|
| 97 |
+
# Format: show first few values, ..., then last few values
|
| 98 |
+
if len(embedding) > 10:
|
| 99 |
+
# Show first 3 and last 3 values with ... in between
|
| 100 |
+
first_vals = " ".join(f"{val:8.6f}" for val in embedding[:3])
|
| 101 |
+
last_vals = " ".join(f"{val:8.6f}" for val in embedding[-3:])
|
| 102 |
+
print(f"embedding {i}: {first_vals} ... {last_vals}")
|
| 103 |
+
else:
|
| 104 |
+
# If embedding is short, show all values
|
| 105 |
+
vals = " ".join(f"{val:8.6f}" for val in embedding)
|
| 106 |
+
print(f"embedding {i}: {vals}")
|
| 107 |
+
|
| 108 |
+
# Also show token info for reference
|
| 109 |
+
print(f"\nToken reference:")
|
| 110 |
+
for i, token in enumerate(tokens):
|
| 111 |
+
print(f" Token {i}: {repr(token)}")
|
| 112 |
+
|
| 113 |
+
print(f"Saved bin logits to: {bin_filename}")
|
| 114 |
+
print(f"Saved txt logist to: {txt_filename}")
|
examples/model-conversion/scripts/causal/run-converted-model-embeddings-logits.sh
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
|
| 3 |
+
set -e
|
| 4 |
+
|
| 5 |
+
# First try command line argument, then environment variable, then file
|
| 6 |
+
CONVERTED_MODEL="${1:-"$CONVERTED_MODEL"}"
|
| 7 |
+
BUILD_DIR="${2:-"$BUILD_DIR"}"
|
| 8 |
+
|
| 9 |
+
# Final check if we have a model path
|
| 10 |
+
if [ -z "$CONVERTED_MODEL" ]; then
|
| 11 |
+
echo "Error: Model path must be provided either as:" >&2
|
| 12 |
+
echo " 1. Command line argument" >&2
|
| 13 |
+
echo " 2. CONVERTED_MODEL environment variable" >&2
|
| 14 |
+
exit 1
|
| 15 |
+
fi
|
| 16 |
+
|
| 17 |
+
if [ -z "$BUILD_DIR" ]; then
|
| 18 |
+
BUILD_DIR="../../build"
|
| 19 |
+
fi
|
| 20 |
+
|
| 21 |
+
cmake --build ${BUILD_DIR} --target llama-debug -j8
|
| 22 |
+
|
| 23 |
+
${BUILD_DIR}/bin/llama-debug -m $CONVERTED_MODEL --embedding -p "Hello world today" --save-logits
|
examples/model-conversion/scripts/causal/run-converted-model.sh
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
|
| 3 |
+
set -e
|
| 4 |
+
|
| 5 |
+
# First try command line argument, then environment variable, then file
|
| 6 |
+
CONVERTED_MODEL="${1:-"$CONVERTED_MODEL"}"
|
| 7 |
+
MODEL_TESTING_PROMPT="${2:-"$MODEL_TESTING_PROMPT"}"
|
| 8 |
+
BUILD_DIR="${3:-"$BUILD_DIR"}"
|
| 9 |
+
|
| 10 |
+
if [ -z "$MODEL_TESTING_PROMPT" ]; then
|
| 11 |
+
MODEL_TESTING_PROMPT="Hello, my name is"
|
| 12 |
+
fi
|
| 13 |
+
|
| 14 |
+
if [ -z "$BUILD_DIR" ]; then
|
| 15 |
+
BUILD_DIR="../../build"
|
| 16 |
+
fi
|
| 17 |
+
|
| 18 |
+
# Final check if we have a model path
|
| 19 |
+
if [ -z "$CONVERTED_MODEL" ]; then
|
| 20 |
+
echo "Error: Model path must be provided either as:" >&2
|
| 21 |
+
echo " 1. Command line argument" >&2
|
| 22 |
+
echo " 2. CONVERTED_MODEL environment variable" >&2
|
| 23 |
+
exit 1
|
| 24 |
+
fi
|
| 25 |
+
|
| 26 |
+
echo $CONVERTED_MODEL
|
| 27 |
+
echo $MODEL_TESTING_PROMPT
|
| 28 |
+
|
| 29 |
+
cmake --build ${BUILD_DIR} --target llama-debug -j8
|
| 30 |
+
|
| 31 |
+
${BUILD_DIR}/bin/llama-debug -m "$CONVERTED_MODEL" -p "$MODEL_TESTING_PROMPT" --save-logits
|
examples/model-conversion/scripts/causal/run-org-model.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
import importlib
|
| 7 |
+
import torch
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, AutoModelForImageTextToText, AutoConfig
|
| 11 |
+
|
| 12 |
+
# Add parent directory to path for imports
|
| 13 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
|
| 14 |
+
from utils.common import debug_hook, save_output_data
|
| 15 |
+
|
| 16 |
+
def parse_arguments():
|
| 17 |
+
parser = argparse.ArgumentParser(description="Process model with specified path")
|
| 18 |
+
parser.add_argument("--model-path", "-m", help="Path to the model")
|
| 19 |
+
parser.add_argument("--prompt-file", "-f", help="Optional prompt file", required=False)
|
| 20 |
+
parser.add_argument("--verbose", "-v", action="store_true", help="Enable verbose debug output")
|
| 21 |
+
parser.add_argument("--device", "-d", help="Device to use (cpu, cuda, mps, auto)", default="auto")
|
| 22 |
+
return parser.parse_args()
|
| 23 |
+
|
| 24 |
+
def load_model_and_tokenizer(model_path, device="auto"):
|
| 25 |
+
print("Loading model and tokenizer using AutoTokenizer:", model_path)
|
| 26 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
| 27 |
+
config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
|
| 28 |
+
multimodal = False
|
| 29 |
+
full_config = config
|
| 30 |
+
|
| 31 |
+
# Determine device_map based on device argument
|
| 32 |
+
if device == "cpu":
|
| 33 |
+
device_map = {"": "cpu"}
|
| 34 |
+
print("Forcing CPU usage")
|
| 35 |
+
elif device == "auto":
|
| 36 |
+
device_map = "auto"
|
| 37 |
+
else:
|
| 38 |
+
device_map = {"": device}
|
| 39 |
+
|
| 40 |
+
print("Model type: ", config.model_type)
|
| 41 |
+
if "vocab_size" not in config and "text_config" in config:
|
| 42 |
+
config = config.text_config
|
| 43 |
+
multimodal = True
|
| 44 |
+
|
| 45 |
+
def print_if_exists(label, obj, attr, default="N/A"):
|
| 46 |
+
val = getattr(obj, attr) if hasattr(obj, attr) else default
|
| 47 |
+
print(f"{label}", val)
|
| 48 |
+
|
| 49 |
+
print_if_exists("Vocab size: ", config, "vocab_size")
|
| 50 |
+
print_if_exists("Hidden size: ", config, "hidden_size")
|
| 51 |
+
print_if_exists("Number of layers: ", config, "num_hidden_layers")
|
| 52 |
+
print_if_exists("BOS token id: ", config, "bos_token_id")
|
| 53 |
+
print_if_exists("EOS token id: ", config, "eos_token_id")
|
| 54 |
+
|
| 55 |
+
unreleased_model_name = os.getenv("UNRELEASED_MODEL_NAME")
|
| 56 |
+
if unreleased_model_name:
|
| 57 |
+
model_name_lower = unreleased_model_name.lower()
|
| 58 |
+
unreleased_module_path = (
|
| 59 |
+
f"transformers.models.{model_name_lower}.modular_{model_name_lower}"
|
| 60 |
+
)
|
| 61 |
+
class_name = f"{unreleased_model_name}ForCausalLM"
|
| 62 |
+
print(f"Importing unreleased model module: {unreleased_module_path}")
|
| 63 |
+
|
| 64 |
+
try:
|
| 65 |
+
model_class = getattr(importlib.import_module(unreleased_module_path), class_name)
|
| 66 |
+
model = model_class.from_pretrained(
|
| 67 |
+
model_path,
|
| 68 |
+
device_map=device_map,
|
| 69 |
+
offload_folder="offload",
|
| 70 |
+
trust_remote_code=True,
|
| 71 |
+
config=config
|
| 72 |
+
)
|
| 73 |
+
except (ImportError, AttributeError) as e:
|
| 74 |
+
print(f"Failed to import or load model: {e}")
|
| 75 |
+
exit(1)
|
| 76 |
+
else:
|
| 77 |
+
if multimodal:
|
| 78 |
+
model = AutoModelForImageTextToText.from_pretrained(
|
| 79 |
+
model_path,
|
| 80 |
+
device_map=device_map,
|
| 81 |
+
offload_folder="offload",
|
| 82 |
+
trust_remote_code=True,
|
| 83 |
+
config=full_config
|
| 84 |
+
)
|
| 85 |
+
else:
|
| 86 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 87 |
+
model_path,
|
| 88 |
+
device_map=device_map,
|
| 89 |
+
offload_folder="offload",
|
| 90 |
+
trust_remote_code=True,
|
| 91 |
+
config=config
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
print(f"Model class: {model.__class__.__name__}")
|
| 95 |
+
|
| 96 |
+
return model, tokenizer, config
|
| 97 |
+
|
| 98 |
+
def enable_torch_debugging(model):
|
| 99 |
+
for name, module in model.named_modules():
|
| 100 |
+
if len(list(module.children())) == 0: # only leaf modules
|
| 101 |
+
module.register_forward_hook(debug_hook(name))
|
| 102 |
+
|
| 103 |
+
def get_prompt(args):
|
| 104 |
+
if args.prompt_file:
|
| 105 |
+
with open(args.prompt_file, encoding='utf-8') as f:
|
| 106 |
+
return f.read()
|
| 107 |
+
elif os.getenv("MODEL_TESTING_PROMPT"):
|
| 108 |
+
return os.getenv("MODEL_TESTING_PROMPT")
|
| 109 |
+
else:
|
| 110 |
+
return "Hello, my name is"
|
| 111 |
+
|
| 112 |
+
def main():
|
| 113 |
+
args = parse_arguments()
|
| 114 |
+
model_path = os.environ.get("MODEL_PATH", args.model_path)
|
| 115 |
+
if model_path is None:
|
| 116 |
+
print("Error: Model path must be specified either via --model-path argument or MODEL_PATH environment variable")
|
| 117 |
+
sys.exit(1)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
model, tokenizer, config = load_model_and_tokenizer(model_path, args.device)
|
| 121 |
+
|
| 122 |
+
if args.verbose:
|
| 123 |
+
enable_torch_debugging(model)
|
| 124 |
+
|
| 125 |
+
model_name = os.path.basename(model_path)
|
| 126 |
+
|
| 127 |
+
# Iterate over the model parameters (the tensors) and get the first one
|
| 128 |
+
# and use it to get the device the model is on.
|
| 129 |
+
device = next(model.parameters()).device
|
| 130 |
+
prompt = get_prompt(args)
|
| 131 |
+
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
|
| 132 |
+
token_ids = input_ids[0].cpu().tolist()
|
| 133 |
+
|
| 134 |
+
print(f"Input tokens: {input_ids}")
|
| 135 |
+
print(f"Input text: {repr(prompt)}")
|
| 136 |
+
print(f"Tokenized: {tokenizer.convert_ids_to_tokens(input_ids[0])}")
|
| 137 |
+
|
| 138 |
+
batch_size = 512
|
| 139 |
+
|
| 140 |
+
with torch.no_grad():
|
| 141 |
+
past = None
|
| 142 |
+
outputs = None
|
| 143 |
+
for i in range(0, input_ids.size(1), batch_size):
|
| 144 |
+
print(f"Processing chunk with tokens {i} to {i + batch_size}")
|
| 145 |
+
chunk = input_ids[:, i:i + batch_size]
|
| 146 |
+
outputs = model(chunk.to(model.device), past_key_values=past, use_cache=True)
|
| 147 |
+
past = outputs.past_key_values
|
| 148 |
+
|
| 149 |
+
logits = outputs.logits # type: ignore
|
| 150 |
+
|
| 151 |
+
# Extract logits for the last token (next token prediction)
|
| 152 |
+
last_logits = logits[0, -1, :].float().cpu().numpy()
|
| 153 |
+
|
| 154 |
+
print(f"Logits shape: {logits.shape}")
|
| 155 |
+
print(f"Last token logits shape: {last_logits.shape}")
|
| 156 |
+
print(f"Vocab size: {len(last_logits)}")
|
| 157 |
+
|
| 158 |
+
# Print some sample logits for quick verification
|
| 159 |
+
print(f"First 10 logits: {last_logits[:10]}")
|
| 160 |
+
print(f"Last 10 logits: {last_logits[-10:]}")
|
| 161 |
+
|
| 162 |
+
# Show top 5 predicted tokens
|
| 163 |
+
top_indices = np.argsort(last_logits)[-5:][::-1]
|
| 164 |
+
print("Top 5 predictions:")
|
| 165 |
+
for idx in top_indices:
|
| 166 |
+
token = tokenizer.decode([idx])
|
| 167 |
+
print(f" Token {idx} ({repr(token)}): {last_logits[idx]:.6f}")
|
| 168 |
+
|
| 169 |
+
save_output_data(last_logits, token_ids, prompt, model_name)
|
| 170 |
+
|
| 171 |
+
if __name__ == "__main__":
|
| 172 |
+
main()
|
examples/model-conversion/scripts/embedding/compare-embeddings-logits.sh
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
|
| 3 |
+
set -e
|
| 4 |
+
|
| 5 |
+
# Parse command line arguments
|
| 6 |
+
MODEL_PATH=""
|
| 7 |
+
MODEL_NAME=""
|
| 8 |
+
PROMPTS_FILE=""
|
| 9 |
+
|
| 10 |
+
# First argument is always model path
|
| 11 |
+
if [ $# -gt 0 ] && [[ "$1" != --* ]]; then
|
| 12 |
+
MODEL_PATH="$1"
|
| 13 |
+
shift
|
| 14 |
+
fi
|
| 15 |
+
|
| 16 |
+
# Parse remaining arguments
|
| 17 |
+
while [[ $# -gt 0 ]]; do
|
| 18 |
+
case $1 in
|
| 19 |
+
--prompts-file|-pf)
|
| 20 |
+
PROMPTS_FILE="$2"
|
| 21 |
+
shift 2
|
| 22 |
+
;;
|
| 23 |
+
*)
|
| 24 |
+
# If MODEL_NAME not set and this isn't a flag, use as model name
|
| 25 |
+
if [ -z "$MODEL_NAME" ] && [[ "$1" != --* ]]; then
|
| 26 |
+
MODEL_NAME="$1"
|
| 27 |
+
fi
|
| 28 |
+
shift
|
| 29 |
+
;;
|
| 30 |
+
esac
|
| 31 |
+
done
|
| 32 |
+
|
| 33 |
+
# Set defaults
|
| 34 |
+
MODEL_PATH="${MODEL_PATH:-"$EMBEDDING_MODEL_PATH"}"
|
| 35 |
+
MODEL_NAME="${MODEL_NAME:-$(basename "$MODEL_PATH")}"
|
| 36 |
+
|
| 37 |
+
CONVERTED_MODEL_PATH="${CONVERTED_EMBEDDING_PATH:-"$CONVERTED_EMBEDDING_MODEL"}"
|
| 38 |
+
CONVERTED_MODEL_NAME="${CONVERTED_MODEL_NAME:-$(basename "$CONVERTED_MODEL_PATH" .gguf)}"
|
| 39 |
+
|
| 40 |
+
if [ -t 0 ]; then
|
| 41 |
+
CPP_EMBEDDINGS="data/llamacpp-${CONVERTED_MODEL_NAME}-embeddings.bin"
|
| 42 |
+
else
|
| 43 |
+
# Process piped JSON data and convert to binary (matching logits.cpp format)
|
| 44 |
+
TEMP_FILE=$(mktemp /tmp/tmp.XXXXXX.binn)
|
| 45 |
+
python3 -c "
|
| 46 |
+
import json
|
| 47 |
+
import sys
|
| 48 |
+
import struct
|
| 49 |
+
|
| 50 |
+
data = json.load(sys.stdin)
|
| 51 |
+
|
| 52 |
+
# Flatten all embeddings completely
|
| 53 |
+
flattened = []
|
| 54 |
+
for item in data:
|
| 55 |
+
embedding = item['embedding']
|
| 56 |
+
for token_embedding in embedding:
|
| 57 |
+
flattened.extend(token_embedding)
|
| 58 |
+
|
| 59 |
+
print(f'Total embedding values: {len(flattened)}', file=sys.stderr)
|
| 60 |
+
|
| 61 |
+
# Write as binary floats - matches logitc.cpp fwrite format
|
| 62 |
+
with open('$TEMP_FILE', 'wb') as f:
|
| 63 |
+
for value in flattened:
|
| 64 |
+
f.write(struct.pack('f', value))
|
| 65 |
+
"
|
| 66 |
+
CPP_EMBEDDINGS="$TEMP_FILE"
|
| 67 |
+
trap "rm -f $TEMP_FILE" EXIT
|
| 68 |
+
fi
|
| 69 |
+
|
| 70 |
+
# Build the semantic_check.py command
|
| 71 |
+
SEMANTIC_CMD="python scripts/utils/semantic_check.py --model-path $MODEL_PATH \
|
| 72 |
+
--python-embeddings data/pytorch-${MODEL_NAME}-embeddings.bin \
|
| 73 |
+
--cpp-embeddings $CPP_EMBEDDINGS"
|
| 74 |
+
|
| 75 |
+
# Add prompts file if specified, otherwise use default prompt
|
| 76 |
+
if [ -n "$PROMPTS_FILE" ]; then
|
| 77 |
+
SEMANTIC_CMD="$SEMANTIC_CMD --prompts-file \"$PROMPTS_FILE\""
|
| 78 |
+
else
|
| 79 |
+
SEMANTIC_CMD="$SEMANTIC_CMD --prompt \"Hello world today\""
|
| 80 |
+
fi
|
| 81 |
+
|
| 82 |
+
# Execute the command
|
| 83 |
+
eval $SEMANTIC_CMD
|
| 84 |
+
|
examples/model-conversion/scripts/embedding/convert-model.sh
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
|
| 3 |
+
set -e
|
| 4 |
+
|
| 5 |
+
# Parse command line arguments
|
| 6 |
+
SENTENCE_TRANSFORMERS=""
|
| 7 |
+
while [[ $# -gt 0 ]]; do
|
| 8 |
+
case $1 in
|
| 9 |
+
-st|--sentence-transformers)
|
| 10 |
+
SENTENCE_TRANSFORMERS="--sentence-transformers-dense-modules"
|
| 11 |
+
shift
|
| 12 |
+
;;
|
| 13 |
+
*)
|
| 14 |
+
echo "Unknown option: $1"
|
| 15 |
+
exit 1
|
| 16 |
+
;;
|
| 17 |
+
esac
|
| 18 |
+
done
|
| 19 |
+
|
| 20 |
+
MODEL_NAME="${MODEL_NAME:-$(basename "$EMBEDDING_MODEL_PATH")}"
|
| 21 |
+
OUTPUT_DIR="${OUTPUT_DIR:-../../models}"
|
| 22 |
+
TYPE="${OUTTYPE:-f16}"
|
| 23 |
+
METADATA_OVERRIDE="${METADATA_OVERRIDE:-}"
|
| 24 |
+
CONVERTED_MODEL="${OUTPUT_DIR}/${MODEL_NAME}.gguf"
|
| 25 |
+
|
| 26 |
+
echo "Model path: ${EMBEDDING_MODEL_PATH}"
|
| 27 |
+
echo "Model name: ${MODEL_NAME}"
|
| 28 |
+
echo "Data type: ${TYPE}"
|
| 29 |
+
echo "Converted model path:: ${CONVERTED_MODEL}"
|
| 30 |
+
python ../../convert_hf_to_gguf.py --verbose \
|
| 31 |
+
${EMBEDDING_MODEL_PATH} \
|
| 32 |
+
--outfile ${CONVERTED_MODEL} \
|
| 33 |
+
--outtype ${TYPE} \
|
| 34 |
+
--model-name ${MODEL_NAME} \
|
| 35 |
+
${SENTENCE_TRANSFORMERS}
|
| 36 |
+
|
| 37 |
+
echo ""
|
| 38 |
+
echo "The environment variable CONVERTED_EMBEDDING MODEL can be set to this path using:"
|
| 39 |
+
echo "export CONVERTED_EMBEDDING_MODEL=$(realpath ${CONVERTED_MODEL})"
|
examples/model-conversion/scripts/embedding/modelcard.template
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
base_model:
|
| 3 |
+
- {base_model}
|
| 4 |
+
---
|
| 5 |
+
# {model_name} GGUF
|
| 6 |
+
|
| 7 |
+
Recommended way to run this model:
|
| 8 |
+
|
| 9 |
+
```sh
|
| 10 |
+
llama-server -hf {namespace}/{model_name}-GGUF --embeddings
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
Then the endpoint can be accessed at http://localhost:8080/embedding, for
|
| 14 |
+
example using `curl`:
|
| 15 |
+
```console
|
| 16 |
+
curl --request POST \
|
| 17 |
+
--url http://localhost:8080/embedding \
|
| 18 |
+
--header "Content-Type: application/json" \
|
| 19 |
+
--data '{{"input": "Hello embeddings"}}' \
|
| 20 |
+
--silent
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
Alternatively, the `llama-embedding` command line tool can be used:
|
| 24 |
+
```sh
|
| 25 |
+
llama-embedding -hf {namespace}/{model_name}-GGUF --verbose-prompt -p "Hello embeddings"
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
#### embd_normalize
|
| 29 |
+
When a model uses pooling, or the pooling method is specified using `--pooling`,
|
| 30 |
+
the normalization can be controlled by the `embd_normalize` parameter.
|
| 31 |
+
|
| 32 |
+
The default value is `2` which means that the embeddings are normalized using
|
| 33 |
+
the Euclidean norm (L2). Other options are:
|
| 34 |
+
* -1 No normalization
|
| 35 |
+
* 0 Max absolute
|
| 36 |
+
* 1 Taxicab
|
| 37 |
+
* 2 Euclidean/L2
|
| 38 |
+
* \>2 P-Norm
|
| 39 |
+
|
| 40 |
+
This can be passed in the request body to `llama-server`, for example:
|
| 41 |
+
```sh
|
| 42 |
+
--data '{{"input": "Hello embeddings", "embd_normalize": -1}}' \
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
And for `llama-embedding`, by passing `--embd-normalize <value>`, for example:
|
| 46 |
+
```sh
|
| 47 |
+
llama-embedding -hf {namespace}/{model_name}-GGUF --embd-normalize -1 -p "Hello embeddings"
|
| 48 |
+
```
|
examples/model-conversion/scripts/embedding/run-converted-model.sh
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
|
| 3 |
+
set -e
|
| 4 |
+
|
| 5 |
+
# Parse command line arguments
|
| 6 |
+
CONVERTED_MODEL=""
|
| 7 |
+
PROMPTS_FILE=""
|
| 8 |
+
EMBD_NORMALIZE="2"
|
| 9 |
+
|
| 10 |
+
while [[ $# -gt 0 ]]; do
|
| 11 |
+
case $1 in
|
| 12 |
+
-p|--prompts-file)
|
| 13 |
+
PROMPTS_FILE="$2"
|
| 14 |
+
shift 2
|
| 15 |
+
;;
|
| 16 |
+
--embd-normalize)
|
| 17 |
+
EMBD_NORMALIZE="$2"
|
| 18 |
+
shift 2
|
| 19 |
+
;;
|
| 20 |
+
*)
|
| 21 |
+
if [ -z "$CONVERTED_MODEL" ]; then
|
| 22 |
+
CONVERTED_MODEL="$1"
|
| 23 |
+
fi
|
| 24 |
+
shift
|
| 25 |
+
;;
|
| 26 |
+
esac
|
| 27 |
+
done
|
| 28 |
+
|
| 29 |
+
# First try command line argument, then environment variable
|
| 30 |
+
CONVERTED_MODEL="${CONVERTED_MODEL:-"$CONVERTED_EMBEDDING_MODEL"}"
|
| 31 |
+
BUILD_DIR="${BUILD_DIR:-"../../build"}"
|
| 32 |
+
|
| 33 |
+
# Final check if we have a model path
|
| 34 |
+
if [ -z "$CONVERTED_MODEL" ]; then
|
| 35 |
+
echo "Error: Model path must be provided either as:" >&2
|
| 36 |
+
echo " 1. Command line argument" >&2
|
| 37 |
+
echo " 2. CONVERTED_EMBEDDING_MODEL environment variable" >&2
|
| 38 |
+
exit 1
|
| 39 |
+
fi
|
| 40 |
+
|
| 41 |
+
# Read prompt from file or use default
|
| 42 |
+
if [ -n "$PROMPTS_FILE" ]; then
|
| 43 |
+
if [ ! -f "$PROMPTS_FILE" ]; then
|
| 44 |
+
echo "Error: Prompts file '$PROMPTS_FILE' not found" >&2
|
| 45 |
+
exit 1
|
| 46 |
+
fi
|
| 47 |
+
PROMPT=$(cat "$PROMPTS_FILE")
|
| 48 |
+
else
|
| 49 |
+
PROMPT="Hello world today"
|
| 50 |
+
fi
|
| 51 |
+
|
| 52 |
+
echo $CONVERTED_MODEL
|
| 53 |
+
|
| 54 |
+
cmake --build ${BUILD_DIR} --target llama-debug -j8
|
| 55 |
+
${BUILD_DIR}/bin/llama-debug -m "$CONVERTED_MODEL" --embedding -p "$PROMPT" --save-logits --embd-normalize $EMBD_NORMALIZE
|
examples/model-conversion/scripts/embedding/run-original-model.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
import importlib
|
| 7 |
+
|
| 8 |
+
from transformers import AutoTokenizer, AutoConfig, AutoModel
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
# Add parent directory to path for imports
|
| 12 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
|
| 13 |
+
from utils.common import save_output_data
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def parse_arguments():
|
| 17 |
+
parser = argparse.ArgumentParser(description='Run original embedding model')
|
| 18 |
+
parser.add_argument(
|
| 19 |
+
'--model-path',
|
| 20 |
+
'-m',
|
| 21 |
+
help='Path to the model'
|
| 22 |
+
)
|
| 23 |
+
parser.add_argument(
|
| 24 |
+
'--prompts-file',
|
| 25 |
+
'-p',
|
| 26 |
+
help='Path to file containing prompts (one per line)'
|
| 27 |
+
)
|
| 28 |
+
parser.add_argument(
|
| 29 |
+
'--use-sentence-transformers',
|
| 30 |
+
action='store_true',
|
| 31 |
+
help=('Use SentenceTransformer to apply all numbered layers '
|
| 32 |
+
'(01_Pooling, 02_Dense, 03_Dense, 04_Normalize)')
|
| 33 |
+
)
|
| 34 |
+
parser.add_argument(
|
| 35 |
+
'--device',
|
| 36 |
+
'-d',
|
| 37 |
+
help='Device to use (cpu, cuda, mps, auto)',
|
| 38 |
+
default='auto'
|
| 39 |
+
)
|
| 40 |
+
return parser.parse_args()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def load_model_and_tokenizer(model_path, use_sentence_transformers=False, device="auto"):
|
| 44 |
+
if device == "cpu":
|
| 45 |
+
device_map = {"": "cpu"}
|
| 46 |
+
print("Forcing CPU usage")
|
| 47 |
+
elif device == "auto":
|
| 48 |
+
# On Mac, "auto" device_map can cause issues with accelerate
|
| 49 |
+
# So we detect the best device manually
|
| 50 |
+
if torch.cuda.is_available():
|
| 51 |
+
device_map = {"": "cuda"}
|
| 52 |
+
print("Using CUDA")
|
| 53 |
+
elif torch.backends.mps.is_available():
|
| 54 |
+
device_map = {"": "mps"}
|
| 55 |
+
print("Using MPS (Apple Metal)")
|
| 56 |
+
else:
|
| 57 |
+
device_map = {"": "cpu"}
|
| 58 |
+
print("Using CPU")
|
| 59 |
+
else:
|
| 60 |
+
device_map = {"": device}
|
| 61 |
+
|
| 62 |
+
if use_sentence_transformers:
|
| 63 |
+
from sentence_transformers import SentenceTransformer
|
| 64 |
+
print("Using SentenceTransformer to apply all numbered layers")
|
| 65 |
+
model = SentenceTransformer(model_path)
|
| 66 |
+
tokenizer = model.tokenizer
|
| 67 |
+
config = model[0].auto_model.config # ty: ignore[unresolved-attribute]
|
| 68 |
+
else:
|
| 69 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path)
|
| 70 |
+
config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
|
| 71 |
+
|
| 72 |
+
# This can be used to override the sliding window size for manual testing. This
|
| 73 |
+
# can be useful to verify the sliding window attention mask in the original model
|
| 74 |
+
# and compare it with the converted .gguf model.
|
| 75 |
+
if hasattr(config, 'sliding_window'):
|
| 76 |
+
original_sliding_window = config.sliding_window
|
| 77 |
+
print(f"Modified sliding window: {original_sliding_window} -> {config.sliding_window}")
|
| 78 |
+
|
| 79 |
+
unreleased_model_name = os.getenv('UNRELEASED_MODEL_NAME')
|
| 80 |
+
print(f"Using unreleased model: {unreleased_model_name}")
|
| 81 |
+
if unreleased_model_name:
|
| 82 |
+
model_name_lower = unreleased_model_name.lower()
|
| 83 |
+
unreleased_module_path = f"transformers.models.{model_name_lower}.modular_{model_name_lower}"
|
| 84 |
+
class_name = f"{unreleased_model_name}Model"
|
| 85 |
+
print(f"Importing unreleased model module: {unreleased_module_path}")
|
| 86 |
+
|
| 87 |
+
try:
|
| 88 |
+
model_class = getattr(importlib.import_module(unreleased_module_path), class_name)
|
| 89 |
+
model = model_class.from_pretrained(
|
| 90 |
+
model_path,
|
| 91 |
+
device_map=device_map,
|
| 92 |
+
offload_folder="offload",
|
| 93 |
+
trust_remote_code=True,
|
| 94 |
+
config=config
|
| 95 |
+
)
|
| 96 |
+
except (ImportError, AttributeError) as e:
|
| 97 |
+
print(f"Failed to import or load model: {e}")
|
| 98 |
+
sys.exit(1)
|
| 99 |
+
else:
|
| 100 |
+
model = AutoModel.from_pretrained(
|
| 101 |
+
model_path,
|
| 102 |
+
device_map=device_map,
|
| 103 |
+
offload_folder="offload",
|
| 104 |
+
trust_remote_code=True,
|
| 105 |
+
config=config
|
| 106 |
+
)
|
| 107 |
+
print(f"Model class: {type(model)}")
|
| 108 |
+
print(f"Model file: {type(model).__module__}")
|
| 109 |
+
|
| 110 |
+
# Verify the model is using the correct sliding window
|
| 111 |
+
if hasattr(model.config, 'sliding_window'):
|
| 112 |
+
print(f"Model's sliding_window: {model.config.sliding_window}")
|
| 113 |
+
else:
|
| 114 |
+
print("Model config does not have sliding_window attribute")
|
| 115 |
+
|
| 116 |
+
return model, tokenizer, config
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def get_prompt(args):
|
| 120 |
+
if args.prompts_file:
|
| 121 |
+
try:
|
| 122 |
+
with open(args.prompts_file, 'r', encoding='utf-8') as f:
|
| 123 |
+
return f.read().strip()
|
| 124 |
+
except FileNotFoundError:
|
| 125 |
+
print(f"Error: Prompts file '{args.prompts_file}' not found")
|
| 126 |
+
sys.exit(1)
|
| 127 |
+
except Exception as e:
|
| 128 |
+
print(f"Error reading prompts file: {e}")
|
| 129 |
+
sys.exit(1)
|
| 130 |
+
else:
|
| 131 |
+
return "Hello world today"
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def main():
|
| 135 |
+
args = parse_arguments()
|
| 136 |
+
|
| 137 |
+
model_path = os.environ.get('EMBEDDING_MODEL_PATH', args.model_path)
|
| 138 |
+
if model_path is None:
|
| 139 |
+
print("Error: Model path must be specified either via --model-path argument "
|
| 140 |
+
"or EMBEDDING_MODEL_PATH environment variable")
|
| 141 |
+
sys.exit(1)
|
| 142 |
+
|
| 143 |
+
# Determine if we should use SentenceTransformer
|
| 144 |
+
use_st = (
|
| 145 |
+
args.use_sentence_transformers or os.environ.get('USE_SENTENCE_TRANSFORMERS', '').lower() in ('1', 'true', 'yes')
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
model, tokenizer, config = load_model_and_tokenizer(model_path, use_st, args.device)
|
| 149 |
+
|
| 150 |
+
# Get the device the model is on
|
| 151 |
+
if not use_st:
|
| 152 |
+
device = next(model.parameters()).device
|
| 153 |
+
else:
|
| 154 |
+
# For SentenceTransformer, get device from the underlying model
|
| 155 |
+
device = next(model[0].auto_model.parameters()).device
|
| 156 |
+
|
| 157 |
+
model_name = os.path.basename(model_path)
|
| 158 |
+
|
| 159 |
+
prompt_text = get_prompt(args)
|
| 160 |
+
texts = [prompt_text]
|
| 161 |
+
|
| 162 |
+
with torch.no_grad():
|
| 163 |
+
if use_st:
|
| 164 |
+
embeddings = model.encode(texts, convert_to_numpy=True)
|
| 165 |
+
all_embeddings = embeddings # Shape: [batch_size, hidden_size]
|
| 166 |
+
|
| 167 |
+
encoded = tokenizer(
|
| 168 |
+
texts,
|
| 169 |
+
padding=True,
|
| 170 |
+
truncation=True,
|
| 171 |
+
return_tensors="pt"
|
| 172 |
+
)
|
| 173 |
+
tokens = encoded['input_ids'][0]
|
| 174 |
+
token_ids = tokens.cpu().tolist()
|
| 175 |
+
token_strings = tokenizer.convert_ids_to_tokens(tokens)
|
| 176 |
+
for i, (token_id, token_str) in enumerate(zip(tokens, token_strings)):
|
| 177 |
+
print(f"{token_id:6d} -> '{token_str}'")
|
| 178 |
+
|
| 179 |
+
print(f"Embeddings shape (after all SentenceTransformer layers): {all_embeddings.shape}")
|
| 180 |
+
print(f"Embedding dimension: {all_embeddings.shape[1] if len(all_embeddings.shape) > 1 else all_embeddings.shape[0]}")
|
| 181 |
+
else:
|
| 182 |
+
# Standard approach: use base model output only
|
| 183 |
+
encoded = tokenizer(
|
| 184 |
+
texts,
|
| 185 |
+
padding=True,
|
| 186 |
+
truncation=True,
|
| 187 |
+
return_tensors="pt"
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
tokens = encoded['input_ids'][0]
|
| 191 |
+
token_ids = tokens.cpu().tolist()
|
| 192 |
+
token_strings = tokenizer.convert_ids_to_tokens(tokens)
|
| 193 |
+
for i, (token_id, token_str) in enumerate(zip(tokens, token_strings)):
|
| 194 |
+
print(f"{token_id:6d} -> '{token_str}'")
|
| 195 |
+
|
| 196 |
+
# Move inputs to the same device as the model
|
| 197 |
+
encoded = {k: v.to(device) for k, v in encoded.items()}
|
| 198 |
+
outputs = model(**encoded)
|
| 199 |
+
hidden_states = outputs.last_hidden_state # Shape: [batch_size, seq_len, hidden_size]
|
| 200 |
+
|
| 201 |
+
all_embeddings = hidden_states[0].float().cpu().numpy() # Shape: [seq_len, hidden_size]
|
| 202 |
+
|
| 203 |
+
print(f"Hidden states shape: {hidden_states.shape}")
|
| 204 |
+
print(f"All embeddings shape: {all_embeddings.shape}")
|
| 205 |
+
print(f"Embedding dimension: {all_embeddings.shape[1]}")
|
| 206 |
+
|
| 207 |
+
if len(all_embeddings.shape) == 1:
|
| 208 |
+
n_embd = all_embeddings.shape[0]
|
| 209 |
+
n_embd_count = 1
|
| 210 |
+
all_embeddings = all_embeddings.reshape(1, -1)
|
| 211 |
+
else:
|
| 212 |
+
n_embd = all_embeddings.shape[1]
|
| 213 |
+
n_embd_count = all_embeddings.shape[0]
|
| 214 |
+
|
| 215 |
+
print()
|
| 216 |
+
|
| 217 |
+
for j in range(n_embd_count):
|
| 218 |
+
embedding = all_embeddings[j]
|
| 219 |
+
print(f"embedding {j}: ", end="")
|
| 220 |
+
|
| 221 |
+
# Print first 3 values
|
| 222 |
+
for i in range(min(3, n_embd)):
|
| 223 |
+
print(f"{embedding[i]:9.6f} ", end="")
|
| 224 |
+
|
| 225 |
+
print(" ... ", end="")
|
| 226 |
+
|
| 227 |
+
# Print last 3 values
|
| 228 |
+
for i in range(n_embd - 3, n_embd):
|
| 229 |
+
print(f"{embedding[i]:9.6f} ", end="")
|
| 230 |
+
|
| 231 |
+
print() # New line
|
| 232 |
+
|
| 233 |
+
print()
|
| 234 |
+
|
| 235 |
+
flattened_embeddings = all_embeddings.flatten()
|
| 236 |
+
print(f"Total values: {len(flattened_embeddings)} ({n_embd_count} embeddings × {n_embd} dimensions)")
|
| 237 |
+
print("")
|
| 238 |
+
|
| 239 |
+
save_output_data(flattened_embeddings, token_ids, prompt_text, model_name, type_suffix="-embeddings")
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
if __name__ == "__main__":
|
| 243 |
+
main()
|
examples/model-conversion/scripts/utils/__init__.py
ADDED
|
File without changes
|
examples/model-conversion/scripts/utils/check-nmse.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import sys
|
| 5 |
+
import os
|
| 6 |
+
import argparse
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from common import get_model_name_from_env_path # type: ignore[import-not-found, ty:unresolved-import]
|
| 9 |
+
|
| 10 |
+
def calculate_nmse(reference, test):
|
| 11 |
+
mse = np.mean((test - reference) ** 2)
|
| 12 |
+
ref_var = np.var(reference)
|
| 13 |
+
if ref_var == 0:
|
| 14 |
+
nmse = float('inf') if mse > 0 else 0.0
|
| 15 |
+
return mse, mse, ref_var
|
| 16 |
+
|
| 17 |
+
nmse = mse / ref_var
|
| 18 |
+
|
| 19 |
+
return nmse, mse, ref_var
|
| 20 |
+
|
| 21 |
+
def load_logits(file_path):
|
| 22 |
+
if not os.path.exists(file_path):
|
| 23 |
+
raise FileNotFoundError(f"File not found: {file_path}")
|
| 24 |
+
|
| 25 |
+
if file_path.suffix == '.npy':
|
| 26 |
+
return np.load(file_path)
|
| 27 |
+
elif file_path.suffix == '.bin':
|
| 28 |
+
return np.fromfile(file_path, dtype=np.float32)
|
| 29 |
+
else:
|
| 30 |
+
# Try to load as text file
|
| 31 |
+
try:
|
| 32 |
+
# If it has index format "0: value", extract just values
|
| 33 |
+
data = []
|
| 34 |
+
with open(file_path, 'r') as f:
|
| 35 |
+
for line in f:
|
| 36 |
+
if ':' in line:
|
| 37 |
+
# Format: "index: value"
|
| 38 |
+
value = float(line.split(':')[1].strip())
|
| 39 |
+
else:
|
| 40 |
+
# Just the value
|
| 41 |
+
value = float(line.strip())
|
| 42 |
+
data.append(value)
|
| 43 |
+
return np.array(data, dtype=np.float32)
|
| 44 |
+
except:
|
| 45 |
+
return np.loadtxt(file_path, dtype=np.float32)
|
| 46 |
+
|
| 47 |
+
def interpret_nmse(nmse):
|
| 48 |
+
"""Provide interpretation of NMSE value"""
|
| 49 |
+
if nmse == 0:
|
| 50 |
+
return "Perfect match", "🎉"
|
| 51 |
+
elif nmse < 1e-6:
|
| 52 |
+
return "Essentially identical", "✅"
|
| 53 |
+
elif nmse < 1e-4:
|
| 54 |
+
return "Excellent match", "✅"
|
| 55 |
+
elif nmse < 1e-3:
|
| 56 |
+
return "Very good match", "👍"
|
| 57 |
+
elif nmse < 1e-2:
|
| 58 |
+
return "Good match", "👍"
|
| 59 |
+
elif nmse < 0.1:
|
| 60 |
+
return "Acceptable match", "⚠️"
|
| 61 |
+
elif nmse < 1.0:
|
| 62 |
+
return "Poor match", "❌"
|
| 63 |
+
else:
|
| 64 |
+
return "Very poor match (worse than noise)", "❌"
|
| 65 |
+
|
| 66 |
+
def main():
|
| 67 |
+
parser = argparse.ArgumentParser(description='Validate model logits')
|
| 68 |
+
parser.add_argument('-m', '--model-path', required=True, help='Path to the model directory')
|
| 69 |
+
args = parser.parse_args()
|
| 70 |
+
|
| 71 |
+
model_name = get_model_name_from_env_path('MODEL_PATH')
|
| 72 |
+
data_dir = Path("data")
|
| 73 |
+
|
| 74 |
+
pytorch_file = data_dir / f"pytorch-{model_name}.bin"
|
| 75 |
+
|
| 76 |
+
llamacpp_model_name = get_model_name_from_env_path('CONVERTED_MODEL')
|
| 77 |
+
llamacpp_file = data_dir / f"llamacpp-{llamacpp_model_name}.bin"
|
| 78 |
+
|
| 79 |
+
print(f"Model name: {model_name}")
|
| 80 |
+
print(f"PyTorch logits file: {pytorch_file}")
|
| 81 |
+
print(f"llama.cpp logits file: {llamacpp_file}")
|
| 82 |
+
|
| 83 |
+
reference_file = pytorch_file
|
| 84 |
+
test_file = llamacpp_file
|
| 85 |
+
|
| 86 |
+
print("📊 NMSE Check for Model Comparison")
|
| 87 |
+
print("=" * 50)
|
| 88 |
+
print(f"Reference (ground truth): {reference_file}")
|
| 89 |
+
print(f"Test (to evaluate): {test_file}")
|
| 90 |
+
print()
|
| 91 |
+
|
| 92 |
+
try:
|
| 93 |
+
print("Loading reference logits...")
|
| 94 |
+
reference = load_logits(reference_file)
|
| 95 |
+
print(f" Shape: {reference.shape}, Type: {reference.dtype}")
|
| 96 |
+
|
| 97 |
+
print("Loading test logits...")
|
| 98 |
+
test = load_logits(test_file)
|
| 99 |
+
print(f" Shape: {test.shape}, Type: {test.dtype}")
|
| 100 |
+
|
| 101 |
+
# Check shapes match
|
| 102 |
+
if reference.shape != test.shape:
|
| 103 |
+
print(f"\n❌ Error: Shape mismatch!")
|
| 104 |
+
print(f" Reference: {reference.shape}")
|
| 105 |
+
print(f" Test: {test.shape}")
|
| 106 |
+
sys.exit(1)
|
| 107 |
+
|
| 108 |
+
print(f"\n✅ Shapes match: {reference.shape}")
|
| 109 |
+
|
| 110 |
+
nmse, mse, ref_var = calculate_nmse(reference, test)
|
| 111 |
+
|
| 112 |
+
# Additional metrics
|
| 113 |
+
max_abs_error = np.max(np.abs(test - reference))
|
| 114 |
+
mean_abs_error = np.mean(np.abs(test - reference))
|
| 115 |
+
|
| 116 |
+
# Results
|
| 117 |
+
print(f"\n📈 METRICS")
|
| 118 |
+
print("=" * 30)
|
| 119 |
+
print(f"MSE (Mean Squared Error): {mse:.6e}")
|
| 120 |
+
print(f"Reference Variance: {ref_var:.6e}")
|
| 121 |
+
print(f"NMSE: {nmse:.6e}")
|
| 122 |
+
print(f"Max Absolute Error: {max_abs_error:.6f}")
|
| 123 |
+
print(f"Mean Absolute Error: {mean_abs_error:.6f}")
|
| 124 |
+
|
| 125 |
+
# NMSE in dB (common in signal processing)
|
| 126 |
+
if nmse > 0:
|
| 127 |
+
nmse_db = 10 * np.log10(nmse)
|
| 128 |
+
print(f"NMSE (dB): {nmse_db:.2f} dB")
|
| 129 |
+
|
| 130 |
+
# Interpretation
|
| 131 |
+
interpretation, emoji = interpret_nmse(nmse)
|
| 132 |
+
print(f"\n🎯 INTERPRETATION")
|
| 133 |
+
print("=" * 30)
|
| 134 |
+
print(f"{emoji} {interpretation}")
|
| 135 |
+
|
| 136 |
+
# Detailed guidance
|
| 137 |
+
print(f"\n📋 GUIDANCE")
|
| 138 |
+
print("=" * 30)
|
| 139 |
+
if nmse < 1e-3:
|
| 140 |
+
print("✅ EXCELLENT: Your GGML conversion is working very well!")
|
| 141 |
+
print(" The differences are negligible for practical use.")
|
| 142 |
+
elif nmse < 1e-2:
|
| 143 |
+
print("👍 GOOD: Your GGML conversion is working well.")
|
| 144 |
+
print(" Small differences are likely due to precision/quantization.")
|
| 145 |
+
elif nmse < 0.1:
|
| 146 |
+
print("⚠️ ACCEPTABLE: Conversion is working but with some differences.")
|
| 147 |
+
print(" Check if you're using quantization (Q4, Q8, etc.)")
|
| 148 |
+
print(" Test generation quality to see if it's acceptable.")
|
| 149 |
+
else:
|
| 150 |
+
print("❌ PROBLEMATIC: Large differences detected.")
|
| 151 |
+
print(" Check your conversion process for potential issues.")
|
| 152 |
+
print(" Verify you're using the same model weights.")
|
| 153 |
+
|
| 154 |
+
# NMSE benchmarks
|
| 155 |
+
print(f"\n📚 NMSE BENCHMARKS")
|
| 156 |
+
print("=" * 30)
|
| 157 |
+
print("< 1e-6: Essentially identical")
|
| 158 |
+
print("< 1e-4: Excellent (typical for good conversions)")
|
| 159 |
+
print("< 1e-3: Very good")
|
| 160 |
+
print("< 1e-2: Good (acceptable for most use cases)")
|
| 161 |
+
print("< 0.1: Acceptable (may need verification)")
|
| 162 |
+
print("> 1.0: Poor (worse than random)")
|
| 163 |
+
|
| 164 |
+
# Exit code based on NMSE
|
| 165 |
+
if nmse < 1e-2:
|
| 166 |
+
print(f"\n✅ RESULT: PASS (NMSE = {nmse:.2e})")
|
| 167 |
+
sys.exit(0)
|
| 168 |
+
else:
|
| 169 |
+
print(f"\n❌ RESULT: NEEDS REVIEW (NMSE = {nmse:.2e})")
|
| 170 |
+
sys.exit(1)
|
| 171 |
+
|
| 172 |
+
except Exception as e:
|
| 173 |
+
print(f"❌ Error: {e}")
|
| 174 |
+
sys.exit(1)
|
| 175 |
+
|
| 176 |
+
if __name__ == "__main__":
|
| 177 |
+
main()
|
examples/model-conversion/scripts/utils/common.py
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
import torch
|
| 6 |
+
import transformers
|
| 7 |
+
import json
|
| 8 |
+
import textwrap
|
| 9 |
+
import numpy as np
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def get_model_name_from_env_path(env_path_name):
|
| 14 |
+
model_path = os.getenv(env_path_name)
|
| 15 |
+
if not model_path:
|
| 16 |
+
print(f"Error: {env_path_name} environment variable not set")
|
| 17 |
+
sys.exit(1)
|
| 18 |
+
|
| 19 |
+
if not os.path.exists(model_path):
|
| 20 |
+
print(f"Error: Model file not found: {model_path}")
|
| 21 |
+
sys.exit(1)
|
| 22 |
+
|
| 23 |
+
name = os.path.basename(os.path.normpath(model_path))
|
| 24 |
+
if name.endswith(".gguf"):
|
| 25 |
+
name = name[:-5]
|
| 26 |
+
|
| 27 |
+
return name
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def summarize(tensor: torch.Tensor, name: str, max_seq: int = 3, max_vals: int = 3):
|
| 31 |
+
"""
|
| 32 |
+
Print a tensor in llama.cpp debug style.
|
| 33 |
+
|
| 34 |
+
Supports:
|
| 35 |
+
- 2D tensors (seq, hidden)
|
| 36 |
+
- 3D tensors (batch, seq, hidden)
|
| 37 |
+
- 4D tensors (batch, seq, heads, dim_per_head) via flattening heads × dim_per_head
|
| 38 |
+
|
| 39 |
+
Shows first and last max_vals of each vector per sequence position.
|
| 40 |
+
"""
|
| 41 |
+
t = tensor.detach().to(torch.float32).cpu()
|
| 42 |
+
|
| 43 |
+
# Determine dimensions
|
| 44 |
+
if t.ndim == 3:
|
| 45 |
+
_, s, _ = t.shape
|
| 46 |
+
elif t.ndim == 2:
|
| 47 |
+
_, s = 1, t.shape[0]
|
| 48 |
+
t = t.unsqueeze(0)
|
| 49 |
+
elif t.ndim == 4:
|
| 50 |
+
_, s, _, _ = t.shape
|
| 51 |
+
else:
|
| 52 |
+
print(f"Skipping tensor due to unsupported dimensions: {t.ndim}")
|
| 53 |
+
return
|
| 54 |
+
|
| 55 |
+
ten_shape = t.shape
|
| 56 |
+
|
| 57 |
+
print(f"ggml_debug: {name} = (f32) ... = {{{ten_shape}}}")
|
| 58 |
+
print(" [")
|
| 59 |
+
print(" [")
|
| 60 |
+
|
| 61 |
+
# Determine indices for first and last sequences
|
| 62 |
+
first_indices = list(range(min(s, max_seq)))
|
| 63 |
+
last_indices = list(range(max(0, s - max_seq), s))
|
| 64 |
+
|
| 65 |
+
# Check if there's an overlap between first and last indices or if we're at the edge case of s = 2 * max_seq
|
| 66 |
+
has_overlap = bool(set(first_indices) & set(last_indices)) or (max_seq * 2 == s)
|
| 67 |
+
|
| 68 |
+
# Combine indices
|
| 69 |
+
if has_overlap:
|
| 70 |
+
# If there's overlap, just use the combined unique indices
|
| 71 |
+
indices = sorted(list(set(first_indices + last_indices)))
|
| 72 |
+
separator_index = None
|
| 73 |
+
else:
|
| 74 |
+
# If no overlap, we'll add a separator between first and last sequences
|
| 75 |
+
indices = first_indices + last_indices
|
| 76 |
+
separator_index = len(first_indices)
|
| 77 |
+
|
| 78 |
+
for i, si in enumerate(indices):
|
| 79 |
+
# Add separator if needed
|
| 80 |
+
if separator_index is not None and i == separator_index:
|
| 81 |
+
print(" ...")
|
| 82 |
+
|
| 83 |
+
# Extract appropriate slice
|
| 84 |
+
vec = t[0, si]
|
| 85 |
+
if vec.ndim == 2: # 4D case: flatten heads × dim_per_head
|
| 86 |
+
flat = vec.flatten().tolist()
|
| 87 |
+
else: # 2D or 3D case
|
| 88 |
+
flat = vec.tolist()
|
| 89 |
+
|
| 90 |
+
# First and last slices
|
| 91 |
+
first = flat[:max_vals]
|
| 92 |
+
last = flat[-max_vals:] if len(flat) >= max_vals else flat
|
| 93 |
+
first_str = ", ".join(f"{v:12.4f}" for v in first)
|
| 94 |
+
last_str = ", ".join(f"{v:12.4f}" for v in last)
|
| 95 |
+
|
| 96 |
+
print(f" [{first_str}, ..., {last_str}]")
|
| 97 |
+
|
| 98 |
+
print(" ],")
|
| 99 |
+
print(" ]")
|
| 100 |
+
print(f" sum = {t.sum().item():.6f}\n")
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def debug_hook(name):
|
| 104 |
+
def fn(_m, input, output):
|
| 105 |
+
if isinstance(input, torch.Tensor):
|
| 106 |
+
summarize(input, name + "_in")
|
| 107 |
+
elif isinstance(input, (tuple, list)) and len(input) > 0 and isinstance(input[0], torch.Tensor):
|
| 108 |
+
summarize(input[0], name + "_in")
|
| 109 |
+
if isinstance(output, torch.Tensor):
|
| 110 |
+
summarize(output, name + "_out")
|
| 111 |
+
elif isinstance(output, (tuple, list)) and len(output) > 0 and isinstance(output[0], torch.Tensor):
|
| 112 |
+
summarize(output[0], name + "_out")
|
| 113 |
+
|
| 114 |
+
return fn
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def setup_rope_debug(model_module_path: str, function_name: str = "apply_rotary_pos_emb"):
|
| 118 |
+
"""
|
| 119 |
+
Apply monkey patch to dump RoPE activations for debugging.
|
| 120 |
+
|
| 121 |
+
Args:
|
| 122 |
+
model_module_path: Path to the model module (e.g., "transformers.models.apertus.modeling_apertus")
|
| 123 |
+
function_name: Name of the RoPE function to patch (default: "apply_rotary_pos_emb")
|
| 124 |
+
|
| 125 |
+
Example:
|
| 126 |
+
from utils.common import setup_rope_debug
|
| 127 |
+
setup_rope_debug("transformers.models.apertus.modeling_apertus")
|
| 128 |
+
"""
|
| 129 |
+
import importlib
|
| 130 |
+
|
| 131 |
+
# Import the module and get the original function
|
| 132 |
+
module = importlib.import_module(model_module_path)
|
| 133 |
+
orig_rope = getattr(module, function_name)
|
| 134 |
+
|
| 135 |
+
# Set torch print options for better debugging
|
| 136 |
+
torch.set_printoptions(threshold=float('inf'))
|
| 137 |
+
torch.set_printoptions(precision=6, sci_mode=False)
|
| 138 |
+
|
| 139 |
+
def debug_rope(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 140 |
+
# log inputs
|
| 141 |
+
summarize(q, "RoPE.q_in")
|
| 142 |
+
summarize(k, "RoPE.k_in")
|
| 143 |
+
|
| 144 |
+
# call original
|
| 145 |
+
q_out, k_out = orig_rope(q, k, cos, sin, position_ids, unsqueeze_dim)
|
| 146 |
+
|
| 147 |
+
# log outputs
|
| 148 |
+
summarize(q_out, "RoPE.q_out")
|
| 149 |
+
summarize(k_out, "RoPE.k_out")
|
| 150 |
+
|
| 151 |
+
return q_out, k_out
|
| 152 |
+
|
| 153 |
+
# Patch it
|
| 154 |
+
setattr(module, function_name, debug_rope)
|
| 155 |
+
print(f"RoPE debug patching applied to {model_module_path}.{function_name}")
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def save_output_data(data, tokens, prompt, model_name, type_suffix="", output_dir="data"):
|
| 159 |
+
"""
|
| 160 |
+
Save output data (logits/embeddings), tokens, and prompt to files.
|
| 161 |
+
|
| 162 |
+
Args:
|
| 163 |
+
data: numpy array of floats (logits or embeddings)
|
| 164 |
+
tokens: list or array of token IDs
|
| 165 |
+
prompt: string containing the input prompt
|
| 166 |
+
model_name: name of the model
|
| 167 |
+
type_suffix: optional suffix like "-embeddings" (default: "")
|
| 168 |
+
output_dir: directory to save files (default: "data")
|
| 169 |
+
|
| 170 |
+
Creates the following files in output_dir:
|
| 171 |
+
- pytorch-{model_name}{type_suffix}.bin
|
| 172 |
+
- pytorch-{model_name}{type_suffix}.txt
|
| 173 |
+
- pytorch-{model_name}{type_suffix}-prompt.txt
|
| 174 |
+
- pytorch-{model_name}{type_suffix}-tokens.bin
|
| 175 |
+
"""
|
| 176 |
+
data_dir = Path(output_dir)
|
| 177 |
+
data_dir.mkdir(exist_ok=True)
|
| 178 |
+
base_path = data_dir / f"pytorch-{model_name}{type_suffix}"
|
| 179 |
+
|
| 180 |
+
# Convert and flatten logits/embeddings
|
| 181 |
+
data = data.cpu().numpy() if isinstance(data, torch.Tensor) else np.asarray(data)
|
| 182 |
+
data = data.flatten() if data.ndim > 1 else data
|
| 183 |
+
|
| 184 |
+
# Save logits/embedding files
|
| 185 |
+
data.astype(np.float32).tofile(f"{base_path}.bin")
|
| 186 |
+
print(f"Data saved to {base_path}.bin")
|
| 187 |
+
|
| 188 |
+
with open(f"{base_path}.txt", "w") as f:
|
| 189 |
+
f.writelines(f"{i}: {value:.6f}\n" for i, value in enumerate(data))
|
| 190 |
+
print(f"Data saved to {base_path}.txt")
|
| 191 |
+
|
| 192 |
+
# Convert and flatten tokens
|
| 193 |
+
tokens = tokens.cpu().numpy() if isinstance(tokens, torch.Tensor) else np.asarray(tokens)
|
| 194 |
+
tokens = tokens.flatten() if tokens.ndim > 1 else tokens
|
| 195 |
+
|
| 196 |
+
# Save token binary file
|
| 197 |
+
tokens.astype(np.int32).tofile(f"{base_path}-tokens.bin")
|
| 198 |
+
print(f"Tokens saved to {base_path}-tokens.bin")
|
| 199 |
+
|
| 200 |
+
# Save prompt file
|
| 201 |
+
with open(f"{base_path}-prompt.txt", "w") as f:
|
| 202 |
+
f.write(f"prompt: {prompt}\n")
|
| 203 |
+
f.write(f"n_tokens: {len(tokens)}\n")
|
| 204 |
+
f.write(f"token ids: {', '.join(str(int(tid)) for tid in tokens)}\n")
|
| 205 |
+
print(f"Prompt saved to {base_path}-prompt.txt")
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def compare_tokens(original, converted, type_suffix="", output_dir="data"):
|
| 209 |
+
data_dir = Path(output_dir)
|
| 210 |
+
|
| 211 |
+
# Read tokens from both models
|
| 212 |
+
tokens1_file = data_dir / f"{original}{type_suffix}-tokens.bin"
|
| 213 |
+
tokens2_file = data_dir / f"{converted}{type_suffix}-tokens.bin"
|
| 214 |
+
|
| 215 |
+
if not tokens1_file.exists():
|
| 216 |
+
print(f"Error: Token file not found: {tokens1_file}")
|
| 217 |
+
return False
|
| 218 |
+
|
| 219 |
+
if not tokens2_file.exists():
|
| 220 |
+
print(f"Error: Token file not found: {tokens2_file}")
|
| 221 |
+
return False
|
| 222 |
+
|
| 223 |
+
tokens1 = np.fromfile(tokens1_file, dtype=np.int32)
|
| 224 |
+
tokens2 = np.fromfile(tokens2_file, dtype=np.int32)
|
| 225 |
+
|
| 226 |
+
print(f"\nComparing tokens between:")
|
| 227 |
+
print(f" Original : {original} ({len(tokens1)} tokens)")
|
| 228 |
+
print(f" Converted: {converted} ({len(tokens2)} tokens)")
|
| 229 |
+
|
| 230 |
+
if len(tokens1) != len(tokens2):
|
| 231 |
+
print(f"\n❌ Token count mismatch: {len(tokens1)} vs {len(tokens2)}")
|
| 232 |
+
return False
|
| 233 |
+
|
| 234 |
+
if np.array_equal(tokens1, tokens2):
|
| 235 |
+
print(f"\n✅ All {len(tokens1)} tokens match!")
|
| 236 |
+
return True
|
| 237 |
+
|
| 238 |
+
mismatches = np.where(tokens1 != tokens2)[0]
|
| 239 |
+
print(f"\n❌ Found {len(mismatches)} mismatched tokens:")
|
| 240 |
+
|
| 241 |
+
num_to_show = min(len(mismatches), 10)
|
| 242 |
+
for idx in mismatches[:num_to_show]:
|
| 243 |
+
print(f" Position {idx}: {tokens1[idx]} vs {tokens2[idx]}")
|
| 244 |
+
|
| 245 |
+
if len(mismatches) > num_to_show:
|
| 246 |
+
print(f" ... and {len(mismatches) - num_to_show} more mismatches")
|
| 247 |
+
|
| 248 |
+
return False
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def show_version_warning(current_version, model_version):
|
| 252 |
+
if not model_version:
|
| 253 |
+
return False
|
| 254 |
+
|
| 255 |
+
try:
|
| 256 |
+
from packaging.version import parse, InvalidVersion
|
| 257 |
+
try:
|
| 258 |
+
return parse(current_version) < parse(model_version)
|
| 259 |
+
except InvalidVersion:
|
| 260 |
+
return current_version != model_version
|
| 261 |
+
except ImportError:
|
| 262 |
+
return current_version != model_version
|
| 263 |
+
|
| 264 |
+
def get_model_transformers_version(model_path):
|
| 265 |
+
if not model_path:
|
| 266 |
+
return None
|
| 267 |
+
|
| 268 |
+
config_path = Path(model_path) / "config.json"
|
| 269 |
+
if not config_path.is_file():
|
| 270 |
+
return None
|
| 271 |
+
|
| 272 |
+
try:
|
| 273 |
+
with open(config_path, "r", encoding="utf-8") as f:
|
| 274 |
+
config = json.load(f)
|
| 275 |
+
return config.get("transformers_version")
|
| 276 |
+
except (IOError, json.JSONDecodeError) as e:
|
| 277 |
+
print(f"Warning: Could not read or parse {config_path}: {e}", file=sys.stderr)
|
| 278 |
+
return None
|
| 279 |
+
|
| 280 |
+
def exit_with_warning(message, model_path):
|
| 281 |
+
print(message)
|
| 282 |
+
|
| 283 |
+
if model_path and transformers is not None:
|
| 284 |
+
model_transformers_version = get_model_transformers_version(model_path)
|
| 285 |
+
transformers_version = transformers.__version__
|
| 286 |
+
if show_version_warning(transformers_version, model_transformers_version):
|
| 287 |
+
warning_message = f"""
|
| 288 |
+
=====================================================================
|
| 289 |
+
Verification failure might be due to a transformers version mismatch:
|
| 290 |
+
|
| 291 |
+
Current transformers version: {transformers_version}
|
| 292 |
+
Model's required version : {model_transformers_version}
|
| 293 |
+
|
| 294 |
+
Consider installing the version specified by the model's config:
|
| 295 |
+
pip install transformers=={model_transformers_version}
|
| 296 |
+
=====================================================================
|
| 297 |
+
"""
|
| 298 |
+
print(textwrap.dedent(warning_message))
|
| 299 |
+
sys.exit(1)
|
examples/model-conversion/scripts/utils/compare_tokens.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import sys
|
| 5 |
+
from common import compare_tokens # type: ignore[import-not-found, ty:unresolved-import]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def parse_arguments():
|
| 9 |
+
parser = argparse.ArgumentParser(
|
| 10 |
+
description='Compare tokens between two models',
|
| 11 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 12 |
+
epilog="""
|
| 13 |
+
Examples:
|
| 14 |
+
%(prog)s pytorch-gemma-3-270m-it llamacpp-gemma-3-270m-it-bf16
|
| 15 |
+
"""
|
| 16 |
+
)
|
| 17 |
+
parser.add_argument(
|
| 18 |
+
'original',
|
| 19 |
+
help='Original model name'
|
| 20 |
+
)
|
| 21 |
+
parser.add_argument(
|
| 22 |
+
'converted',
|
| 23 |
+
help='Converted model name'
|
| 24 |
+
)
|
| 25 |
+
parser.add_argument(
|
| 26 |
+
'-s', '--suffix',
|
| 27 |
+
default='',
|
| 28 |
+
help='Type suffix (e.g., "-embeddings")'
|
| 29 |
+
)
|
| 30 |
+
parser.add_argument(
|
| 31 |
+
'-d', '--data-dir',
|
| 32 |
+
default='data',
|
| 33 |
+
help='Directory containing token files (default: data)'
|
| 34 |
+
)
|
| 35 |
+
parser.add_argument(
|
| 36 |
+
'-v', '--verbose',
|
| 37 |
+
action='store_true',
|
| 38 |
+
help='Print prompts from both models'
|
| 39 |
+
)
|
| 40 |
+
return parser.parse_args()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def main():
|
| 44 |
+
args = parse_arguments()
|
| 45 |
+
|
| 46 |
+
if args.verbose:
|
| 47 |
+
from pathlib import Path
|
| 48 |
+
data_dir = Path(args.data_dir)
|
| 49 |
+
|
| 50 |
+
prompt1_file = data_dir / f"{args.original}{args.suffix}-prompt.txt"
|
| 51 |
+
prompt2_file = data_dir / f"{args.converted}{args.suffix}-prompt.txt"
|
| 52 |
+
|
| 53 |
+
if prompt1_file.exists():
|
| 54 |
+
print(f"\nOriginal model prompt ({args.original}):")
|
| 55 |
+
print(f" {prompt1_file.read_text().strip()}")
|
| 56 |
+
|
| 57 |
+
if prompt2_file.exists():
|
| 58 |
+
print(f"\nConverted model prompt ({args.converted}):")
|
| 59 |
+
print(f" {prompt2_file.read_text().strip()}")
|
| 60 |
+
|
| 61 |
+
print()
|
| 62 |
+
|
| 63 |
+
result = compare_tokens(
|
| 64 |
+
args.original,
|
| 65 |
+
args.converted,
|
| 66 |
+
type_suffix=args.suffix,
|
| 67 |
+
output_dir=args.data_dir
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
# Enable the script to be used in shell scripts so that they can check
|
| 71 |
+
# the exit code for success/failure.
|
| 72 |
+
sys.exit(0 if result else 1)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
if __name__ == "__main__":
|
| 76 |
+
main()
|
examples/model-conversion/scripts/utils/create-collection-add-model.sh
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
#!/usr/bin/env bash
|
| 3 |
+
|
| 4 |
+
COLLECTION_SLUG=$(python ./create_collection.py --return-slug)
|
| 5 |
+
echo "Created collection: $COLLECTION_SLUG"
|
| 6 |
+
|
| 7 |
+
# Use it in the next command
|
| 8 |
+
python add_model_to_collection.py "$COLLECTION_SLUG" "username/my-model"
|
examples/model-conversion/scripts/utils/curl-embedding-server.sh
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
curl --request POST \
|
| 3 |
+
--url http://localhost:8080/embedding \
|
| 4 |
+
--header "Content-Type: application/json" \
|
| 5 |
+
--data '{"input": "Hello world today"}' \
|
| 6 |
+
--silent
|
examples/model-conversion/scripts/utils/hf-add-model-to-collection.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
from huggingface_hub import HfApi
|
| 4 |
+
import argparse
|
| 5 |
+
import sys
|
| 6 |
+
|
| 7 |
+
def add_model_to_collection(collection_slug, model_id, note=""):
|
| 8 |
+
"""
|
| 9 |
+
Add a model to an existing collection
|
| 10 |
+
|
| 11 |
+
Args:
|
| 12 |
+
collection_slug: The slug of the collection (e.g., "username/collection-name-12345")
|
| 13 |
+
model_id: The model repository ID (e.g., "username/model-name")
|
| 14 |
+
note: Optional note about the model
|
| 15 |
+
|
| 16 |
+
Returns:
|
| 17 |
+
True if successful, False if failed
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
# Initialize API
|
| 21 |
+
api = HfApi()
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
user_info = api.whoami()
|
| 25 |
+
print(f"✅ Authenticated as: {user_info['name']}")
|
| 26 |
+
|
| 27 |
+
# Verify the model exists
|
| 28 |
+
print(f"🔍 Checking if model exists: {model_id}")
|
| 29 |
+
try:
|
| 30 |
+
model_info = api.model_info(model_id)
|
| 31 |
+
except Exception as e:
|
| 32 |
+
print(f"❌ Model not found or not accessible: {model_id}")
|
| 33 |
+
print(f"Error: {e}")
|
| 34 |
+
return False
|
| 35 |
+
|
| 36 |
+
print(f"📚 Adding model to collection...")
|
| 37 |
+
api.add_collection_item(
|
| 38 |
+
collection_slug=collection_slug,
|
| 39 |
+
item_id=model_id,
|
| 40 |
+
item_type="model",
|
| 41 |
+
note=note
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
print(f"✅ Model added to collection successfully!")
|
| 45 |
+
print(f"🔗 Collection URL: https://huggingface.co/collections/{collection_slug}")
|
| 46 |
+
|
| 47 |
+
return True
|
| 48 |
+
|
| 49 |
+
except Exception as e:
|
| 50 |
+
print(f"❌ Error adding model to collection: {e}")
|
| 51 |
+
return False
|
| 52 |
+
|
| 53 |
+
def main():
|
| 54 |
+
# This script requires that the environment variable HF_TOKEN is set with your
|
| 55 |
+
# Hugging Face API token.
|
| 56 |
+
api = HfApi()
|
| 57 |
+
|
| 58 |
+
parser = argparse.ArgumentParser(description='Add model to a Huggingface Collection')
|
| 59 |
+
parser.add_argument('--collection', '-c', help='The collection slug username/collection-hash', required=True)
|
| 60 |
+
parser.add_argument('--model', '-m', help='The model to add to the Collection', required=True)
|
| 61 |
+
parser.add_argument('--note', '-n', help='An optional note/description', required=False)
|
| 62 |
+
args = parser.parse_args()
|
| 63 |
+
|
| 64 |
+
collection = args.collection
|
| 65 |
+
model = args.model
|
| 66 |
+
note = args.note
|
| 67 |
+
|
| 68 |
+
success = add_model_to_collection(
|
| 69 |
+
collection_slug=collection,
|
| 70 |
+
model_id=model,
|
| 71 |
+
note=note
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
if success:
|
| 75 |
+
print("\n🎉 Model added successfully!")
|
| 76 |
+
else:
|
| 77 |
+
print("\n❌ Failed to add model to collection")
|
| 78 |
+
sys.exit(1)
|
| 79 |
+
if __name__ == "__main__":
|
| 80 |
+
main()
|
examples/model-conversion/scripts/utils/hf-create-collection.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
from huggingface_hub import HfApi
|
| 4 |
+
import argparse
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def create_collection(title, description, private=False, namespace=None, return_slug=False):
|
| 10 |
+
"""
|
| 11 |
+
Create a new collection on Hugging Face
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
title: Collection title
|
| 15 |
+
description: Collection description
|
| 16 |
+
private: Whether the collection should be private (default: False)
|
| 17 |
+
namespace: Optional namespace (defaults to your username)
|
| 18 |
+
|
| 19 |
+
Returns:
|
| 20 |
+
Collection object if successful, None if failed
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
# Check if HF_TOKEN is available
|
| 24 |
+
token = os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACE_HUB_TOKEN")
|
| 25 |
+
if not token:
|
| 26 |
+
print("❌ No HF_TOKEN or HUGGINGFACE_HUB_TOKEN found in environment variables")
|
| 27 |
+
print("Please set your Hugging Face token as an environment variable")
|
| 28 |
+
return None
|
| 29 |
+
|
| 30 |
+
# Initialize API
|
| 31 |
+
api = HfApi()
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
# Test authentication first
|
| 35 |
+
user_info = api.whoami()
|
| 36 |
+
if not return_slug:
|
| 37 |
+
print(f"✅ Authenticated as: {user_info['name']}")
|
| 38 |
+
|
| 39 |
+
# Create the collection
|
| 40 |
+
if not return_slug:
|
| 41 |
+
print(f"📚 Creating collection: '{title}'...")
|
| 42 |
+
collection = api.create_collection(
|
| 43 |
+
title=title,
|
| 44 |
+
description=description,
|
| 45 |
+
private=private,
|
| 46 |
+
namespace=namespace
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
if not return_slug:
|
| 50 |
+
print(f"✅ Collection created successfully!")
|
| 51 |
+
print(f"📋 Collection slug: {collection.slug}")
|
| 52 |
+
print(f"🔗 Collection URL: https://huggingface.co/collections/{collection.slug}")
|
| 53 |
+
|
| 54 |
+
return collection
|
| 55 |
+
|
| 56 |
+
except Exception as e:
|
| 57 |
+
print(f"❌ Error creating collection: {e}")
|
| 58 |
+
return None
|
| 59 |
+
|
| 60 |
+
def main():
|
| 61 |
+
# This script requires that the environment variable HF_TOKEN is set with your
|
| 62 |
+
# Hugging Face API token.
|
| 63 |
+
api = HfApi()
|
| 64 |
+
|
| 65 |
+
parser = argparse.ArgumentParser(description='Create a Huggingface Collection')
|
| 66 |
+
parser.add_argument('--name', '-n', help='The name/title of the Collection', required=True)
|
| 67 |
+
parser.add_argument('--description', '-d', help='The description for the Collection', required=True)
|
| 68 |
+
parser.add_argument('--namespace', '-ns', help='The namespace to add the Collection to', required=True)
|
| 69 |
+
parser.add_argument('--private', '-p', help='Create a private Collection', action='store_true') # Fixed
|
| 70 |
+
parser.add_argument('--return-slug', '-s', help='Only output the collection slug', action='store_true') # Fixed
|
| 71 |
+
|
| 72 |
+
args = parser.parse_args()
|
| 73 |
+
|
| 74 |
+
name = args.name
|
| 75 |
+
description = args.description
|
| 76 |
+
private = args.private
|
| 77 |
+
namespace = args.namespace
|
| 78 |
+
return_slug = args.return_slug
|
| 79 |
+
|
| 80 |
+
if not return_slug:
|
| 81 |
+
print("🚀 Creating Hugging Face Collection")
|
| 82 |
+
print(f"Title: {name}")
|
| 83 |
+
print(f"Description: {description}")
|
| 84 |
+
print(f"Namespace: {namespace}")
|
| 85 |
+
print(f"Private: {private}")
|
| 86 |
+
|
| 87 |
+
collection = create_collection(
|
| 88 |
+
title=name,
|
| 89 |
+
description=description,
|
| 90 |
+
private=private,
|
| 91 |
+
namespace=namespace,
|
| 92 |
+
return_slug=return_slug
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
if collection:
|
| 96 |
+
if return_slug:
|
| 97 |
+
print(collection.slug)
|
| 98 |
+
else:
|
| 99 |
+
print("\n🎉 Collection created successfully!")
|
| 100 |
+
print(f"Use this slug to add models: {collection.slug}")
|
| 101 |
+
else:
|
| 102 |
+
print("\n❌ Failed to create collection")
|
| 103 |
+
sys.exit(1)
|
| 104 |
+
|
| 105 |
+
if __name__ == "__main__":
|
| 106 |
+
main()
|
examples/model-conversion/scripts/utils/hf-create-model.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
from huggingface_hub import HfApi
|
| 4 |
+
import argparse
|
| 5 |
+
|
| 6 |
+
# This script requires that the environment variable HF_TOKEN is set with your
|
| 7 |
+
# Hugging Face API token.
|
| 8 |
+
api = HfApi()
|
| 9 |
+
|
| 10 |
+
def load_template_and_substitute(template_path, **kwargs):
|
| 11 |
+
try:
|
| 12 |
+
with open(template_path, 'r', encoding='utf-8') as f:
|
| 13 |
+
template_content = f.read()
|
| 14 |
+
|
| 15 |
+
return template_content.format(**kwargs)
|
| 16 |
+
except FileNotFoundError:
|
| 17 |
+
print(f"Template file '{template_path}' not found!")
|
| 18 |
+
return None
|
| 19 |
+
except KeyError as e:
|
| 20 |
+
print(f"Missing template variable: {e}")
|
| 21 |
+
return None
|
| 22 |
+
|
| 23 |
+
parser = argparse.ArgumentParser(description='Create a new Hugging Face model repository')
|
| 24 |
+
parser.add_argument('--model-name', '-m', help='Name for the model', required=True)
|
| 25 |
+
parser.add_argument('--namespace', '-ns', help='Namespace to add the model to', required=True)
|
| 26 |
+
parser.add_argument('--org-base-model', '-b', help='Original Base model name', default="")
|
| 27 |
+
parser.add_argument('--no-card', action='store_true', help='Skip creating model card')
|
| 28 |
+
parser.add_argument('--private', '-p', action='store_true', help='Create private model')
|
| 29 |
+
parser.add_argument('--embedding', '-e', action='store_true', help='Use embedding model card template')
|
| 30 |
+
parser.add_argument('--dry-run', '-d', action='store_true', help='Print repository info and template without creating repository')
|
| 31 |
+
|
| 32 |
+
args = parser.parse_args()
|
| 33 |
+
|
| 34 |
+
repo_id = f"{args.namespace}/{args.model_name}-GGUF"
|
| 35 |
+
print("Repository ID: ", repo_id)
|
| 36 |
+
|
| 37 |
+
repo_url = None
|
| 38 |
+
if not args.dry_run:
|
| 39 |
+
repo_url = api.create_repo(
|
| 40 |
+
repo_id=repo_id,
|
| 41 |
+
repo_type="model",
|
| 42 |
+
private=args.private,
|
| 43 |
+
exist_ok=False
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
if not args.no_card:
|
| 47 |
+
if args.embedding:
|
| 48 |
+
template_path = "scripts/embedding/modelcard.template"
|
| 49 |
+
else:
|
| 50 |
+
template_path = "scripts/causal/modelcard.template"
|
| 51 |
+
|
| 52 |
+
print("Template path: ", template_path)
|
| 53 |
+
|
| 54 |
+
model_card_content = load_template_and_substitute(
|
| 55 |
+
template_path,
|
| 56 |
+
model_name=args.model_name,
|
| 57 |
+
namespace=args.namespace,
|
| 58 |
+
base_model=args.org_base_model,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
if args.dry_run:
|
| 62 |
+
print("\nTemplate Content:\n")
|
| 63 |
+
print(model_card_content)
|
| 64 |
+
else:
|
| 65 |
+
if model_card_content:
|
| 66 |
+
api.upload_file(
|
| 67 |
+
path_or_fileobj=model_card_content.encode('utf-8'),
|
| 68 |
+
path_in_repo="README.md",
|
| 69 |
+
repo_id=repo_id
|
| 70 |
+
)
|
| 71 |
+
print("Model card created successfully.")
|
| 72 |
+
else:
|
| 73 |
+
print("Failed to create model card.")
|
| 74 |
+
|
| 75 |
+
if not args.dry_run and repo_url:
|
| 76 |
+
print(f"Repository created: {repo_url}")
|
| 77 |
+
|
| 78 |
+
|
examples/model-conversion/scripts/utils/hf-upload-gguf-model.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
from huggingface_hub import HfApi
|
| 4 |
+
import argparse
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
def upload_gguf_file(local_file_path, repo_id, filename_in_repo=None):
|
| 8 |
+
"""
|
| 9 |
+
Upload a GGUF file to a Hugging Face model repository
|
| 10 |
+
|
| 11 |
+
Args:
|
| 12 |
+
local_file_path: Path to your local GGUF file
|
| 13 |
+
repo_id: Your repository ID (e.g., "username/model-name")
|
| 14 |
+
filename_in_repo: Optional custom name for the file in the repo
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
if not os.path.exists(local_file_path):
|
| 18 |
+
print(f"❌ File not found: {local_file_path}")
|
| 19 |
+
return False
|
| 20 |
+
|
| 21 |
+
if filename_in_repo is None:
|
| 22 |
+
filename_in_repo = os.path.basename(local_file_path)
|
| 23 |
+
|
| 24 |
+
if filename_in_repo is None or filename_in_repo == "":
|
| 25 |
+
filename_in_repo = os.path.basename(local_file_path)
|
| 26 |
+
|
| 27 |
+
print(f"📤 Uploading {local_file_path} to {repo_id}/{filename_in_repo}")
|
| 28 |
+
|
| 29 |
+
api = HfApi()
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
api.upload_file(
|
| 33 |
+
path_or_fileobj=local_file_path,
|
| 34 |
+
path_in_repo=filename_in_repo,
|
| 35 |
+
repo_id=repo_id,
|
| 36 |
+
repo_type="model",
|
| 37 |
+
commit_message=f"Upload {filename_in_repo}"
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
print("✅ Upload successful!")
|
| 41 |
+
print(f"🔗 File available at: https://huggingface.co/{repo_id}/blob/main/{filename_in_repo}")
|
| 42 |
+
return True
|
| 43 |
+
|
| 44 |
+
except Exception as e:
|
| 45 |
+
print(f"❌ Upload failed: {e}")
|
| 46 |
+
return False
|
| 47 |
+
|
| 48 |
+
# This script requires that the environment variable HF_TOKEN is set with your
|
| 49 |
+
# Hugging Face API token.
|
| 50 |
+
api = HfApi()
|
| 51 |
+
|
| 52 |
+
parser = argparse.ArgumentParser(description='Upload a GGUF model to a Huggingface model repository')
|
| 53 |
+
parser.add_argument('--gguf-model-path', '-m', help='The GGUF model file to upload', required=True)
|
| 54 |
+
parser.add_argument('--repo-id', '-r', help='The repository to upload to', required=True)
|
| 55 |
+
parser.add_argument('--name', '-o', help='The name in the model repository', required=False)
|
| 56 |
+
args = parser.parse_args()
|
| 57 |
+
|
| 58 |
+
upload_gguf_file(args.gguf_model_path, args.repo_id, args.name)
|
examples/model-conversion/scripts/utils/inspect-converted-model.sh
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
|
| 3 |
+
# First try command line argument, then environment variable, then file
|
| 4 |
+
CONVERTED_MODEL="${1:-"$CONVERTED_MODEL"}"
|
| 5 |
+
|
| 6 |
+
# Final check if we have a model path
|
| 7 |
+
if [ -z "$CONVERTED_MODEL" ]; then
|
| 8 |
+
echo "Error: Model path must be provided either as:" >&2
|
| 9 |
+
echo " 1. Command line argument" >&2
|
| 10 |
+
echo " 2. CONVERTED_MODEL environment variable" >&2
|
| 11 |
+
exit 1
|
| 12 |
+
fi
|
| 13 |
+
|
| 14 |
+
../../gguf-py/gguf/scripts/gguf_dump.py $CONVERTED_MODEL
|
examples/model-conversion/scripts/utils/inspect-org-model.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
import struct
|
| 8 |
+
import sys
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Optional
|
| 11 |
+
from safetensors import safe_open
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
MODEL_SAFETENSORS_FILE = "model.safetensors"
|
| 15 |
+
MODEL_SAFETENSORS_INDEX = "model.safetensors.index.json"
|
| 16 |
+
|
| 17 |
+
DTYPE_SIZES = {
|
| 18 |
+
"F64": 8, "I64": 8, "U64": 8,
|
| 19 |
+
"F32": 4, "I32": 4, "U32": 4,
|
| 20 |
+
"F16": 2, "BF16": 2, "I16": 2, "U16": 2,
|
| 21 |
+
"I8": 1, "U8": 1, "BOOL": 1,
|
| 22 |
+
"F8_E4M3": 1, "F8_E5M2": 1,
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
SIZE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB']
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def get_weight_map(model_path: Path) -> Optional[dict[str, str]]:
|
| 29 |
+
index_file = model_path / MODEL_SAFETENSORS_INDEX
|
| 30 |
+
|
| 31 |
+
if index_file.exists():
|
| 32 |
+
with open(index_file, 'r') as f:
|
| 33 |
+
index = json.load(f)
|
| 34 |
+
return index.get("weight_map", {})
|
| 35 |
+
|
| 36 |
+
return None
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def get_all_tensor_names(model_path: Path) -> list[str]:
|
| 40 |
+
weight_map = get_weight_map(model_path)
|
| 41 |
+
|
| 42 |
+
if weight_map is not None:
|
| 43 |
+
return list(weight_map.keys())
|
| 44 |
+
|
| 45 |
+
single_file = model_path / MODEL_SAFETENSORS_FILE
|
| 46 |
+
if single_file.exists():
|
| 47 |
+
try:
|
| 48 |
+
with safe_open(single_file, framework="pt", device="cpu") as f:
|
| 49 |
+
return list(f.keys())
|
| 50 |
+
except Exception as e:
|
| 51 |
+
print(f"Error reading {single_file}: {e}")
|
| 52 |
+
sys.exit(1)
|
| 53 |
+
|
| 54 |
+
print(f"Error: No safetensors files found in {model_path}")
|
| 55 |
+
sys.exit(1)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def find_tensor_file(model_path: Path, tensor_name: str) -> Optional[str]:
|
| 59 |
+
weight_map = get_weight_map(model_path)
|
| 60 |
+
|
| 61 |
+
if weight_map is not None:
|
| 62 |
+
return weight_map.get(tensor_name)
|
| 63 |
+
|
| 64 |
+
single_file = model_path / MODEL_SAFETENSORS_FILE
|
| 65 |
+
if single_file.exists():
|
| 66 |
+
return single_file.name
|
| 67 |
+
|
| 68 |
+
return None
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def read_safetensors_header(file_path: Path) -> dict:
|
| 72 |
+
with open(file_path, 'rb') as f:
|
| 73 |
+
header_size = struct.unpack('<Q', f.read(8))[0]
|
| 74 |
+
return json.loads(f.read(header_size))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def get_tensor_size_bytes(tensor_meta: dict) -> int:
|
| 78 |
+
offsets = tensor_meta.get("data_offsets")
|
| 79 |
+
if offsets and len(offsets) == 2:
|
| 80 |
+
return offsets[1] - offsets[0]
|
| 81 |
+
n_elements = 1
|
| 82 |
+
for d in tensor_meta.get("shape", []):
|
| 83 |
+
n_elements *= d
|
| 84 |
+
return n_elements * DTYPE_SIZES.get(tensor_meta.get("dtype", "F32"), 4)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def format_size(size_bytes: int) -> str:
|
| 88 |
+
val = float(size_bytes)
|
| 89 |
+
for unit in SIZE_UNITS[:-1]:
|
| 90 |
+
if val < 1024.0:
|
| 91 |
+
return f"{val:.2f} {unit}"
|
| 92 |
+
val /= 1024.0
|
| 93 |
+
return f"{val:.2f} {SIZE_UNITS[-1]}"
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def get_all_tensor_metadata(model_path: Path) -> dict[str, dict]:
|
| 97 |
+
weight_map = get_weight_map(model_path)
|
| 98 |
+
|
| 99 |
+
if weight_map is not None:
|
| 100 |
+
file_to_tensors: dict[str, list[str]] = {}
|
| 101 |
+
for tensor_name, file_name in weight_map.items():
|
| 102 |
+
file_to_tensors.setdefault(file_name, []).append(tensor_name)
|
| 103 |
+
|
| 104 |
+
all_metadata: dict[str, dict] = {}
|
| 105 |
+
for file_name, tensor_names in file_to_tensors.items():
|
| 106 |
+
try:
|
| 107 |
+
header = read_safetensors_header(model_path / file_name)
|
| 108 |
+
for tensor_name in tensor_names:
|
| 109 |
+
if tensor_name in header:
|
| 110 |
+
all_metadata[tensor_name] = header[tensor_name]
|
| 111 |
+
except Exception as e:
|
| 112 |
+
print(f"Warning: Could not read header from {file_name}: {e}", file=sys.stderr)
|
| 113 |
+
return all_metadata
|
| 114 |
+
|
| 115 |
+
single_file = model_path / MODEL_SAFETENSORS_FILE
|
| 116 |
+
if single_file.exists():
|
| 117 |
+
try:
|
| 118 |
+
header = read_safetensors_header(single_file)
|
| 119 |
+
return {k: v for k, v in header.items() if k != "__metadata__"}
|
| 120 |
+
except Exception as e:
|
| 121 |
+
print(f"Error reading {single_file}: {e}")
|
| 122 |
+
sys.exit(1)
|
| 123 |
+
|
| 124 |
+
print(f"Error: No safetensors files found in {model_path}")
|
| 125 |
+
sys.exit(1)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def normalize_tensor_name(tensor_name: str) -> str:
|
| 129 |
+
normalized = re.sub(r'\.\d+\.', '.#.', tensor_name)
|
| 130 |
+
normalized = re.sub(r'\.\d+$', '.#', normalized)
|
| 131 |
+
return normalized
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def list_all_tensors(
|
| 135 |
+
model_path: Path,
|
| 136 |
+
short: bool = False,
|
| 137 |
+
show_sizes: bool = False,
|
| 138 |
+
):
|
| 139 |
+
tensor_names = get_all_tensor_names(model_path)
|
| 140 |
+
|
| 141 |
+
metadata: Optional[dict[str, dict]] = None
|
| 142 |
+
if show_sizes:
|
| 143 |
+
metadata = get_all_tensor_metadata(model_path)
|
| 144 |
+
|
| 145 |
+
total_bytes = 0
|
| 146 |
+
|
| 147 |
+
if short:
|
| 148 |
+
seen: dict[str, str] = {}
|
| 149 |
+
for tensor_name in sorted(tensor_names):
|
| 150 |
+
normalized = normalize_tensor_name(tensor_name)
|
| 151 |
+
if normalized not in seen:
|
| 152 |
+
seen[normalized] = tensor_name
|
| 153 |
+
display_pairs = list(sorted(seen.items()))
|
| 154 |
+
name_width = max((len(n) for n, _ in display_pairs), default=0)
|
| 155 |
+
for normalized, first_name in display_pairs:
|
| 156 |
+
if metadata and first_name in metadata:
|
| 157 |
+
m = metadata[first_name]
|
| 158 |
+
size = get_tensor_size_bytes(m)
|
| 159 |
+
total_bytes += size
|
| 160 |
+
print(f"{normalized:{name_width}} {m.get('dtype', '?'):6s} {str(m.get('shape', '')):30s} {format_size(size)}")
|
| 161 |
+
else:
|
| 162 |
+
print(normalized)
|
| 163 |
+
else:
|
| 164 |
+
name_width = max((len(n) for n in tensor_names), default=0)
|
| 165 |
+
for tensor_name in sorted(tensor_names):
|
| 166 |
+
if metadata and tensor_name in metadata:
|
| 167 |
+
m = metadata[tensor_name]
|
| 168 |
+
size = get_tensor_size_bytes(m)
|
| 169 |
+
total_bytes += size
|
| 170 |
+
print(f"{tensor_name:{name_width}} {m.get('dtype', '?'):6s} {str(m.get('shape', '')):30s} {format_size(size)}")
|
| 171 |
+
else:
|
| 172 |
+
print(tensor_name)
|
| 173 |
+
|
| 174 |
+
if show_sizes:
|
| 175 |
+
print(f"\nTotal: {format_size(total_bytes)}")
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def print_tensor_info(model_path: Path, tensor_name: str, num_values: Optional[int] = None):
|
| 179 |
+
tensor_file = find_tensor_file(model_path, tensor_name)
|
| 180 |
+
|
| 181 |
+
if tensor_file is None:
|
| 182 |
+
print(f"Error: Could not find tensor '{tensor_name}' in model index")
|
| 183 |
+
print(f"Model path: {model_path}")
|
| 184 |
+
sys.exit(1)
|
| 185 |
+
|
| 186 |
+
file_path = model_path / tensor_file
|
| 187 |
+
|
| 188 |
+
try:
|
| 189 |
+
header = read_safetensors_header(file_path)
|
| 190 |
+
tensor_meta = header.get(tensor_name, {})
|
| 191 |
+
dtype_str = tensor_meta.get("dtype")
|
| 192 |
+
|
| 193 |
+
with safe_open(file_path, framework="pt", device="cpu") as f:
|
| 194 |
+
if tensor_name in f.keys():
|
| 195 |
+
tensor_slice = f.get_slice(tensor_name)
|
| 196 |
+
shape = tensor_slice.get_shape()
|
| 197 |
+
print(f"Tensor: {tensor_name}")
|
| 198 |
+
print(f"File: {tensor_file}")
|
| 199 |
+
print(f"Shape: {shape}")
|
| 200 |
+
if dtype_str:
|
| 201 |
+
print(f"Dtype: {dtype_str}")
|
| 202 |
+
if tensor_meta:
|
| 203 |
+
print(f"Size: {format_size(get_tensor_size_bytes(tensor_meta))}")
|
| 204 |
+
if num_values is not None:
|
| 205 |
+
tensor = f.get_tensor(tensor_name)
|
| 206 |
+
if not dtype_str:
|
| 207 |
+
print(f"Dtype: {tensor.dtype}")
|
| 208 |
+
flat = tensor.flatten()
|
| 209 |
+
n = min(num_values, flat.numel())
|
| 210 |
+
print(f"Values: {flat[:n].tolist()}")
|
| 211 |
+
else:
|
| 212 |
+
print(f"Error: Tensor '{tensor_name}' not found in {tensor_file}")
|
| 213 |
+
sys.exit(1)
|
| 214 |
+
|
| 215 |
+
except FileNotFoundError:
|
| 216 |
+
print(f"Error: The file '{file_path}' was not found.")
|
| 217 |
+
sys.exit(1)
|
| 218 |
+
except Exception as e:
|
| 219 |
+
print(f"An error occurred: {e}")
|
| 220 |
+
sys.exit(1)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def main():
|
| 224 |
+
parser = argparse.ArgumentParser(
|
| 225 |
+
description="Print tensor information from a safetensors model"
|
| 226 |
+
)
|
| 227 |
+
parser.add_argument(
|
| 228 |
+
"tensor_name",
|
| 229 |
+
nargs="?",
|
| 230 |
+
help="Name of the tensor to inspect"
|
| 231 |
+
)
|
| 232 |
+
parser.add_argument(
|
| 233 |
+
"-m", "--model-path",
|
| 234 |
+
type=Path,
|
| 235 |
+
help="Path to the model directory (default: MODEL_PATH environment variable)"
|
| 236 |
+
)
|
| 237 |
+
parser.add_argument(
|
| 238 |
+
"-l", "--list-all-short",
|
| 239 |
+
action="store_true",
|
| 240 |
+
help="List unique tensor patterns (layer numbers replaced with #)"
|
| 241 |
+
)
|
| 242 |
+
parser.add_argument(
|
| 243 |
+
"-la", "--list-all",
|
| 244 |
+
action="store_true",
|
| 245 |
+
help="List all tensor names with actual layer numbers"
|
| 246 |
+
)
|
| 247 |
+
parser.add_argument(
|
| 248 |
+
"-n", "--num-values",
|
| 249 |
+
nargs="?",
|
| 250 |
+
const=10,
|
| 251 |
+
default=None,
|
| 252 |
+
type=int,
|
| 253 |
+
metavar="N",
|
| 254 |
+
help="Print the first N values of the tensor flattened (default: 10 if flag is given without a number)"
|
| 255 |
+
)
|
| 256 |
+
parser.add_argument(
|
| 257 |
+
"-s", "--sizes",
|
| 258 |
+
action="store_true",
|
| 259 |
+
help="Show dtype, shape, and size for each tensor when listing"
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
args = parser.parse_args()
|
| 263 |
+
|
| 264 |
+
model_path = args.model_path
|
| 265 |
+
if model_path is None:
|
| 266 |
+
model_path_str = os.environ.get("MODEL_PATH")
|
| 267 |
+
if model_path_str is None:
|
| 268 |
+
print("Error: --model-path not provided and MODEL_PATH environment variable not set")
|
| 269 |
+
sys.exit(1)
|
| 270 |
+
model_path = Path(model_path_str)
|
| 271 |
+
|
| 272 |
+
if not model_path.exists():
|
| 273 |
+
print(f"Error: Model path does not exist: {model_path}")
|
| 274 |
+
sys.exit(1)
|
| 275 |
+
|
| 276 |
+
if not model_path.is_dir():
|
| 277 |
+
print(f"Error: Model path is not a directory: {model_path}")
|
| 278 |
+
sys.exit(1)
|
| 279 |
+
|
| 280 |
+
if args.list_all_short or args.list_all:
|
| 281 |
+
list_all_tensors(model_path, short=args.list_all_short, show_sizes=args.sizes)
|
| 282 |
+
else:
|
| 283 |
+
if args.tensor_name is None:
|
| 284 |
+
print("Error: tensor_name is required when not using --list-all-short or --list-all")
|
| 285 |
+
sys.exit(1)
|
| 286 |
+
print_tensor_info(model_path, args.tensor_name, args.num_values)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
if __name__ == "__main__":
|
| 290 |
+
main()
|
examples/model-conversion/scripts/utils/perplexity-gen.sh
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
|
| 3 |
+
set -e
|
| 4 |
+
|
| 5 |
+
CONVERTED_MODEL="${1:-"$CONVERTED_MODEL"}"
|
| 6 |
+
BUILD_DIR="${2:-"$BUILD_DIR"}"
|
| 7 |
+
|
| 8 |
+
# Final check if we have a model path
|
| 9 |
+
if [ -z "$CONVERTED_MODEL" ]; then
|
| 10 |
+
echo "Error: Model path must be provided either as:" >&2
|
| 11 |
+
echo " 1. Command line argument" >&2
|
| 12 |
+
echo " 2. CONVERTED_MODEL environment variable" >&2
|
| 13 |
+
exit 1
|
| 14 |
+
fi
|
| 15 |
+
|
| 16 |
+
# Check if data/wikitext-2-raw directory exists
|
| 17 |
+
if [ ! -d "ppl/wikitext-2-raw" ]; then
|
| 18 |
+
echo "ppl/wikitext-2-raw directory does not exist. Downloading..." >&2
|
| 19 |
+
mkdir -p ppl
|
| 20 |
+
pushd ppl
|
| 21 |
+
./../../../scripts/get-wikitext-2.sh
|
| 22 |
+
popd
|
| 23 |
+
fi
|
| 24 |
+
|
| 25 |
+
mkdir -p ppl
|
| 26 |
+
OUTPUTFILE="ppl/$(basename $CONVERTED_MODEL).kld"
|
| 27 |
+
echo "Model: $CONVERTED_MODEL"
|
| 28 |
+
|
| 29 |
+
if [ -z "$BUILD_DIR" ]; then
|
| 30 |
+
BUILD_DIR="../../build"
|
| 31 |
+
fi
|
| 32 |
+
|
| 33 |
+
cmake --build $BUILD_DIR --target llama-perplexity -j8
|
| 34 |
+
|
| 35 |
+
${BUILD_DIR}/bin/llama-perplexity -m $CONVERTED_MODEL \
|
| 36 |
+
-f ppl/wikitext-2-raw/wiki.test.raw \
|
| 37 |
+
--kl-divergence-base $OUTPUTFILE
|
| 38 |
+
|
| 39 |
+
echo "Generated logits in $OUTPUTFILE"
|
| 40 |
+
|
examples/model-conversion/scripts/utils/perplexity-run-simple.sh
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
|
| 3 |
+
set -e
|
| 4 |
+
|
| 5 |
+
QUANTIZED_MODEL="${1:-"$QUANTIZED_MODEL"}"
|
| 6 |
+
BUILD_DIR="${2:-"$BUILD_DIR"}"
|
| 7 |
+
|
| 8 |
+
if [ -z "$QUANTIZED_MODEL" ]; then
|
| 9 |
+
echo "Error: Model path must be provided either as:" >&2
|
| 10 |
+
echo " 1. Command line argument" >&2
|
| 11 |
+
echo " 2. QUANTIZED_MODEL environment variable" >&2
|
| 12 |
+
exit 1
|
| 13 |
+
fi
|
| 14 |
+
|
| 15 |
+
# Check if data/wikitext-2-raw directory exists
|
| 16 |
+
if [ ! -d "ppl/wikitext-2-raw" ]; then
|
| 17 |
+
echo "ppl/wikitext-2-raw directory does not exist. Downloading..." >&2
|
| 18 |
+
mkdir -p ppl
|
| 19 |
+
pushd ppl
|
| 20 |
+
./../../../scripts/get-wikitext-2.sh
|
| 21 |
+
popd
|
| 22 |
+
fi
|
| 23 |
+
|
| 24 |
+
if [ -z "$BUILD_DIR" ]; then
|
| 25 |
+
BUILD_DIR="../../build"
|
| 26 |
+
fi
|
| 27 |
+
|
| 28 |
+
cmake --build $BUILD_DIR --target llama-perplexity -j8
|
| 29 |
+
|
| 30 |
+
${BUILD_DIR}/bin/llama-perplexity -m $QUANTIZED_MODEL -f ppl/wikitext-2-raw/wiki.test.raw
|
| 31 |
+
|
| 32 |
+
|
examples/model-conversion/scripts/utils/perplexity-run.sh
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
|
| 3 |
+
set -e
|
| 4 |
+
|
| 5 |
+
QUANTIZED_MODEL="${1:-"$QUANTIZED_MODEL"}"
|
| 6 |
+
LOGITS_FILE="${2:-"$LOGITS_FILE"}"
|
| 7 |
+
BUILD_DIR="${3:-"$BUILD_DIR"}"
|
| 8 |
+
|
| 9 |
+
if [ -z "$QUANTIZED_MODEL" ]; then
|
| 10 |
+
echo "Error: Model path must be provided either as:" >&2
|
| 11 |
+
echo " 1. Command line argument" >&2
|
| 12 |
+
echo " 2. QUANTIZED_MODEL environment variable" >&2
|
| 13 |
+
exit 1
|
| 14 |
+
fi
|
| 15 |
+
|
| 16 |
+
if [ ! -f ${LOGITS_FILE} ]; then
|
| 17 |
+
echo "Error: logits file '${LOGITS_FILE} was not found"
|
| 18 |
+
echo "Did you run the perplexity-gen.sh script?"
|
| 19 |
+
exit 1
|
| 20 |
+
fi
|
| 21 |
+
|
| 22 |
+
if [ -z "$BUILD_DIR" ]; then
|
| 23 |
+
BUILD_DIR="../../build"
|
| 24 |
+
fi
|
| 25 |
+
|
| 26 |
+
echo "Model: $QUANTIZED_MODEL"
|
| 27 |
+
echo "Data file: $LOGITS_FILE"
|
| 28 |
+
|
| 29 |
+
cmake --build $BUILD_DIR --target llama-perplexity -j8
|
| 30 |
+
|
| 31 |
+
${BUILD_DIR}/bin/llama-perplexity -m $QUANTIZED_MODEL \
|
| 32 |
+
--kl-divergence-base $LOGITS_FILE \
|
| 33 |
+
--kl-divergence
|
examples/model-conversion/scripts/utils/quantize.sh
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
|
| 3 |
+
set -e
|
| 4 |
+
|
| 5 |
+
CONVERTED_MODEL="${1:-"$CONVERTED_MODEL"}"
|
| 6 |
+
QUANTIZED_TYPE="${2:-"$QUANTIZED_TYPE"}"
|
| 7 |
+
TOKEN_EMBD_TYPE="${3:-"${TOKEN_EMBD_TYPE}"}"
|
| 8 |
+
OUTPUT_TYPE="${4:-"${OUTPUT_TYPE}"}"
|
| 9 |
+
BUILD_DIR="${5:-"$BUILD_DIR"}"
|
| 10 |
+
QUANTIZED_MODEL=$CONVERTED_MODEL
|
| 11 |
+
|
| 12 |
+
# Final check if we have a model path
|
| 13 |
+
if [ -z "$CONVERTED_MODEL" ]; then
|
| 14 |
+
echo "Error: Model path must be provided either as:" >&2
|
| 15 |
+
echo " 1. Command line argument" >&2
|
| 16 |
+
echo " 2. CONVERTED_MODEL environment variable" >&2
|
| 17 |
+
exit 1
|
| 18 |
+
fi
|
| 19 |
+
|
| 20 |
+
if [ -z "$QUANTIZED_TYPE" ]; then
|
| 21 |
+
echo "Error: QUANTIZED_TYPE is required" >&2
|
| 22 |
+
exit 1
|
| 23 |
+
fi
|
| 24 |
+
|
| 25 |
+
echo $CONVERTED_MODEL
|
| 26 |
+
|
| 27 |
+
# Process the quantized model filename
|
| 28 |
+
if [[ "$QUANTIZED_MODEL" == *.gguf ]]; then
|
| 29 |
+
# Remove .gguf suffix, add quantized type, then add .gguf back
|
| 30 |
+
BASE_NAME="${QUANTIZED_MODEL%.gguf}"
|
| 31 |
+
QUANTIZED_MODEL="${BASE_NAME}-${QUANTIZED_TYPE}.gguf"
|
| 32 |
+
else
|
| 33 |
+
echo "Error: QUANTIZED_MODEL must end with .gguf extension" >&2
|
| 34 |
+
exit 1
|
| 35 |
+
fi
|
| 36 |
+
|
| 37 |
+
if [ -z "$BUILD_DIR" ]; then
|
| 38 |
+
BUILD_DIR="../../build"
|
| 39 |
+
fi
|
| 40 |
+
|
| 41 |
+
cmake --build $BUILD_DIR --target llama-quantize -j8
|
| 42 |
+
|
| 43 |
+
echo $TOKEN_EMBD_TYPE
|
| 44 |
+
echo $OUTPUT_TYPE
|
| 45 |
+
|
| 46 |
+
CMD_ARGS=("${BUILD_DIR}/bin/llama-quantize")
|
| 47 |
+
[[ -n "$TOKEN_EMBD_TYPE" ]] && CMD_ARGS+=("--token-embedding-type" "$TOKEN_EMBD_TYPE")
|
| 48 |
+
[[ -n "$OUTPUT_TYPE" ]] && CMD_ARGS+=("--output-tensor-type" "$OUTPUT_TYPE")
|
| 49 |
+
CMD_ARGS+=("$CONVERTED_MODEL" "$QUANTIZED_MODEL" "$QUANTIZED_TYPE")
|
| 50 |
+
|
| 51 |
+
"${CMD_ARGS[@]}"
|
| 52 |
+
|
| 53 |
+
echo "Quantized model saved to: $QUANTIZED_MODEL"
|
examples/model-conversion/scripts/utils/run-embedding-server.sh
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
|
| 3 |
+
set -e
|
| 4 |
+
#
|
| 5 |
+
# First try command line argument, then environment variable, then file
|
| 6 |
+
CONVERTED_MODEL="${1:-"$CONVERTED_MODEL"}"
|
| 7 |
+
BUILD_DIR="${2:-"$BUILD_DIR"}"
|
| 8 |
+
|
| 9 |
+
# Final check if we have a model path
|
| 10 |
+
if [ -z "$CONVERTED_MODEL" ]; then
|
| 11 |
+
echo "Error: Model path must be provided either as:" >&2
|
| 12 |
+
echo " 1. Command line argument" >&2
|
| 13 |
+
echo " 2. CONVERTED_MODEL environment variable" >&2
|
| 14 |
+
exit 1
|
| 15 |
+
fi
|
| 16 |
+
|
| 17 |
+
if [ -z "$BUILD_DIR" ]; then
|
| 18 |
+
BUILD_DIR="../../build"
|
| 19 |
+
fi
|
| 20 |
+
|
| 21 |
+
echo $CONVERTED_MODEL
|
| 22 |
+
|
| 23 |
+
cmake --build $BUILD_DIR --target llama-server
|
| 24 |
+
|
| 25 |
+
${BUILD_DIR}/bin/llama-server -m $CONVERTED_MODEL \
|
| 26 |
+
--embedding \
|
| 27 |
+
--pooling none
|
examples/model-conversion/scripts/utils/semantic_check.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import argparse
|
| 5 |
+
import os
|
| 6 |
+
import importlib
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
from transformers import AutoTokenizer, AutoConfig, AutoModelForCausalLM, AutoModel
|
| 10 |
+
from common import compare_tokens, exit_with_warning # type: ignore[import-not-found, ty:unresolved-import]
|
| 11 |
+
|
| 12 |
+
unreleased_model_name = os.getenv('UNRELEASED_MODEL_NAME')
|
| 13 |
+
|
| 14 |
+
def cosine_similarity(a, b=None):
|
| 15 |
+
a = np.asarray(a)
|
| 16 |
+
if b is None:
|
| 17 |
+
b = a
|
| 18 |
+
else:
|
| 19 |
+
b = np.asarray(b)
|
| 20 |
+
|
| 21 |
+
if a.ndim == 1:
|
| 22 |
+
a = a.reshape(1, -1)
|
| 23 |
+
if b.ndim == 1:
|
| 24 |
+
b = b.reshape(1, -1)
|
| 25 |
+
|
| 26 |
+
a_norms = np.linalg.norm(a, axis=1, keepdims=True)
|
| 27 |
+
b_norms = np.linalg.norm(b, axis=1, keepdims=True)
|
| 28 |
+
|
| 29 |
+
a_norms = np.where(a_norms == 0, 1e-8, a_norms)
|
| 30 |
+
b_norms = np.where(b_norms == 0, 1e-8, b_norms)
|
| 31 |
+
|
| 32 |
+
a_normalized = a / a_norms
|
| 33 |
+
b_normalized = b / b_norms
|
| 34 |
+
|
| 35 |
+
# Compute cosine similarity
|
| 36 |
+
return np.dot(a_normalized, b_normalized.T)
|
| 37 |
+
|
| 38 |
+
def load_embeddings_from_file(filename, n_tokens, n_embd):
|
| 39 |
+
embeddings = np.fromfile(filename, dtype=np.float32)
|
| 40 |
+
# Check if this is pooled (single embedding) or per-token embeddings
|
| 41 |
+
if len(embeddings) == n_embd:
|
| 42 |
+
return embeddings.reshape(1, n_embd)
|
| 43 |
+
else:
|
| 44 |
+
return embeddings.reshape(n_tokens, n_embd)
|
| 45 |
+
|
| 46 |
+
def test_single_prompt_similarity(python_emb, cpp_emb, tokens, prompt):
|
| 47 |
+
np.set_printoptions(suppress=True, precision=6)
|
| 48 |
+
print("pytorch embeddings:");
|
| 49 |
+
print(python_emb)
|
| 50 |
+
print("llama.cpp embeddings:");
|
| 51 |
+
print(cpp_emb)
|
| 52 |
+
print(f"\n=== Prompt: '{prompt}' ===")
|
| 53 |
+
print(f"Tokens: {tokens}")
|
| 54 |
+
print(f"Embeddings shape: Python {python_emb.shape}, llama.cpp {cpp_emb.shape}")
|
| 55 |
+
|
| 56 |
+
n_tokens = len(tokens)
|
| 57 |
+
is_pooled = python_emb.shape[0] == 1
|
| 58 |
+
|
| 59 |
+
if is_pooled:
|
| 60 |
+
print(f"\n[Pooled Embeddings Mode - comparing single sentence embeddings]")
|
| 61 |
+
|
| 62 |
+
# 1. Direct embedding comparison for pooled embeddings
|
| 63 |
+
print(f"\n1. Raw Embedding Magnitude Comparison:")
|
| 64 |
+
py_mag = np.linalg.norm(python_emb[0])
|
| 65 |
+
cpp_mag = np.linalg.norm(cpp_emb[0])
|
| 66 |
+
ratio = py_mag / cpp_mag if cpp_mag > 0 else float('inf')
|
| 67 |
+
print(f" Pooled embedding: Python={py_mag:.3f}, llama.cpp={cpp_mag:.3f}, ratio={ratio:.3f}")
|
| 68 |
+
|
| 69 |
+
# 2. Cross-model similarity for pooled embeddings
|
| 70 |
+
print(f"\n2. Cross-Model Pooled Embedding Similarity:")
|
| 71 |
+
sim = cosine_similarity([python_emb[0]], [cpp_emb[0]])[0][0]
|
| 72 |
+
print(f" Cosine similarity: {sim:.6f}")
|
| 73 |
+
|
| 74 |
+
return {
|
| 75 |
+
'cross_model_similarities': [sim],
|
| 76 |
+
'similarity_matrix_diff': np.array([[0.0]]),
|
| 77 |
+
'max_diff': 0.0,
|
| 78 |
+
'mean_diff': 0.0,
|
| 79 |
+
'rms_diff': 0.0
|
| 80 |
+
}
|
| 81 |
+
else:
|
| 82 |
+
# Original per-token comparison logic
|
| 83 |
+
# 1. Direct embedding comparison
|
| 84 |
+
print(f"\n1. Raw Embedding Magnitude Comparison:")
|
| 85 |
+
# Check if the distance of each token embedding from the origin and compare
|
| 86 |
+
# if the vectors are on the same "sphere". This does not tell us about
|
| 87 |
+
# direction (meaning of the token embedding), just magnitude.
|
| 88 |
+
for i in range(n_tokens):
|
| 89 |
+
py_mag = np.linalg.norm(python_emb[i]) # calculate standard euclidean norm for Python embeddings
|
| 90 |
+
cpp_mag = np.linalg.norm(cpp_emb[i]) # calculate standard euclidean norm for llama.cpp embeddings
|
| 91 |
+
ratio = py_mag / cpp_mag if cpp_mag > 0 else float('inf')
|
| 92 |
+
print(f" Token {i} ({tokens[i]}): Python={py_mag:.3f}, llama.cpp={cpp_mag:.3f}, ratio={ratio:.3f}")
|
| 93 |
+
|
| 94 |
+
# 2. Cosine similarity between tokens within each model
|
| 95 |
+
# Here we check the direction of token embeddings to see if the have the
|
| 96 |
+
# same meaning (similarity). This is done by calculating cosine similarity
|
| 97 |
+
# of a pair of token embeddings within each model.
|
| 98 |
+
print(f"\n2. Within-Model Token Similarities:")
|
| 99 |
+
print(" Python model:")
|
| 100 |
+
for i in range(n_tokens):
|
| 101 |
+
for j in range(i+1, n_tokens):
|
| 102 |
+
sim = cosine_similarity([python_emb[i]], [python_emb[j]])[0][0]
|
| 103 |
+
print(f" {tokens[i]} ↔ {tokens[j]}: {sim:.4f}")
|
| 104 |
+
|
| 105 |
+
print(" llama.cpp model:")
|
| 106 |
+
for i in range(n_tokens):
|
| 107 |
+
for j in range(i+1, n_tokens):
|
| 108 |
+
sim = cosine_similarity([cpp_emb[i]], [cpp_emb[j]])[0][0]
|
| 109 |
+
print(f" {tokens[i]} ↔ {tokens[j]}: {sim:.4f}")
|
| 110 |
+
|
| 111 |
+
# 3. Cross-model similarity (same token position)
|
| 112 |
+
print(f"\n3. Cross-Model Same-Token Similarities:")
|
| 113 |
+
for i in range(n_tokens):
|
| 114 |
+
sim = cosine_similarity([python_emb[i]], [cpp_emb[i]])[0][0]
|
| 115 |
+
print(f" Token {i} ({tokens[i]}): {sim:.4f}")
|
| 116 |
+
|
| 117 |
+
# 4. Similarity matrix comparison
|
| 118 |
+
print(f"\n4. Similarity Matrix Differences:")
|
| 119 |
+
py_sim_matrix = cosine_similarity(python_emb)
|
| 120 |
+
cpp_sim_matrix = cosine_similarity(cpp_emb)
|
| 121 |
+
diff_matrix = np.abs(py_sim_matrix - cpp_sim_matrix)
|
| 122 |
+
|
| 123 |
+
print(f" Max difference: {np.max(diff_matrix):.4f}")
|
| 124 |
+
print(f" Mean difference: {np.mean(diff_matrix):.4f}")
|
| 125 |
+
print(f" RMS difference: {np.sqrt(np.mean(diff_matrix**2)):.4f}")
|
| 126 |
+
|
| 127 |
+
return {
|
| 128 |
+
'cross_model_similarities': [cosine_similarity([python_emb[i]], [cpp_emb[i]])[0][0] for i in range(n_tokens)],
|
| 129 |
+
'similarity_matrix_diff': diff_matrix,
|
| 130 |
+
'max_diff': np.max(diff_matrix),
|
| 131 |
+
'mean_diff': np.mean(diff_matrix),
|
| 132 |
+
'rms_diff': np.sqrt(np.mean(diff_matrix**2))
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
def read_prompt_from_file(file_path):
|
| 136 |
+
try:
|
| 137 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 138 |
+
return f.read().strip()
|
| 139 |
+
except FileNotFoundError:
|
| 140 |
+
print(f"Error: Prompts file '{file_path}' not found")
|
| 141 |
+
exit(1)
|
| 142 |
+
except Exception as e:
|
| 143 |
+
print(f"Error reading prompts file: {e}")
|
| 144 |
+
exit(1)
|
| 145 |
+
|
| 146 |
+
def main():
|
| 147 |
+
parser = argparse.ArgumentParser(description='Test semantic similarity between Python and llama.cpp embeddings')
|
| 148 |
+
parser.add_argument('--model-path', '-m', required=True, help='Path to the original Python model')
|
| 149 |
+
parser.add_argument('--python-embeddings', '-pe', help='Path to pytorch embeddings "logits" binary file')
|
| 150 |
+
parser.add_argument('--cpp-embeddings', '-ce', help='Path to llama.cpp embeddings "logits" binary file')
|
| 151 |
+
parser.add_argument('--causal', '-c', default=False, help='if the model is causal (default: false)', action='store_true')
|
| 152 |
+
parser.add_argument('--prompt', '-p', default='Hello world today', help='Test prompt')
|
| 153 |
+
parser.add_argument('--prompts-file', '-pf', help='Path to file containing prompts')
|
| 154 |
+
|
| 155 |
+
args = parser.parse_args()
|
| 156 |
+
|
| 157 |
+
if args.prompts_file:
|
| 158 |
+
prompt = read_prompt_from_file(args.prompts_file)
|
| 159 |
+
else:
|
| 160 |
+
prompt = args.prompt
|
| 161 |
+
|
| 162 |
+
python_emb_path = Path(args.python_embeddings)
|
| 163 |
+
cpp_emb_path = Path(args.cpp_embeddings)
|
| 164 |
+
|
| 165 |
+
# Extract base names (e.g., "pytorch-model-name-embeddings.bin" -> "pytorch-model-name")
|
| 166 |
+
python_model_name = python_emb_path.stem.replace("-embeddings", "")
|
| 167 |
+
cpp_model_name = cpp_emb_path.stem.replace("-embeddings", "")
|
| 168 |
+
|
| 169 |
+
print("Semantic Similarity Test Between Python and llama.cpp Embedding Models")
|
| 170 |
+
print("=" * 70)
|
| 171 |
+
|
| 172 |
+
# First verify tokens match before comparing embeddings
|
| 173 |
+
print("\n🔍 Token Comparison Check")
|
| 174 |
+
print("=" * 70)
|
| 175 |
+
data_dir = python_emb_path.parent
|
| 176 |
+
if not compare_tokens(python_model_name, cpp_model_name, type_suffix="-embeddings", output_dir=str(data_dir)):
|
| 177 |
+
exit_with_warning("\n❌ Token mismatch detected", args.model_path)
|
| 178 |
+
print()
|
| 179 |
+
|
| 180 |
+
# Single prompt detailed comparison
|
| 181 |
+
print(f"\nTesting with prompt: '{prompt}'")
|
| 182 |
+
|
| 183 |
+
# Load the python model to get configuration information and also to load the tokenizer.
|
| 184 |
+
print("Loading model and tokenizer using AutoTokenizer:", args.model_path)
|
| 185 |
+
tokenizer = AutoTokenizer.from_pretrained(args.model_path)
|
| 186 |
+
config = AutoConfig.from_pretrained(args.model_path, trust_remote_code=True)
|
| 187 |
+
|
| 188 |
+
if unreleased_model_name:
|
| 189 |
+
model_name_lower = unreleased_model_name.lower()
|
| 190 |
+
unreleased_module_path = f"transformers.models.{model_name_lower}.modular_{model_name_lower}"
|
| 191 |
+
if args.causal:
|
| 192 |
+
class_name = f"{unreleased_model_name}ForCausalLM"
|
| 193 |
+
else:
|
| 194 |
+
class_name = f"{unreleased_model_name}Model"
|
| 195 |
+
print(f"Model class: {class_name}")
|
| 196 |
+
print(f"Importing unreleased model module: {unreleased_module_path}")
|
| 197 |
+
|
| 198 |
+
try:
|
| 199 |
+
model_class = getattr(importlib.import_module(unreleased_module_path), class_name)
|
| 200 |
+
model = model_class.from_pretrained(args.model_path)
|
| 201 |
+
except (ImportError, AttributeError) as e:
|
| 202 |
+
print(f"Failed to import or load model: {e}")
|
| 203 |
+
exit(1)
|
| 204 |
+
else:
|
| 205 |
+
if args.causal:
|
| 206 |
+
model = AutoModelForCausalLM.from_pretrained(args.model_path, trust_remote_code=True)
|
| 207 |
+
else:
|
| 208 |
+
model = AutoModel.from_pretrained(args.model_path, trust_remote_code=True)
|
| 209 |
+
|
| 210 |
+
encoded = tokenizer(prompt, return_tensors="pt") # ty: ignore[call-non-callable]
|
| 211 |
+
tokens = tokenizer.convert_ids_to_tokens(encoded['input_ids'][0]) # ty: ignore[unresolved-attribute]
|
| 212 |
+
n_tokens = len(tokens)
|
| 213 |
+
print(f"n_tokens: {n_tokens}");
|
| 214 |
+
print(f"hidden_size: {model.config.hidden_size}")
|
| 215 |
+
|
| 216 |
+
# Load binary embeddings from data directory.
|
| 217 |
+
llamacpp_embeddings = load_embeddings_from_file(args.cpp_embeddings, n_tokens, model.config.hidden_size)
|
| 218 |
+
python_embeddings = load_embeddings_from_file(args.python_embeddings, n_tokens, model.config.hidden_size)
|
| 219 |
+
|
| 220 |
+
# Run comparison
|
| 221 |
+
results = test_single_prompt_similarity(python_embeddings, llamacpp_embeddings, tokens, prompt)
|
| 222 |
+
|
| 223 |
+
# Summary
|
| 224 |
+
print(f"\n=== SUMMARY ===")
|
| 225 |
+
avg_cross_sim = np.mean(results['cross_model_similarities'])
|
| 226 |
+
print(f"Average cross-model similarity: {avg_cross_sim:.4f}")
|
| 227 |
+
print(f"Similarity matrix RMS difference: {results['rms_diff']:.4f}")
|
| 228 |
+
|
| 229 |
+
# Quality assessment
|
| 230 |
+
if avg_cross_sim > 0.95:
|
| 231 |
+
print("✅ EXCELLENT: Models are highly similar")
|
| 232 |
+
elif avg_cross_sim > 0.90:
|
| 233 |
+
print("✅ VERY GOOD: Models are very similar")
|
| 234 |
+
elif avg_cross_sim > 0.80:
|
| 235 |
+
print("⚠️ GOOD: Models are reasonably similar")
|
| 236 |
+
elif avg_cross_sim > 0.70:
|
| 237 |
+
print("⚠️ FAIR: Models have some differences")
|
| 238 |
+
else:
|
| 239 |
+
exit_with_warning("❌ POOR: Models are significantly different", args.model_path)
|
| 240 |
+
|
| 241 |
+
if __name__ == "__main__":
|
| 242 |
+
main()
|