You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm was investigating how to store the graph more compact and found something that improves the situation for wayGeometry. This is still in its early shape but basically uses a "vint" (see Lucene) with delta encoding like described in #234. To make this more effective the whole graph structure would need a change so that the "edge rows" would not need to be of same length. And this new graph storage (basically a persistent linked list that avoids duplicating edge information) would also allow a more efficient turn cost storage as 1. only the turn cost needs to be stored (no additional node id info) and 2. it would likely need only one byte per tc info. So we would want this if we start storing and reading turn costs for every junction.
It creates a new IntsRef object on every call, even though all it returns is a double
The funny or sad thing here is that the JVM seems to heavily optimize these things and for the wayGeometry work I found it did not make a difference if I reused or created the byte array. But here it could make a difference when we call it for every node in the algorithm and not only for the location lookup.
Ok cool :) Another thing that I thought could be useful in different places would be separating the graph topology (information about which edges are adjacent to which nodes) from the edge properties. So we could have a data structure that allows fast graph traversal and only gives us edge ids/keys (basically the nodeA/B and nextA/B columns from the edge storage) and then a separate storage for 'edge data'. Maybe this way it would be easier/more natural to a) 'attach' additional data to edges (simply by id) and b) to optimize the graph traversal for different use-cases. For example think of Dijkstra running for the car encoder. In principle we could build the (rather small) 'traversal' graph only including roads that are accessible for cars. This is a bit contrary to making the routing more 'flexible' (no access flags), but I do not yet see any disadvantage of this separation and at least things like this would be possible. Not sure just some thoughts, maybe you can take this into account when designing this new storage.
So we could have a data structure that allows fast graph traversal and only gives us edge ids/keys (basically the nodeA/B and nextA/B columns from the edge storage) and then a separate storage for 'edge data'.
Interestingly the new storage could also allow that. Let me sketch the storage roughly:
nodeRefs: a fixed length list of "pointers" into the edge area
edgeRefs: a fixed length list of "pointers" into the edge area
edge area:
neighboring nodes of nodeA | edge infos of nodeA->* | edgeRefs to edge infos for nodeA<-* to avoid duplicating this information | node info for nodeA | turn infos of nodeA->* | edgeRef for extension area (2)
neighboring nodes of nodeB | turn infos of nodeB->* | edge infos of nodeB->* | edgeRefs to edge infos for nodeB<-* | node info for nodeB | turn infos of nodeB->* for every | edgeRef for extension area (2)
...
There are many benefits to this structure:
likely much more cache friendly
likely more compact
likely extendable to a tiled-based structure
but also a couple of disadvantages that might or might not slow down the algorithms:
(1) every edge row has a different size and when we do not want to loose the property that every nodeId and edgeId fits into 4 bytes and is adjacent we need an additional hop from the edgeId via the edgeRefs array into the edge area. But for graph traversal this doesn't matter only for many getEdgeIteratorState lookups.
(2) "edgeRef for extension area" the storage needs a compaction call for the import, i.e. for every 10k edges we copy the linked list of edges into this "neighboring" edge format, i.e. the property "edgeRef for extension area" is unused afterwards. (info: something like would be required anyway for a tile-based storage format)
Another possible improvement would be providing an API to read the first (and maybe last) pillar node, because this is frequently needed to determine the orientation of a road at a junction. This is needed when calculating instructions, but also when we want to calculate turn costs depending on the sharpness of a turn (maybe this will be done on the fly during path calculation so its important to make this run very fast). Right now we call fetchWayGeometry and this takes a significant amount of time when calling /route when instructions are enabled even though we only need one (not all) pillar nodes.
To make this efficient we would need to store the geometry twice (one per direction) or without delta encoding like now. But when we want delta encoding (+vint) and want to store only one geometry per edge there is no efficient way to get the last pillar node. Still we could store the angle explicitly (e.g. as a turn cost), so we would also avoid expensive triangular operations while routing or path expanding.
Ah yes I already thought so. But I can imagine a 'bidirectional' version of the delta encoding? Then again storing the orientation of both sides of the edge would also be very cheap (just two numbers in the range of 0-3600 or something) and like you said we would even save calculating these angles.
Another thought: Currently we are not expanding the paths very efficiently: For example we first use Path#forEveryEdge just to get the coordinates. Then we do the same for instructions, path details etc. It would probably be better to only traverse the path once and extract all the information we want in one go. But maybe this becomes less of an issue with #1847.
But I can imagine a 'bidirectional' version of the delta encoding?
For the delta coding: yes, this is possible, e.g. we could store just the delta towards the first pillar node (or even just the delta towards the tower node). But the problem is the vint: when you write a number then you do not know up front how many bytes it needs and so you would need to store a pointer to where the last pillar node is stored which would likely make the format a bit inefficient.
and like you said we would even save calculating these angles.
Especially as these angle calculations could also look about the real angle of the two edges - often the first pillar node is just a slight beginning of a sharp turn or similar.
For example we first use Path#forEveryEdge just to get the coordinates. Then we do the same for instructions, path details etc.
Especially as these angle calculations could also look about the real angle of the two edges - often the first pillar node is just a slight beginning of a sharp turn or similar.
Yes, agreed. It seems much better to determine the orientation of every edge on both ends (based on all or as many as needed pillar nodes) and store this with the edge.
Sure, have also done this partly. Still the priority of certain requirements are different:
In the past we favored speed over everything else and we relaxed this requirement only a bit, because a more compact in-memory representation can also mean a higher speed ;)
we want the edge and node IDs to be adjacent to make it easy for consumers of our Java API to store helper information in a fast, simple and compact way: in an array (or DataAccess).
we do not need a tile structure (yet). This requirement also contradicts a bit with point 2, but we could still have "somewhat adjacent IDs" with the approach above, likely still faster and more compact than a HashMap. But again, without community work this won't be a priority for us (see Future of 'Offline' Routing #1940).
I've done some preliminary tests and the new format currently requires +30% more storage. But will try to optimize this and interestingly this could be possible with a tiled-graph as we can use much smaller pointers (2 bytes?) within one tile. But the complexity for such a graph storage is much higher.
Also it would mean to switch to long edgeIds and nodeId which are not adjacent. This would basically prevent us from using an external storage (we would have to offer the possibilities to store external data like OSM IDs etc) because fetching the data with a hashmap (5x) or mapdb 1.0.8 (25x) is much slower (tested with 20 million random reads) and obviously costs much more memory. (btw: reading from a large int array was slightly, but predictable slower than reading from our DataAccess which is interesting as DataAccess has some overhead regarding the access index calculation)
write DataAccess (50 iters): 0.27s (including flush: 0.5s)
read DataAccess (10 iters): 1.99s (read is random access)
write array (50 iters): 0.26s
read array (10 iters): 2.05s
write DBMaker (1 iters): 72s (via DBMaker.newFileDB(new File("/tmp/blupmapdb")).mmapFileEnable().transactionDisable().make(); but MapDB has Pump for fast bulk import of collections)
read DBMaker (2 iters): 54s
write BTreeMap<Long,?> (1 iters): 53s
read BTreeMap<Long,?> (2 iters): 50s
write HashMap (1 iters): 2.7s
read HashMap (10 iters): 11.5s
One benefit of edge attributes separate from topology would be that it would allow different attributes for different types of edges without wasting memory, like a union. Very useful for public transit.
Not having this was one of my reasons for using external storage in the first place.
we can use much smaller pointers (2 bytes?) within one tile
Also it would mean to switch to long edgeIds and nodeId which are not adjacent.
If we can use 2 bytes to address within a single tile(relative address) why can't we add a 2 byte prefix as the tile address? The overall address space would still be 4 bytes.
Sorry if i'm asking stupid questions but i'm genuinely curious.
reading from a large int array was slightly, but predictable slower
Hmm. Now I played myself, and I can't reproduce that. This is what I get (measuring throughput in ops/s here, since that's what JMH does by default):
All data structures have 200_000_000 ints. I fill them (not measured), and then I exercise them, reading by random access, for 5 seconds and measure throughput, for 5 trials. testNothing only draws a random index.
Please review me, I've never done this before.
REMEMBER: The numbers below are just data. To gain reusable insights, you need to follow up on
why the numbers are the way they are. Use profilers (see -prof, -lprof), design factorial
experiments, perform baseline and negative tests that provide experimental control, make sure
the benchmarking environment is safe on JVM/OS/HW level, ask for reviews from the domain experts.
Do not assume the numbers tell you what you want them to tell.
Benchmark Mode Cnt Score Error Units
MyBenchmark.testArray thrpt 5 9678253,129 ± 1711305,919 ops/s
MyBenchmark.testDA thrpt 5 7875590,512 ± 536350,570 ops/s
MyBenchmark.testMap thrpt 5 5649702,959 ± 537668,032 ops/s
MyBenchmark.testNothing thrpt 5 76826032,375 ± 4574191,535 ops/s
Finding: DA is significantly, but not much, slower. IntIntHashMap is also pretty good, but this is not a good exercise for it, since if you pack values, you don't need a Map. A sparseLongIntHashMap would be more interesting.
Repeating, going 10 seconds per trial (coming closer to covering the entire data set while reading), and putting MMapDataAccess into the mix:
REMEMBER: The numbers below are just data. To gain reusable insights, you need to follow up on
why the numbers are the way they are. Use profilers (see -prof, -lprof), design factorial
experiments, perform baseline and negative tests that provide experimental control, make sure
the benchmarking environment is safe on JVM/OS/HW level, ask for reviews from the domain experts.
Do not assume the numbers tell you what you want them to tell.
Benchmark Mode Cnt Score Error Units
MyBenchmark.testArray thrpt 5 10975510,299 ± 7950888,008 ops/s
MyBenchmark.testDA thrpt 5 7431124,160 ± 1602688,106 ops/s
MyBenchmark.testMDA thrpt 5 8992418,704 ± 126207,552 ops/s
MyBenchmark.testMap thrpt 5 5634964,787 ± 789737,086 ops/s
MyBenchmark.testNothing thrpt 5 75231685,281 ± 2779523,020 ops/s
Where an OS-managed direct buffer is actually faster than a self-segmented array of arrays, which is what I would have predicted makes some sense if you ask me, but now nothing is significant anymore.
This is all so wiggly I don't trust it yet. It also looked like it was still getting faster over time. Need more and longer iterations, I guess.
And since this is not what we observe while we're routing, I'm clearly not measuring the right thing yet.
testDA has a pretty high error range. This might explain why the testMDA seems to score better. Moving the random value generation into a setup method could probably lead to more precise results.
My expectation: testNothing>>>>testArray>>>testDA>testMDA>>testMap
@michaz interesting - thanks! Now that the array stuff is faster like expected I will have to go back to see what I did and why it was slower.
Please review me, I've never done this before.
I can reproduce your numbers and the benchmark looks good. The high error rate in your case looks a bit strange - can you retry with a higher warmup? I used 3 instead of 1.
I have slightly rewritten the benchmark to avoid creating the test data multiple times and always have the same random numbers for all benchmarks.
Where an OS-managed direct buffer is actually faster than a self-segmented array of arrays,
The high speed of the MMapDataAccess is very surprising to me as it has the "synchronized" overhead and we get different numbers if you use this DAType for a "normal" GraphHopper benchmark. Plus in worst case it has to access the data from disk instead of RAM. But probably in this micro benchmark the JIT can remove the synchronized and all accesses are in RAM.
Please also note that the speed tests are not the only deciding factor. Most hashmap implementations (also hppc) have the disadvantages that they require 9x more RAM in worst case than our DataAccess:
maps need 2x more RAM when the indices are adjacent because you need to store key and value. For java's normal HashMap it is even worse due to the boxed integers.
the backing array of a map is ~25% larger to reduce hash collision; and in case of hppc it seems that the backing array is even much larger as they do length = Math.max(MIN_HASH_ARRAY_LENGTH, BitUtil.nextHighestPowerOfTwo(length)); which is especially bad for large maps. -> 1.5x more RAM
at some point the backing array is no longer sufficient and you need 3x of the actual memory and also loose some speed, because hppc (and most other implementations) allocate a twice-as-large backing array and do a copy & rehash. (Similar problem if we would use a simple array and would have to increase it)
So hashmaps will be slower and more memory demanding, which we would have to save with a potential new graph format, which is tough.
One benefit of edge attributes separate from topology would be that it would allow different attributes for different types of edges without wasting memory, like a union.
My plan for this was to refactor the StringIndex into a more generic ByteIndex - actually this should be pretty easy. Would it help you to be able to store a byte array per edge?
If we can use 2 bytes to address within a single tile(relative address) why can't we add a 2 byte prefix as the tile address? The overall address space would still be 4 bytes.
@otbutz Interesting. It might work. 2 bytes means there would be 65k tiles and 2 bytes per tile means we have a maximum number of edges per tile, so the node IDs will get a certain gap (if there are more nodes we have the gap for the edge IDs). We have currently around 330 mio edges and 250 mio nodes, so we would need around 5000 tiles and if the gap is also 25% on average it could fit. (if we allow only signed ints to make normal arrays working and like it is the current state we would have only 32k tiles)
Would it help you to be able to store a byte array per edge?
OMG yes.
Except that I won't be the only one. Meaning, very soon, n people (or n parts of the software) will want to store a byte array per edge. Don't know if that's already taken into account. :)
To avoid yet another external storage I converted the StringIndex into a storage that is able to store a Map<String, Object> where the Object can currently be String, byte[], int, long, double or float. It tries to store them as compact as possible (len+value) and stores only the pointer if it is a duplicate but stores only the value without len if it is int, long, double or float. So storing the osm_way_id requires only 2+8 bytes per edge (key+value).
The API is currently:
Map<String, Object> map = new HashMap<>();
map.put("street_name", "some name");
map.put("mykey", byteArray);
edge.setKeyValues(map);
// get it via internally looping through all keys:
edge.getValue("mykey");
// or 'deserialize' everything if more than one key is required:
edge.getKeyValues().get("mykey");
Activity
easbar commentedon Jul 15, 2020
From @karussell (originally in #2084):
I'm was investigating how to store the graph more compact and found something that improves the situation for wayGeometry. This is still in its early shape but basically uses a "vint" (see Lucene) with delta encoding like described in #234. To make this more effective the whole graph structure would need a change so that the "edge rows" would not need to be of same length. And this new graph storage (basically a persistent linked list that avoids duplicating edge information) would also allow a more efficient turn cost storage as 1. only the turn cost needs to be stored (no additional node id info) and 2. it would likely need only one byte per tc info. So we would want this if we start storing and reading turn costs for every junction.
The funny or sad thing here is that the JVM seems to heavily optimize these things and for the wayGeometry work I found it did not make a difference if I reused or created the byte array. But here it could make a difference when we call it for every node in the algorithm and not only for the location lookup.
easbar commentedon Jul 15, 2020
Ok cool :) Another thing that I thought could be useful in different places would be separating the graph topology (information about which edges are adjacent to which nodes) from the edge properties. So we could have a data structure that allows fast graph traversal and only gives us edge ids/keys (basically the
nodeA/BandnextA/Bcolumns from the edge storage) and then a separate storage for 'edge data'. Maybe this way it would be easier/more natural to a) 'attach' additional data to edges (simply by id) and b) to optimize the graph traversal for different use-cases. For example think of Dijkstra running for the car encoder. In principle we could build the (rather small) 'traversal' graph only including roads that are accessible for cars. This is a bit contrary to making the routing more 'flexible' (no access flags), but I do not yet see any disadvantage of this separation and at least things like this would be possible. Not sure just some thoughts, maybe you can take this into account when designing this new storage.karussell commentedon Jul 15, 2020
Interestingly the new storage could also allow that. Let me sketch the storage roughly:
There are many benefits to this structure:
but also a couple of disadvantages that might or might not slow down the algorithms:
easbar commentedon Jul 16, 2020
Another possible improvement would be providing an API to read the first (and maybe last) pillar node, because this is frequently needed to determine the orientation of a road at a junction. This is needed when calculating instructions, but also when we want to calculate turn costs depending on the sharpness of a turn (maybe this will be done on the fly during path calculation so its important to make this run very fast). Right now we call
fetchWayGeometryand this takes a significant amount of time when calling/routewhen instructions are enabled even though we only need one (not all) pillar nodes.karussell commentedon Jul 16, 2020
To make this efficient we would need to store the geometry twice (one per direction) or without delta encoding like now. But when we want delta encoding (+vint) and want to store only one geometry per edge there is no efficient way to get the last pillar node. Still we could store the angle explicitly (e.g. as a turn cost), so we would also avoid expensive triangular operations while routing or path expanding.
easbar commentedon Jul 16, 2020
Ah yes I already thought so. But I can imagine a 'bidirectional' version of the delta encoding? Then again storing the orientation of both sides of the edge would also be very cheap (just two numbers in the range of 0-3600 or something) and like you said we would even save calculating these angles.
Another thought: Currently we are not expanding the paths very efficiently: For example we first use
Path#forEveryEdgejust to get the coordinates. Then we do the same for instructions, path details etc. It would probably be better to only traverse the path once and extract all the information we want in one go. But maybe this becomes less of an issue with #1847.karussell commentedon Jul 16, 2020
For the delta coding: yes, this is possible, e.g. we could store just the delta towards the first pillar node (or even just the delta towards the tower node). But the problem is the vint: when you write a number then you do not know up front how many bytes it needs and so you would need to store a pointer to where the last pillar node is stored which would likely make the format a bit inefficient.
Especially as these angle calculations could also look about the real angle of the two edges - often the first pillar node is just a slight beginning of a sharp turn or similar.
Yeah, indeed suboptimal.
easbar commentedon Jul 16, 2020
Yes, agreed. It seems much better to determine the orientation of every edge on both ends (based on all or as many as needed pillar nodes) and store this with the edge.
otbutz commentedon Jul 17, 2020
Taking a sneak peak at other open source projects might also be a good idea: https://valhalla.readthedocs.io/en/latest/tiles/
karussell commentedon Jul 17, 2020
Sure, have also done this partly. Still the priority of certain requirements are different:
HashMap. But again, without community work this won't be a priority for us (see Future of 'Offline' Routing #1940).karussell commentedon Jul 20, 2020
I've done some preliminary tests and the new format currently requires +30% more storage. But will try to optimize this and interestingly this could be possible with a tiled-graph as we can use much smaller pointers (2 bytes?) within one tile. But the complexity for such a graph storage is much higher.
Also it would mean to switch to
longedgeIds and nodeId which are not adjacent. This would basically prevent us from using an external storage (we would have to offer the possibilities to store external data like OSM IDs etc) because fetching the data with a hashmap (5x) or mapdb 1.0.8 (25x) is much slower (tested with 20 million random reads) and obviously costs much more memory. (btw: reading from a large int array was slightly, but predictable slower than reading from our DataAccess which is interesting as DataAccess has some overhead regarding the access index calculation)test code:
(absolute values are not so interesting as this was done on an older laptop but already with SSD)
michaz commentedon Jul 23, 2020
One benefit of edge attributes separate from topology would be that it would allow different attributes for different types of edges without wasting memory, like a
union. Very useful for public transit.Not having this was one of my reasons for using external storage in the first place.
otbutz commentedon Aug 13, 2020
If we can use 2 bytes to address within a single tile(relative address) why can't we add a 2 byte prefix as the tile address? The overall address space would still be 4 bytes.
Sorry if i'm asking stupid questions but i'm genuinely curious.
michaz commentedon Aug 18, 2020
Hmm. Now I played myself, and I can't reproduce that. This is what I get (measuring throughput in ops/s here, since that's what JMH does by default):
All data structures have 200_000_000 ints. I fill them (not measured), and then I exercise them, reading by random access, for 5 seconds and measure throughput, for 5 trials.
testNothingonly draws a random index.Please review me, I've never done this before.
Finding: DA is significantly, but not much, slower.
IntIntHashMapis also pretty good, but this is not a good exercise for it, since if you pack values, you don't need a Map. A sparseLongIntHashMapwould be more interesting.Code.
michaz commentedon Aug 18, 2020
Repeating, going 10 seconds per trial (coming closer to covering the entire data set while reading), and putting
MMapDataAccessinto the mix:Where an OS-managed direct buffer is actually faster than a self-segmented array of arrays, which
is what I would have predictedmakes some sense if you ask me, but now nothing is significant anymore.This is all so wiggly I don't trust it yet. It also looked like it was still getting faster over time. Need more and longer iterations, I guess.
And since this is not what we observe while we're routing, I'm clearly not measuring the right thing yet.
otbutz commentedon Aug 18, 2020
I'd preload the random values using a
@Setupannotated method. Otherwise you're adding that overhead to your benchmark values.michaz commentedon Aug 18, 2020
Is that a problem if this is done for all cases and I'm interested in relative performance?
otbutz commentedon Aug 18, 2020
It should be ok for relative performance as it's still a pseudo-random generator so there won't be any entropy bottlenecks or something like that.
otbutz commentedon Aug 18, 2020
testDAhas a pretty high error range. This might explain why thetestMDAseems to score better. Moving the random value generation into a setup method could probably lead to more precise results.My expectation: testNothing>>>>testArray>>>testDA>testMDA>>testMap
karussell commentedon Aug 25, 2020
@michaz interesting - thanks! Now that the array stuff is faster like expected I will have to go back to see what I did and why it was slower.
I can reproduce your numbers and the benchmark looks good. The high error rate in your case looks a bit strange - can you retry with a higher warmup? I used 3 instead of 1.
I have slightly rewritten the benchmark to avoid creating the test data multiple times and always have the same random numbers for all benchmarks.
The high speed of the MMapDataAccess is very surprising to me as it has the "synchronized" overhead and we get different numbers if you use this DAType for a "normal" GraphHopper benchmark. Plus in worst case it has to access the data from disk instead of RAM. But probably in this micro benchmark the JIT can remove the
synchronizedand all accesses are in RAM.Please also note that the speed tests are not the only deciding factor. Most hashmap implementations (also hppc) have the disadvantages that they require 9x more RAM in worst case than our DataAccess:
length = Math.max(MIN_HASH_ARRAY_LENGTH, BitUtil.nextHighestPowerOfTwo(length));which is especially bad for large maps. -> 1.5x more RAMSo hashmaps will be slower and more memory demanding, which we would have to save with a potential new graph format, which is tough.
My plan for this was to refactor the StringIndex into a more generic ByteIndex - actually this should be pretty easy. Would it help you to be able to store a byte array per edge?
@otbutz Interesting. It might work. 2 bytes means there would be 65k tiles and 2 bytes per tile means we have a maximum number of edges per tile, so the node IDs will get a certain gap (if there are more nodes we have the gap for the edge IDs). We have currently around 330 mio edges and 250 mio nodes, so we would need around 5000 tiles and if the gap is also 25% on average it could fit. (if we allow only signed ints to make normal arrays working and like it is the current state we would have only 32k tiles)
btw: valhalla uses 43 bits for this.
michaz commentedon Aug 26, 2020
OMG yes.
Except that I won't be the only one. Meaning, very soon, n people (or n parts of the software) will want to store a byte array per edge. Don't know if that's already taken into account. :)
karussell commentedon Dec 29, 2020
@michaz It is still a work in progress but so far it seems to work and might make other things also easier (store
refinto separate field) and possible (storing the osm_way_id): https://github.com/graphhopper/graphhopper/compare/byteindexTo avoid yet another external storage I converted the StringIndex into a storage that is able to store a
Map<String, Object>where the Object can currently beString,byte[], int, long, double or float. It tries to store them as compact as possible (len+value) and stores only the pointer if it is a duplicate but stores only the value without len if it is int, long, double or float. So storing the osm_way_id requires only 2+8 bytes per edge (key+value).The API is currently:
update: see now #2597