Class: Leann::Backend::LeannGraph
- Inherits:
-
Object
- Object
- Leann::Backend::LeannGraph
- Defined in:
- lib/leann/backend/leann_graph.rb
Overview
LEANN Graph-only backend - stores only the HNSW graph structure Achieves ~97% storage reduction by not storing embeddings
Graph is stored as:
-
Node levels (which layers each node participates in)
-
Neighbor lists per level
-
Entry point and HNSW parameters
During search, embeddings are recomputed on-the-fly via API calls
Constant Summary collapse
- DEFAULT_M =
HNSW parameters
16- DEFAULT_EF_CONSTRUCTION =
Max connections per layer
200- DEFAULT_ML =
Build-time search width
1.0 / Math.log(DEFAULT_M)
Instance Attribute Summary collapse
-
#dimensions ⇒ Object
readonly
Returns the value of attribute dimensions.
-
#ef_construction ⇒ Object
readonly
Returns the value of attribute ef_construction.
-
#entry_point ⇒ Object
readonly
Returns the value of attribute entry_point.
-
#m ⇒ Object
readonly
Returns the value of attribute m.
-
#max_level ⇒ Object
readonly
Returns the value of attribute max_level.
-
#node_count ⇒ Object
readonly
Returns the value of attribute node_count.
Class Method Summary collapse
-
.load(path) ⇒ LeannGraph
Load graph from files.
Instance Method Summary collapse
-
#build(ids, embeddings) ⇒ self
Build the graph from embeddings After building, embeddings can be discarded.
-
#get_id(node_idx) ⇒ Object
Get document ID for a node index.
-
#get_idx(id) ⇒ Object
Get node index for a document ID.
-
#get_neighbors(node_idx, level) ⇒ Object
Get neighbors at a specific level.
-
#initialize(dimensions:, m: DEFAULT_M, ef_construction: DEFAULT_EF_CONSTRUCTION) ⇒ LeannGraph
constructor
A new instance of LeannGraph.
-
#load_from_files(path, meta) ⇒ Object
Load graph data from binary file.
-
#save(path) ⇒ Object
Save graph to files (no embeddings!).
-
#search(query_embedding, embedding_provider:, passages:, limit: 5, ef: nil) ⇒ Array<[String, Float]>
Search the graph using on-the-fly embedding computation.
Constructor Details
#initialize(dimensions:, m: DEFAULT_M, ef_construction: DEFAULT_EF_CONSTRUCTION) ⇒ LeannGraph
Returns a new instance of LeannGraph.
26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/leann/backend/leann_graph.rb', line 26 def initialize(dimensions:, m: DEFAULT_M, ef_construction: DEFAULT_EF_CONSTRUCTION) @dimensions = dimensions @m = m @m0 = m * 2 # Layer 0 has 2x connections @ef_construction = ef_construction @ml = 1.0 / Math.log(m) @nodes = [] # Array of node data {id:, level:} @id_to_idx = {} # Map document ID to node index @neighbors = [] # neighbors[idx][level] = [neighbor_indices] @entry_point = nil @max_level = -1 @node_count = 0 end |
Instance Attribute Details
#dimensions ⇒ Object (readonly)
Returns the value of attribute dimensions.
23 24 25 |
# File 'lib/leann/backend/leann_graph.rb', line 23 def dimensions @dimensions end |
#ef_construction ⇒ Object (readonly)
Returns the value of attribute ef_construction.
23 24 25 |
# File 'lib/leann/backend/leann_graph.rb', line 23 def ef_construction @ef_construction end |
#entry_point ⇒ Object (readonly)
Returns the value of attribute entry_point.
23 24 25 |
# File 'lib/leann/backend/leann_graph.rb', line 23 def entry_point @entry_point end |
#m ⇒ Object (readonly)
Returns the value of attribute m.
23 24 25 |
# File 'lib/leann/backend/leann_graph.rb', line 23 def m @m end |
#max_level ⇒ Object (readonly)
Returns the value of attribute max_level.
23 24 25 |
# File 'lib/leann/backend/leann_graph.rb', line 23 def max_level @max_level end |
#node_count ⇒ Object (readonly)
Returns the value of attribute node_count.
24 25 26 |
# File 'lib/leann/backend/leann_graph.rb', line 24 def node_count @node_count end |
Class Method Details
.load(path) ⇒ LeannGraph
Load graph from files
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 |
# File 'lib/leann/backend/leann_graph.rb', line 152 def self.load(path) graph_file = "#{path}.graph.bin" = "#{path}.graph.meta.json" raise IndexNotFoundError, "Graph file not found: #{graph_file}" unless File.exist?(graph_file) = JSON.parse(File.read(), symbolize_names: true) graph = new( dimensions: [:dimensions], m: [:m], ef_construction: [:ef_construction] ) graph.load_from_files(path, ) graph end |
Instance Method Details
#build(ids, embeddings) ⇒ self
Build the graph from embeddings After building, embeddings can be discarded
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/leann/backend/leann_graph.rb', line 47 def build(ids, ) raise ArgumentError, "IDs and embeddings must have same length" unless ids.length == .length return self if ids.empty? @node_count = ids.length puts "Building LEANN graph with #{@node_count} nodes (M=#{@m})..." ids.each_with_index do |id, idx| level = random_level @nodes << { id: id, level: level } @id_to_idx[id] = idx @neighbors << Array.new(level + 1) { [] } if @entry_point.nil? @entry_point = idx @max_level = level else # Insert node into graph insert_node(idx, [idx], , level) end print "." if (idx + 1) % 100 == 0 end puts "\nGraph built: #{@node_count} nodes, max_level=#{@max_level}" self end |
#get_id(node_idx) ⇒ Object
Get document ID for a node index
287 288 289 |
# File 'lib/leann/backend/leann_graph.rb', line 287 def get_id(node_idx) @nodes[node_idx][:id] end |
#get_idx(id) ⇒ Object
Get node index for a document ID
292 293 294 |
# File 'lib/leann/backend/leann_graph.rb', line 292 def get_idx(id) @id_to_idx[id] end |
#get_neighbors(node_idx, level) ⇒ Object
Get neighbors at a specific level
280 281 282 283 284 |
# File 'lib/leann/backend/leann_graph.rb', line 280 def get_neighbors(node_idx, level) return [] if node_idx >= @neighbors.length return [] if level >= @neighbors[node_idx].length @neighbors[node_idx][level] || [] end |
#load_from_files(path, meta) ⇒ Object
Load graph data from binary file
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 |
# File 'lib/leann/backend/leann_graph.rb', line 170 def load_from_files(path, ) graph_file = "#{path}.graph.bin" @node_count = [:node_count] @max_level = [:max_level] @entry_point = [:entry_point] File.open(graph_file, "rb") do |f| # Read node count node_count = f.read(8).unpack1("Q<") raise "Node count mismatch" unless node_count == @node_count # Read levels levels = f.read(@node_count * 4).unpack("l<*") # Read node IDs @nodes = [] @id_to_idx = {} @node_count.times do |idx| id_len = f.read(2).unpack1("S<") id = f.read(id_len).force_encoding("UTF-8") @nodes << { id: id, level: levels[idx] } @id_to_idx[id] = idx end # Read offsets offsets = f.read((@node_count + 1) * 8).unpack("Q<*") # Read level offsets level_offsets_count = f.read(8).unpack1("Q<") level_offsets = f.read(level_offsets_count * 8).unpack("Q<*") # Read all neighbors neighbors_count = f.read(8).unpack1("Q<") all_neighbors = f.read(neighbors_count * 4).unpack("l<*") # Reconstruct neighbor structure @neighbors = [] level_offset_idx = 0 @node_count.times do |idx| node_level = levels[idx] node_neighbors = [] base_offset = offsets[idx] (node_level + 1).times do |level| start_off = level_offsets[level_offset_idx] end_off = level_offsets[level_offset_idx + 1] level_offset_idx += 1 level_neighbors = all_neighbors[(base_offset + start_off)...(base_offset + end_off)] node_neighbors << (level_neighbors || []) end level_offset_idx += 1 # Skip end marker @neighbors << node_neighbors end end puts "Graph loaded: #{@node_count} nodes, max_level=#{@max_level}" end |
#save(path) ⇒ Object
Save graph to files (no embeddings!)
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 |
# File 'lib/leann/backend/leann_graph.rb', line 78 def save(path) graph_file = "#{path}.graph.bin" = "#{path}.graph.meta.json" # Save metadata = { version: "1.0", format: "leann_graph", node_count: @node_count, dimensions: @dimensions, m: @m, ef_construction: @ef_construction, max_level: @max_level, entry_point: @entry_point } File.write(, JSON.pretty_generate()) # Save graph in binary format File.open(graph_file, "wb") do |f| # Header f.write([@node_count].pack("Q<")) # uint64 node count # Node levels levels = @nodes.map { |n| n[:level] } f.write(levels.pack("l<*")) # int32 array # Node IDs (as length-prefixed strings) @nodes.each do |node| id_bytes = node[:id].to_s.encode("UTF-8") f.write([id_bytes.bytesize].pack("S<")) # uint16 length f.write(id_bytes) end # Neighbor lists (CSR-like format) # First: offsets into neighbor data for each node offsets = [] current_offset = 0 @neighbors.each do |node_neighbors| offsets << current_offset node_neighbors.each do |level_neighbors| current_offset += level_neighbors.length end end offsets << current_offset # Final offset f.write(offsets.pack("Q<*")) # uint64 array # Level offsets within each node level_offsets = [] @neighbors.each do |node_neighbors| level_offset = 0 node_neighbors.each do |level_neighbors| level_offsets << level_offset level_offset += level_neighbors.length end level_offsets << level_offset # End marker for this node end f.write([level_offsets.length].pack("Q<")) f.write(level_offsets.pack("Q<*")) # All neighbor indices (flattened) all_neighbors = @neighbors.flat_map { |nn| nn.flat_map { |ln| ln } } f.write([all_neighbors.length].pack("Q<")) f.write(all_neighbors.pack("l<*")) # int32 array end graph_size = File.size(graph_file) puts "Graph saved: #{format_bytes(graph_size)} (no embeddings stored!)" end |
#search(query_embedding, embedding_provider:, passages:, limit: 5, ef: nil) ⇒ Array<[String, Float]>
Search the graph using on-the-fly embedding computation
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 |
# File 'lib/leann/backend/leann_graph.rb', line 239 def search(, embedding_provider:, passages:, limit: 5, ef: nil) return [] if @entry_point.nil? ef ||= [limit * 2, 10].max # Cache for embeddings computed during this search = {} # Start from entry point, traverse down to layer 0 current = @entry_point current_dist = distance(, (current, , passages, )) # Greedy search from top layer down to layer 1 (@max_level).downto(1) do |level| changed = true while changed changed = false neighbors = get_neighbors(current, level) neighbors.each do |neighbor| neighbor_emb = (neighbor, , passages, ) neighbor_dist = distance(, neighbor_emb) if neighbor_dist < current_dist current = neighbor current_dist = neighbor_dist changed = true end end end end # Search layer 0 with ef-sized candidate set candidates = search_layer(, current, ef, 0, , passages, ) # Return top-k results, converted to similarity scores candidates .sort_by { |_, dist| dist } .first(limit) .map { |idx, dist| [@nodes[idx][:id], 1.0 - dist] } # Convert distance to similarity end |