-
Notifications
You must be signed in to change notification settings - Fork 24
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implement viewing sharded neuroglancer precomputed datasets #6920
Merged
Changes from 7 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
d7ddc07
Implement compressed morton code
frcroth 89ccc3d
Implement sharding based on webknossos-connect
frcroth 352294f
Fix some bugs in sharding
frcroth a81d1e6
Fix sharding for mags with only one shard file
frcroth 4351977
Use chunkContentsCache for sharded data
frcroth 39bd078
Add comments
frcroth f799422
Perf: fix chunk cache key, load source chunks in parallel, align hist…
fm3 5ac2fb7
Merge branch 'master' into sharding
frcroth 84979ec
Use one interface of chunk reader for sharded and unsharded
frcroth ae080a4
Update changelog
frcroth 2f2d15c
Merge branch 'master' into sharding
frcroth File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
package backend | ||
|
||
import com.scalableminds.webknossos.datastore.datareaders.precomputed.CompressedMortonCode | ||
import org.scalatestplus.play.PlaySpec | ||
|
||
class CompressedMortonCodeTestSuite extends PlaySpec { | ||
|
||
"Compressed Morton Code" when { | ||
"Grid size = 10,10,10" should { | ||
val grid_size = Array(10, 10, 10) | ||
"encode 0,0,0" in { | ||
assert(CompressedMortonCode.encode(Array(0, 0, 0), grid_size) == 0) | ||
} | ||
"encode 1,2,3" in { | ||
assert(CompressedMortonCode.encode(Array(1, 2, 3), grid_size) == 53) | ||
} | ||
"encode 9,9,9" in { | ||
assert(CompressedMortonCode.encode(Array(9, 9, 9), grid_size) == 3591) | ||
} | ||
"encode 10,10,10" in { | ||
assert(CompressedMortonCode.encode(Array(10, 10, 10), grid_size) == 3640) | ||
} | ||
} | ||
"Grid size = 2048,2048,1024" should { | ||
val grid_size = Array(2048, 2048, 1024) | ||
"encode 0,0,0" in { | ||
assert(CompressedMortonCode.encode(Array(0, 0, 0), grid_size) == 0) | ||
} | ||
"encode 1,2,3" in { | ||
assert(CompressedMortonCode.encode(Array(1, 2, 3), grid_size) == 53) | ||
} | ||
"encode 1024, 512, 684" in { | ||
assert(CompressedMortonCode.encode(Array(1024, 512, 684), grid_size) == 1887570176) | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
39 changes: 39 additions & 0 deletions
39
...com/scalableminds/webknossos/datastore/datareaders/precomputed/CompressedMortonCode.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
package com.scalableminds.webknossos.datastore.datareaders.precomputed | ||
|
||
import scala.math.log10 | ||
|
||
object CompressedMortonCode { | ||
|
||
def log2(x: Double): Double = log10(x) / log10(2.0) | ||
|
||
def encode(position: Array[Int], gridSize: Array[Int]): Long = { | ||
/* | ||
Computes the compressed morton code as per | ||
https://github.com/google/neuroglancer/blob/master/src/neuroglancer/datasource/precomputed/volume.md#compressed-morton-code | ||
https://github.com/google/neuroglancer/blob/162b698f703c86e0b3e92b8d8e0cacb0d3b098df/src/neuroglancer/util/zorder.ts#L72 | ||
*/ | ||
val bits = gridSize.map(log2(_).ceil.toInt) | ||
val maxBits = bits.max | ||
var outputBit = 0L | ||
val one = 1L | ||
|
||
var output = 0L | ||
for (bit <- 0 to maxBits) { | ||
if (bit < bits(0)) { | ||
output |= (((position(0) >> bit) & one) << outputBit) | ||
outputBit += 1 | ||
} | ||
if (bit < bits(1)) { | ||
output |= (((position(1) >> bit) & one) << outputBit) | ||
outputBit += 1 | ||
} | ||
if (bit < bits(2)) { | ||
output |= (((position(2) >> bit) & one) << outputBit) | ||
outputBit += 1 | ||
} | ||
} | ||
|
||
output | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||||||
---|---|---|---|---|---|---|---|---|---|---|
@@ -1,12 +1,19 @@ | ||||||||||
package com.scalableminds.webknossos.datastore.datareaders.precomputed | ||||||||||
|
||||||||||
import com.scalableminds.util.cache.AlfuFoxCache | ||||||||||
import com.scalableminds.util.tools.Fox | ||||||||||
import com.scalableminds.webknossos.datastore.datareaders.{AxisOrder, ChunkReader, DatasetArray, DatasetPath} | ||||||||||
import com.scalableminds.webknossos.datastore.datavault.VaultPath | ||||||||||
import com.typesafe.scalalogging.LazyLogging | ||||||||||
import play.api.libs.json.{JsError, JsSuccess, Json} | ||||||||||
|
||||||||||
import java.io.IOException | ||||||||||
import java.nio.ByteOrder | ||||||||||
|
||||||||||
import java.nio.ByteBuffer | ||||||||||
import java.nio.charset.StandardCharsets | ||||||||||
import scala.collection.immutable.NumericRange | ||||||||||
import scala.concurrent.{ExecutionContext, Future} | ||||||||||
|
||||||||||
object PrecomputedArray extends LazyLogging { | ||||||||||
@throws[IOException] | ||||||||||
|
@@ -69,4 +76,182 @@ class PrecomputedArray(relativePath: DatasetPath, | |||||||||
.mkString(header.dimension_separator.toString) | ||||||||||
} | ||||||||||
|
||||||||||
// SHARDING | ||||||||||
// Implemented according to https://github.com/google/neuroglancer/blob/master/src/neuroglancer/datasource/precomputed/sharded.md, | ||||||||||
// directly adapted from https://github.com/scalableminds/webknossos-connect/blob/master/wkconnect/backends/neuroglancer/sharding.py. | ||||||||||
|
||||||||||
private val shardIndexCache: AlfuFoxCache[VaultPath, Array[Byte]] = | ||||||||||
AlfuFoxCache() | ||||||||||
|
||||||||||
private val minishardIndexCache: AlfuFoxCache[(VaultPath, Int), Seq[(Long, Long, Long)]] = | ||||||||||
AlfuFoxCache() | ||||||||||
|
||||||||||
private def getHashForChunk(chunkIndex: Array[Int]): Long = | ||||||||||
CompressedMortonCode.encode(chunkIndex, header.gridSize) | ||||||||||
|
||||||||||
private lazy val minishardMask = { | ||||||||||
header.precomputedScale.sharding match { | ||||||||||
case Some(shardingSpec: ShardingSpecification) => | ||||||||||
if (shardingSpec.minishard_bits == 0) { | ||||||||||
0 | ||||||||||
} else { | ||||||||||
var minishardMask = 1L | ||||||||||
for (_ <- 0 until shardingSpec.minishard_bits - 1) { | ||||||||||
minishardMask <<= 1 | ||||||||||
minishardMask |= 1 | ||||||||||
} | ||||||||||
minishardMask | ||||||||||
} | ||||||||||
case None => 0 | ||||||||||
} | ||||||||||
} | ||||||||||
|
||||||||||
private lazy val shardMask = { | ||||||||||
header.precomputedScale.sharding match { | ||||||||||
case Some(shardingSpec: ShardingSpecification) => | ||||||||||
val oneMask = Long.MinValue // 0xFFFFFFFFFFFFFFFF | ||||||||||
val cursor = shardingSpec.minishard_bits + shardingSpec.shard_bits | ||||||||||
val shardMask = ~((oneMask >> cursor) << cursor) | ||||||||||
shardMask & (~minishardMask) | ||||||||||
case None => 0 | ||||||||||
} | ||||||||||
} | ||||||||||
|
||||||||||
private lazy val minishardCount = 1 << header.precomputedScale.sharding.map(_.minishard_bits).getOrElse(0) | ||||||||||
|
||||||||||
private lazy val shardIndexRange: NumericRange.Exclusive[Long] = { | ||||||||||
val end = minishardCount * 16 | ||||||||||
Range.Long(0, end, 1) | ||||||||||
} | ||||||||||
|
||||||||||
private def getShardIndex(shardPath: VaultPath)(implicit ec: ExecutionContext): Fox[Array[Byte]] = | ||||||||||
shardIndexCache.getOrLoad(shardPath, readShardIndex) | ||||||||||
|
||||||||||
private def readShardIndex(shardPath: VaultPath)(implicit ec: ExecutionContext): Fox[Array[Byte]] = | ||||||||||
for { | ||||||||||
bytes <- Fox.option2Fox(shardPath.readBytes(Some(shardIndexRange))) | ||||||||||
} yield bytes | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
should be identical |
||||||||||
|
||||||||||
private def parseShardIndex(index: Array[Byte]): Seq[(Long, Long)] = | ||||||||||
// See https://github.com/google/neuroglancer/blob/master/src/neuroglancer/datasource/precomputed/sharded.md#shard-index-format | ||||||||||
index | ||||||||||
.grouped(16) // 16 Bytes: 2 uint64 numbers: start_offset, end_offset | ||||||||||
.map((bytes: Array[Byte]) => { | ||||||||||
(BigInt(bytes.take(8).reverse).toLong, BigInt(bytes.slice(8, 16).reverse).toLong) // bytes reversed because they are stored little endian | ||||||||||
}) | ||||||||||
.toSeq | ||||||||||
|
||||||||||
private def getMinishardInfo(chunkHash: Long): (Long, Long) = | ||||||||||
header.precomputedScale.sharding match { | ||||||||||
case Some(shardingSpec: ShardingSpecification) => | ||||||||||
val rawChunkIdentifier = chunkHash >> shardingSpec.preshift_bits | ||||||||||
val chunkIdentifier = shardingSpec.hashFunction(rawChunkIdentifier) | ||||||||||
val minishardNumber = chunkIdentifier & minishardMask | ||||||||||
val shardNumber = (chunkIdentifier & shardMask) >> shardingSpec.minishard_bits | ||||||||||
(shardNumber, minishardNumber) | ||||||||||
case None => (0, 0) | ||||||||||
} | ||||||||||
|
||||||||||
private def getPathForShard(shardNumber: Long): VaultPath = { | ||||||||||
val shardBits = header.precomputedScale.sharding.map(_.shard_bits.toFloat).getOrElse(0f) | ||||||||||
if (shardBits == 0) { | ||||||||||
vaultPath / relativePath.storeKey / "0.shard" | ||||||||||
} else { | ||||||||||
val shardString = String.format(s"%1$$${(shardBits / 4).ceil.toInt}s", shardNumber.toHexString).replace(' ', '0') | ||||||||||
vaultPath / relativePath.storeKey / s"$shardString.shard" | ||||||||||
} | ||||||||||
|
||||||||||
} | ||||||||||
|
||||||||||
private def getMinishardIndexRange(minishardNumber: Int, | ||||||||||
parsedShardIndex: Seq[(Long, Long)]): NumericRange.Exclusive[Long] = { | ||||||||||
val miniShardIndexStart: Long = (shardIndexRange.end).toLong + parsedShardIndex(minishardNumber)._1 | ||||||||||
val miniShardIndexEnd: Long = (shardIndexRange.end).toLong + parsedShardIndex(minishardNumber)._2 | ||||||||||
Range.Long(miniShardIndexStart, miniShardIndexEnd, 1) | ||||||||||
} | ||||||||||
|
||||||||||
private def parseMinishardIndex(bytes: Array[Byte]): Seq[(Long, Long, Long)] = { | ||||||||||
// Because readBytes already decodes gzip, we don't need to decompress here | ||||||||||
/* | ||||||||||
From: https://github.com/google/neuroglancer/blob/master/src/neuroglancer/datasource/precomputed/sharded.md#minishard-index-format | ||||||||||
The decoded "minishard index" is a binary string of 24*n bytes, specifying a contiguous C-order array of [3, n] | ||||||||||
uint64le values. | ||||||||||
*/ | ||||||||||
val n = bytes.length / 24 | ||||||||||
val buf = ByteBuffer.allocate(bytes.length) | ||||||||||
buf.put(bytes) | ||||||||||
|
||||||||||
val longArray = new Array[Long](n * 3) | ||||||||||
buf.position(0) | ||||||||||
buf.order(ByteOrder.LITTLE_ENDIAN) | ||||||||||
buf.asLongBuffer().get(longArray) | ||||||||||
// longArray is row major / C-order | ||||||||||
/* | ||||||||||
From: https://github.com/google/neuroglancer/blob/master/src/neuroglancer/datasource/precomputed/sharded.md#minishard-index-format | ||||||||||
Values array[0, 0], ..., array[0, n-1] specify the chunk IDs in the minishard, and are delta encoded, such that | ||||||||||
array[0, 0] is equal to the ID of the first chunk, and the ID of chunk i is equal to the sum | ||||||||||
of array[0, 0], ..., array[0, i]. | ||||||||||
*/ | ||||||||||
val chunkIds = new Array[Long](n) | ||||||||||
chunkIds(0) = longArray(0) | ||||||||||
for (i <- 1 until n) { | ||||||||||
chunkIds(i) = longArray(i) + chunkIds(i - 1) | ||||||||||
} | ||||||||||
/* | ||||||||||
From: https://github.com/google/neuroglancer/blob/master/src/neuroglancer/datasource/precomputed/sharded.md#minishard-index-format | ||||||||||
The size of the data for chunk i is stored as array[2, i]. | ||||||||||
Values array[1, 0], ..., array[1, n-1] specify the starting offsets in the shard file of the data corresponding to | ||||||||||
each chunk, and are also delta encoded relative to the end of the prior chunk, such that the starting offset of the | ||||||||||
first chunk is equal to shard_index_end + array[1, 0], and the starting offset of chunk i is the sum of | ||||||||||
shard_index_end + array[1, 0], ..., array[1, i] and array[2, 0], ..., array[2, i-1]. | ||||||||||
*/ | ||||||||||
val chunkSizes = longArray.slice(2 * n, 3 * n) | ||||||||||
val chunkStartOffsets = new Array[Long](n) | ||||||||||
chunkStartOffsets(0) = longArray(n) | ||||||||||
for (i <- 1 until n) { | ||||||||||
val startOffsetIndex = i + n | ||||||||||
chunkStartOffsets(i) = chunkStartOffsets(i - 1) + longArray(startOffsetIndex) + chunkSizes(i - 1) | ||||||||||
} | ||||||||||
(chunkIds, chunkStartOffsets, chunkSizes).zipped.map((a, b, c) => (a, b, c)) | ||||||||||
} | ||||||||||
|
||||||||||
private def getMinishardIndex(shardPath: VaultPath, minishardNumber: Int)( | ||||||||||
implicit ec: ExecutionContext): Fox[Seq[(Long, Long, Long)]] = | ||||||||||
minishardIndexCache.getOrLoad((shardPath, minishardNumber), readMinishardIndex) | ||||||||||
|
||||||||||
private def readMinishardIndex(vaultPathAndMinishardNumber: (VaultPath, Int))( | ||||||||||
implicit ec: ExecutionContext): Fox[Seq[(Long, Long, Long)]] = { | ||||||||||
val (vaultPath, minishardNumber) = vaultPathAndMinishardNumber | ||||||||||
for { | ||||||||||
index <- getShardIndex(vaultPath) | ||||||||||
parsedIndex = parseShardIndex(index) | ||||||||||
minishardIndexRange = getMinishardIndexRange(minishardNumber, parsedIndex) | ||||||||||
indexRaw <- vaultPath.readBytes(Some(minishardIndexRange)) | ||||||||||
} yield parseMinishardIndex(indexRaw) | ||||||||||
} | ||||||||||
|
||||||||||
private def getChunkRange(chunkId: Long, | ||||||||||
minishardIndex: Seq[(Long, Long, Long)]): Option[NumericRange.Exclusive[Long]] = | ||||||||||
for { | ||||||||||
chunkSpecification <- minishardIndex.find(_._1 == chunkId) | ||||||||||
chunkStart = (shardIndexRange.end).toLong + chunkSpecification._2 | ||||||||||
chunkEnd = (shardIndexRange.end).toLong + chunkSpecification._2 + chunkSpecification._3 | ||||||||||
} yield Range.Long(chunkStart, chunkEnd, 1) | ||||||||||
|
||||||||||
override def readShardedChunk(chunkIndex: Array[Int])(implicit ec: ExecutionContext): Future[Array[Byte]] = { | ||||||||||
val chunkIdentifier = getHashForChunk(chunkIndex) | ||||||||||
val minishardInfo = getMinishardInfo(chunkIdentifier) | ||||||||||
val shardPath = getPathForShard(minishardInfo._1) | ||||||||||
for { | ||||||||||
minishardIndex <- getMinishardIndex(shardPath, minishardInfo._2.toInt) | ||||||||||
.toFutureOrThrowException("Could not get minishard index") | ||||||||||
chunkRange: NumericRange.Exclusive[Long] <- Fox | ||||||||||
.option2Fox(getChunkRange(chunkIdentifier, minishardIndex)) | ||||||||||
.toFutureOrThrowException("Chunk range not found in minishard index") | ||||||||||
chunkData <- Fox | ||||||||||
.option2Fox(shardPath.readBytes(Some(chunkRange))) | ||||||||||
.toFutureOrThrowException(s"Could not read chunk data from path ${shardPath.toString}") | ||||||||||
} yield chunkData | ||||||||||
} | ||||||||||
|
||||||||||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I’m wondering whether we can get the two branches here into one. As I understand, currently, both branches have their own version of reading from the store, decompressing, then typing. Could it be unified? Maybe the sharding implementation could just return the chunk path plus byte range to be passed to the existing chunkReader? (With non-sharding returning None for the range)