[llvm] 2ff9310 - [llvm-ir2vec] Adding BB Embeddings Map API to ir2vec python bindings (#180135)
via llvm-commits
llvm-commits at lists.llvm.org
Wed Feb 11 20:48:16 PST 2026
Author: Nishant Sachdeva
Date: 2026-02-12T10:18:11+05:30
New Revision: 2ff93109daf7ff72f384b90f4dfc9a6cfe823aed
URL: https://github.com/llvm/llvm-project/commit/2ff93109daf7ff72f384b90f4dfc9a6cfe823aed
DIFF: https://github.com/llvm/llvm-project/commit/2ff93109daf7ff72f384b90f4dfc9a6cfe823aed.diff
LOG: [llvm-ir2vec] Adding BB Embeddings Map API to ir2vec python bindings (#180135)
Returns a BB Embedding Map based on the input function name
`getBBEmbMap(funcName) -> Map<BB name, Embedding>`
Added:
Modified:
llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py
llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp
llvm/tools/llvm-ir2vec/lib/Utils.cpp
llvm/tools/llvm-ir2vec/lib/Utils.h
Removed:
################################################################################
diff --git a/llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py b/llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py
index a0d61e4808292..502f8a2411aa8 100644
--- a/llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py
+++ b/llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py
@@ -31,6 +31,18 @@
print(f"Function: {func_name}")
print(f" Embedding: {func_emb.tolist()}")
+ # Test getBBEmbMap
+ print("\n=== Basic Block Embeddings ===")
+
+ # Test valid function names in sorted order
+ for func_name in sorted(["add", "multiply", "conditional"]):
+ bb_emb_map = tool.getBBEmbMap(func_name)
+ print(f"Function: {func_name}")
+ for bb_name in sorted(bb_emb_map.keys()):
+ emb = bb_emb_map[bb_name]
+ print(f" BB: {bb_name}")
+ print(f" Embedding: {emb.tolist()}")
+
# CHECK: SUCCESS: Tool initialized
# CHECK: Tool type: IR2VecTool
# CHECK: === Function Embeddings ===
@@ -47,3 +59,19 @@
# CHECK-NEXT: Embedding: [50.0, 52.0, 54.0]
# CHECK: Function: conditional
# CHECK-NEXT: Embedding: [413.20000000298023, 421.20000000298023, 429.20000000298023]
+# CHECK: === Basic Block Embeddings ===
+# CHECK: Function: add
+# CHECK: BB: entry
+# CHECK-NEXT: Embedding: [38.0, 40.0, 42.0]
+# CHECK: Function: conditional
+# CHECK: BB: entry
+# CHECK-NEXT: Embedding: [161.20000000298023, 163.20000000298023, 165.20000000298023]
+# CHECK: BB: exit
+# CHECK-NEXT: Embedding: [164.0, 166.0, 168.0]
+# CHECK: BB: negative
+# CHECK-NEXT: Embedding: [47.0, 49.0, 51.0]
+# CHECK: BB: positive
+# CHECK-NEXT: Embedding: [41.0, 43.0, 45.0]
+# CHECK: Function: multiply
+# CHECK: BB: entry
+# CHECK-NEXT: Embedding: [50.0, 52.0, 54.0]
diff --git a/llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp b/llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp
index 5032a053ce7b6..e334997b31394 100644
--- a/llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp
+++ b/llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp
@@ -119,6 +119,37 @@ class PyIR2VecTool {
return NbArray;
}
+
+ nb::dict getBBEmbMap(const std::string &FuncName) {
+ const Function *F = M->getFunction(FuncName);
+
+ if (!F)
+ throw nb::value_error(
+ ("Function '" + FuncName + "' not found in module").c_str());
+
+ auto ToolBBEmbMap = Tool->getBBEmbeddingsMap(*F, OutputEmbeddingMode);
+
+ if (!ToolBBEmbMap)
+ throw nb::value_error(toString(ToolBBEmbMap.takeError()).c_str());
+
+ nb::dict NbBBEmbMap;
+
+ for (const auto &[BBPtr, BBEmb] : *ToolBBEmbMap) {
+ auto BBEmbVec = BBEmb.getData();
+ double *NbBBEmbVec = new double[BBEmbVec.size()];
+ std::copy(BBEmbVec.begin(), BBEmbVec.end(), NbBBEmbVec);
+
+ auto NbArray = nb::ndarray<nb::numpy, double>(
+ NbBBEmbVec, {BBEmbVec.size()},
+ nb::capsule(NbBBEmbVec, [](void *P) noexcept {
+ delete[] static_cast<double *>(P);
+ }));
+
+ NbBBEmbMap[nb::str(BBPtr->getName().str().c_str())] = NbArray;
+ }
+
+ return NbBBEmbMap;
+ }
};
} // namespace
@@ -133,12 +164,16 @@ NB_MODULE(ir2vec, m) {
.def("getFuncEmbMap", &PyIR2VecTool::getFuncEmbMap,
"Generate function-level embeddings for all functions\n"
"Returns: dict[str, ndarray[float64]] - "
- "{function_name: embedding}")
+ "{function_name: embedding vector}")
.def("getFuncEmb", &PyIR2VecTool::getFuncEmb, nb::arg("funcName"),
"Generate embedding for a single function by name\n"
"Args: funcName (str) - IR-Name of the function\n"
- "Returns: ndarray[float64] - Function embedding vector");
-
+ "Returns: ndarray[float64] - Function embedding vector")
+ .def("getBBEmbMap", &PyIR2VecTool::getBBEmbMap, nb::arg("funcName"),
+ "Generate embeddings for all basic blocks in a function\n"
+ "Args: funcName (str) - IR-Name of the function\n"
+ "Returns: dict[str, ndarray[float64]] - "
+ "{basic_block_name: embedding vector}");
m.def(
"initEmbedding",
[](const std::string &filename, const std::string &mode,
diff --git a/llvm/tools/llvm-ir2vec/lib/Utils.cpp b/llvm/tools/llvm-ir2vec/lib/Utils.cpp
index 50b71d6c134d6..70f501c116407 100644
--- a/llvm/tools/llvm-ir2vec/lib/Utils.cpp
+++ b/llvm/tools/llvm-ir2vec/lib/Utils.cpp
@@ -191,6 +191,31 @@ IR2VecTool::getFunctionEmbeddingsMap(IR2VecKind Kind) const {
return Result;
}
+Expected<BBEmbeddingsMap>
+IR2VecTool::getBBEmbeddingsMap(const Function &F, IR2VecKind Kind) const {
+ if (!Vocab || !Vocab->isValid())
+ return createStringError(
+ errc::invalid_argument,
+ "Vocabulary is not valid. IR2VecTool not initialized.");
+
+ BBEmbeddingsMap Result;
+
+ if (F.isDeclaration())
+ return createStringError(errc::invalid_argument,
+ "Function is a declaration.");
+
+ auto Emb = Embedder::create(Kind, F, *Vocab);
+ if (!Emb)
+ return createStringError(errc::invalid_argument,
+ "Failed to create embedder for function '%s'.",
+ F.getName().str().c_str());
+
+ for (const BasicBlock &BB : F)
+ Result.try_emplace(&BB, Emb->getBBVector(BB));
+
+ return Result;
+}
+
void IR2VecTool::writeEmbeddingsToStream(raw_ostream &OS,
EmbeddingLevel Level) const {
if (!Vocab || !Vocab->isValid()) {
diff --git a/llvm/tools/llvm-ir2vec/lib/Utils.h b/llvm/tools/llvm-ir2vec/lib/Utils.h
index d535f5fd5bb74..04ec4a74b1e24 100644
--- a/llvm/tools/llvm-ir2vec/lib/Utils.h
+++ b/llvm/tools/llvm-ir2vec/lib/Utils.h
@@ -114,6 +114,9 @@ class IR2VecTool {
/// Returns EntityList containing all entity strings
static EntityList collectEntityMappings();
+ /// Dump entity ID to string mappings
+ static void writeEntitiesToStream(raw_ostream &OS);
+
// Get embedding for a single function
Expected<Embedding> getFunctionEmbedding(const Function &F,
IR2VecKind Kind) const;
@@ -121,8 +124,9 @@ class IR2VecTool {
/// Get embeddings for all functions in the module
Expected<FuncEmbMap> getFunctionEmbeddingsMap(IR2VecKind Kind) const;
- /// Dump entity ID to string mappings
- static void writeEntitiesToStream(raw_ostream &OS);
+ /// Get embeddings for all basic blocks in a function
+ Expected<BBEmbeddingsMap> getBBEmbeddingsMap(const Function &F,
+ IR2VecKind Kind) const;
/// Generate embeddings for the entire module
void writeEmbeddingsToStream(raw_ostream &OS, EmbeddingLevel Level) const;
More information about the llvm-commits
mailing list