[llvm] [llvm-ir2vec] Adding BB Embeddings Map API to ir2vec python bindings (PR #180135)
via llvm-commits
llvm-commits at lists.llvm.org
Thu Feb 5 23:54:26 PST 2026
llvmbot wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-mlgo
Author: Nishant Sachdeva (nishant-sachdeva)
<details>
<summary>Changes</summary>
- returns a nested map indexed by functions
---
Full diff: https://github.com/llvm/llvm-project/pull/180135.diff
4 Files Affected:
- (modified) llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py (+48)
- (modified) llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp (+74-8)
- (modified) llvm/tools/llvm-ir2vec/lib/Utils.cpp (+44)
- (modified) llvm/tools/llvm-ir2vec/lib/Utils.h (+8)
``````````diff
diff --git a/llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py b/llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py
index a209a47cba42e..6461b73738c7d 100644
--- a/llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py
+++ b/llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py
@@ -22,6 +22,34 @@
print(f"Function: {func_name}")
print(f" Embedding: {emb.tolist()}")
+ # Test getFuncEmb for individual functions
+ print("\n=== Single Function Embeddings ===")
+
+ # Test valid function names
+ for func_name in ["add", "multiply", "conditional"]:
+ func_emb = tool.getFuncEmb(func_name)
+ print(f"Function: {func_name}")
+ print(f" Embedding: {func_emb.tolist()}")
+
+ # Test getBBEmbMap
+ print("\n=== Basic Block Embeddings ===")
+ bb_emb_map = tool.getBBEmbMap()
+
+ # Sorting by function name, then BB name, then embedding values for deterministic output
+ bb_sorted = []
+ for func_name in sorted(bb_emb_map.keys()):
+ func_bb_map = bb_emb_map[func_name]
+ for bb_name in sorted(func_bb_map.keys()):
+ emb = func_bb_map[bb_name]
+ bb_sorted.append((bb_name, emb))
+
+ # Sort the flattened list by BB name, then embedding values
+ bb_sorted = sorted(bb_sorted, key=lambda x: (x[0], tuple(x[1].tolist())))
+
+ for bb_name, emb in bb_sorted:
+ print(f"BB: {bb_name}")
+ print(f" Embedding: {emb.tolist()}")
+
# CHECK: SUCCESS: Tool initialized
# CHECK: Tool type: IR2VecTool
# CHECK: === Function Embeddings ===
@@ -31,3 +59,23 @@
# CHECK-NEXT: Embedding: [413.20000000298023, 421.20000000298023, 429.20000000298023]
# CHECK: Function: multiply
# CHECK-NEXT: Embedding: [50.0, 52.0, 54.0]
+# CHECK: === Single Function Embeddings ===
+# CHECK: Function: add
+# CHECK-NEXT: Embedding: [38.0, 40.0, 42.0]
+# CHECK: Function: multiply
+# 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: BB: entry
+# CHECK-NEXT: Embedding: [38.0, 40.0, 42.0]
+# CHECK: BB: entry
+# CHECK-NEXT: Embedding: [50.0, 52.0, 54.0]
+# 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]
diff --git a/llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp b/llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp
index 08a0844b44eef..1210d7775186f 100644
--- a/llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp
+++ b/llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp
@@ -76,23 +76,79 @@ class PyIR2VecTool {
if (!ToolFuncEmbMap)
throw nb::value_error(toString(ToolFuncEmbMap.takeError()).c_str());
- nb::dict NBFuncEmbMap;
+ nb::dict NbFuncEmbMap;
for (const auto &[FuncPtr, FuncEmb] : *ToolFuncEmbMap) {
auto FuncEmbVec = FuncEmb.getData();
- double *NBFuncEmbVec = new double[FuncEmbVec.size()];
- std::copy(FuncEmbVec.begin(), FuncEmbVec.end(), NBFuncEmbVec);
+ double *NbFuncEmbVec = new double[FuncEmbVec.size()];
+ std::copy(FuncEmbVec.begin(), FuncEmbVec.end(), NbFuncEmbVec);
auto NbArray = nb::ndarray<nb::numpy, double>(
- NBFuncEmbVec, {FuncEmbVec.size()},
- nb::capsule(NBFuncEmbVec, [](void *P) noexcept {
+ NbFuncEmbVec, {FuncEmbVec.size()},
+ nb::capsule(NbFuncEmbVec, [](void *P) noexcept {
delete[] static_cast<double *>(P);
}));
- NBFuncEmbMap[nb::str(FuncPtr->getName().str().c_str())] = NbArray;
+ NbFuncEmbMap[nb::str(FuncPtr->getName().str().c_str())] = NbArray;
}
- return NBFuncEmbMap;
+ return NbFuncEmbMap;
+ }
+
+ nb::ndarray<nb::numpy, double> getFuncEmb(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 ToolFuncEmb = Tool->getFunctionEmbedding(*F, OutputEmbeddingMode);
+
+ if (!ToolFuncEmb)
+ throw nb::value_error(toString(ToolFuncEmb.takeError()).c_str());
+
+ auto FuncEmbVec = ToolFuncEmb->getData();
+ double *NbFuncEmbVec = new double[FuncEmbVec.size()];
+ std::copy(FuncEmbVec.begin(), FuncEmbVec.end(), NbFuncEmbVec);
+
+ auto NbArray = nb::ndarray<nb::numpy, double>(
+ NbFuncEmbVec, {FuncEmbVec.size()},
+ nb::capsule(NbFuncEmbVec, [](void *P) noexcept {
+ delete[] static_cast<double *>(P);
+ }));
+
+ return NbArray;
+ }
+
+ nb::dict getBBEmbMap() {
+ auto ToolFuncBBEmbMap = Tool->getFuncBBEmbMap(OutputEmbeddingMode);
+
+ if (!ToolFuncBBEmbMap)
+ throw nb::value_error(toString(ToolFuncBBEmbMap.takeError()).c_str());
+
+ nb::dict NbFuncBBEmbMap;
+
+ for (const auto &[FuncPtr, BBMap] : *ToolFuncBBEmbMap) {
+ nb::dict NbFuncBBMap;
+
+ for (const auto &[BBPtr, BBEmb] : BBMap) {
+ 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);
+ }));
+
+ NbFuncBBMap[nb::str(BBPtr->getName().str().c_str())] = NbArray;
+ }
+
+ NbFuncBBEmbMap[nb::str(FuncPtr->getName().str().c_str())] = NbFuncBBMap;
+ }
+
+ return NbFuncBBEmbMap;
}
};
@@ -108,7 +164,17 @@ 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}")
+ .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")
+ .def("getBBEmbMap", &PyIR2VecTool::getBBEmbMap,
+ "Generate embeddings for all basic blocks in the module\n"
+ "Returns: dict[str, dict[str, ndarray[float64]]] - Nested "
+ "dictionary mapping "
+ "function names to dictionaries of basic block names to embedding "
+ "vectors");
m.def(
"initEmbedding",
diff --git a/llvm/tools/llvm-ir2vec/lib/Utils.cpp b/llvm/tools/llvm-ir2vec/lib/Utils.cpp
index 50b71d6c134d6..7d2c8d14985e0 100644
--- a/llvm/tools/llvm-ir2vec/lib/Utils.cpp
+++ b/llvm/tools/llvm-ir2vec/lib/Utils.cpp
@@ -191,6 +191,50 @@ IR2VecTool::getFunctionEmbeddingsMap(IR2VecKind Kind) const {
return Result;
}
+Expected<BBEmbeddingsMap> IR2VecTool::getBBEmbMap(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;
+}
+
+Expected<FuncBBEmbMap> IR2VecTool::getFuncBBEmbMap(IR2VecKind Kind) const {
+ if (!Vocab || !Vocab->isValid())
+ return createStringError(
+ errc::invalid_argument,
+ "Vocabulary is not valid. IR2VecTool not initialized.");
+
+ FuncBBEmbMap Result;
+
+ for (const Function &F : M.getFunctionDefs()) {
+ auto FuncBBVecs = getBBEmbMap(F, Kind);
+ if (!FuncBBVecs)
+ return FuncBBVecs.takeError();
+
+ Result.try_emplace(&F, std::move(*FuncBBVecs));
+ }
+
+ 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..7797a7b2a77ed 100644
--- a/llvm/tools/llvm-ir2vec/lib/Utils.h
+++ b/llvm/tools/llvm-ir2vec/lib/Utils.h
@@ -74,6 +74,7 @@ struct TripletResult {
/// Entity mappings: [entity_name]
using EntityList = std::vector<std::string>;
using FuncEmbMap = DenseMap<const Function *, ir2vec::Embedding>;
+using FuncBBEmbMap = DenseMap<const Function *, ir2vec::BBEmbeddingsMap>;
namespace ir2vec {
@@ -121,6 +122,13 @@ class IR2VecTool {
/// Get embeddings for all functions in the module
Expected<FuncEmbMap> getFunctionEmbeddingsMap(IR2VecKind Kind) const;
+ /// Get embeddings for all basic blocks in a function
+ Expected<BBEmbeddingsMap> getBBEmbMap(const Function &F,
+ IR2VecKind Kind) const;
+
+ /// Get embeddings for all basic blocks in the module, organized by function
+ Expected<FuncBBEmbMap> getFuncBBEmbMap(IR2VecKind Kind) const;
+
/// Dump entity ID to string mappings
static void writeEntitiesToStream(raw_ostream &OS);
``````````
</details>
https://github.com/llvm/llvm-project/pull/180135
More information about the llvm-commits
mailing list