Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
* Tencent is pleased to support the open source community by making Angel available.
*
* Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/Apache-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package com.tencent.angel.spark.examples.cluster

import com.tencent.angel.graph.ann.algo.BruteForce
import com.tencent.angel.graph.ann.utils.DataUtils
import com.tencent.angel.graph.utils.GraphIO
import com.tencent.angel.spark.context.PSContext
import com.tencent.angel.spark.ml.core.ArgsUtil
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.SparkSession
import org.apache.spark.storage.StorageLevel

object BruteForceExample {
def main(args: Array[String]): Unit = {
val params = ArgsUtil.parse(args)
val mode = params.getOrElse("mode", "yarn-cluster")
val sc = start(mode)

val vectorPath = params.getOrElse("vectorPath", null)
val outputPath = params.getOrElse("outputPath", null)
val queryPath = params.getOrElse("queryPath", null)
val partitionNum = params.getOrElse("partitionNum", "100").toInt
val storageLevel = StorageLevel.fromString(params.getOrElse("storageLevel", "MEMORY_ONLY"))
val psPartitionNum = params.getOrElse("psPartitionNum",
sc.getConf.get("spark.ps.instances", "10")).toInt

val batchSize = params.getOrElse("batchSize", "2000").toInt
val topK = params.getOrElse("topK", "10").toInt
val isInternal = params.getOrElse("isInternal", "false").toBoolean
val distanceFuncion = params.getOrElse("distanceFunction", "cosine-distance")
val sheetsNum = params.getOrElse("sheetsNum", "1").toInt
val queryPartitionNum = params.getOrElse("queryPartitionNum", "10").toInt

val cpDir = params.get("cpDir").filter(_.nonEmpty).orElse(GraphIO.defaultCheckpointDir)
.getOrElse(throw new Exception("checkpoint dir not provided"))
sc.setCheckpointDir(cpDir)

val itemSep = params.getOrElse("itemSep", "colon") match {
case "space" => " "
case "comma" => ","
case "tab" => "\t"
case "colon" => ":"
}
val vecSep = params.getOrElse("vecSep", "space") match {
case "space" => " "
case "comma" => ","
case "tab" => "\t"
case "colon" => ":"
}
val saveItemSep = params.getOrElse("saveItemSep", "tab") match {
case "space" => " "
case "comma" => ","
case "tab" => "\t"
}

val bruteforce = new BruteForce()
.setTopK(topK)
.setStorageLevel(storageLevel)
.setPartitionNum(partitionNum)
.setPSPartitionNum(psPartitionNum)
.setIsInternal(isInternal)
.setQueryPath(queryPath)
.setDisFunc(distanceFuncion)
.setItemSep(itemSep)
.setVecSep(vecSep)
.setBatchSize(batchSize)
.setQueryPartitionNum(queryPartitionNum)
.setSheetsNum(sheetsNum)

val ss = SparkSession.builder().getOrCreate()
val df = DataUtils.loadVectors(ss, vectorPath, itemSep).repartition(partitionNum)

val retDF = bruteforce.transform(df)

println(s"start to save")
DataUtils.saveResult(retDF, outputPath, saveItemSep)

stop()
}


def start(mode: String): SparkContext = {
val conf = new SparkConf()

// Add jvm parameters for executors
if (!mode.contains("local")) {
var executorJvmOptions = conf.get("spark.executor.extraJavaOptions")
executorJvmOptions += " -XX:ConcGCThreads=4 -XX:ParallelGCThreads=4 -Xss4M "
conf.set("spark.executor.extraJavaOptions", executorJvmOptions)
println(s"executorJvmOptions = ${executorJvmOptions}")
}

conf.setMaster(mode)
conf.setAppName("BruteForce")
val sc = new SparkContext(conf)
sc
}

def stop(): Unit = {
PSContext.stop()
SparkContext.getOrCreate().stop()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,6 @@ object HnswExample {
val sheetsNum = params.getOrElse("sheetsNum", "1").toInt
val queryPartitionNum = params.getOrElse("queryPartitionNum", "10").toInt

val itemIdx = params.getOrElse("itemIdx", "0").toInt
val vecIdx = params.getOrElse("vecIdx", "1").toInt

val cpDir = params.get("cpDir").filter(_.nonEmpty).orElse(GraphIO.defaultCheckpointDir)
.getOrElse(throw new Exception("checkpoint dir not provided"))
sc.setCheckpointDir(cpDir)
Expand Down Expand Up @@ -87,9 +84,7 @@ object HnswExample {
.setQueryPath(queryPath)
.setDisFunc(distanceFuncion)
.setItemSep(itemSep)
.setItemIdx(itemIdx)
.setVecSep(vecSep)
.setVecIdx(vecIdx)
.setBatchSize(batchSize)
.setQueryPartitionNum(queryPartitionNum)
.setSheetsNum(sheetsNum)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,48 +14,49 @@
* the License.
*
*/
package com.tencent.angel.graph.ann.algo
package com.tencent.angel.graph.ann

import com.tencent.angel.graph.common.param.ModelContext
import com.tencent.angel.spark.context.PSContext
import com.tencent.angel.graph.ann.params._
import com.tencent.angel.graph.ann.partition.ANNPartition
import com.tencent.angel.graph.ann.utils.DataUtils
import com.tencent.angel.graph.common.param.ModelContext
import com.tencent.angel.graph.data.NeighborDistance
import com.tencent.angel.spark.context.PSContext
import com.tencent.angel.spark.ml.graph.utils.params._
import org.apache.spark.SparkContext
import org.apache.spark.ml.param.{ParamMap, Params}
import org.apache.spark.ml.util.Identifiable
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.types.{LongType, StringType, StructField, StructType}
import org.apache.spark.sql.{DataFrame, Dataset, Row, SparkSession}
import com.tencent.angel.spark.ml.graph.utils.params._

import scala.collection.mutable.ArrayBuffer

class HnswModel(override val uid: String) extends Serializable with HasTopK with HasVecSep
class ANNModel[T <: ANNPartition](override val uid: String) extends Serializable with HasTopK with HasVecSep
with HasItemSep with HasItemIdCol with HasVectorCol with HasDistanceFunction with HasPartitionNum
with HasPSPartitionNum with HasStorageLevel with HasQueryPath with HasIsInternalQuery with HasBatchSize
with HasMaxItemCount with HasItemIdx with HasVecIdx with HasQueryPartitionNum
with HasUseBalancePartition with HasBalancePartitionPercent with HasSheetsNum {

def this() = this(Identifiable.randomUID("HnswModel"))
with HasMaxItemCount with HasQueryPartitionNum with HasUseBalancePartition with HasBalancePartitionPercent
with HasSheetsNum {
def this() = this(Identifiable.randomUID("ANNModel"))

var ss: SparkSession = _
var KNN: Int = _
var data: RDD[(Long, Array[Float])] = _
var queryIds: RDD[Long] = _
var psModel: HnswPSModel = _
var psModel: ANNPSModel = _
var querySheets: Array[RDD[Long]] = _
var partitionSheets: RDD[(Int, HnswPartition)] = _

var partitionSheets: RDD[(Int, T)] = _
def start(dataset: Dataset[_]): Unit = {
this.ss = dataset.sparkSession
this.KNN = if ($(isInternal)) $(topK) else $(topK) + 1
data = DataUtils.loadFromDF(dataset, $(itemIdCol), $(vectorCol), $(vecSep), $(partitionNum))
data.persist($(storageLevel))
val numVectors = data.count()

println(s"$numVectors items in total...")

var (queryData, tQueryIds) =
if ($(isInternal)) {
val tQIdsRDD =
Expand All @@ -78,7 +79,7 @@ class HnswModel(override val uid: String) extends Serializable with HasTopK with
println(s"load query ids and vectors from ${$(queryPath)}. ")
(tQueryData, tQIdsRDD)
}

this.queryIds = tQueryIds
if (!$(isInternal)) {
val queryCnt = queryData.count()
Expand All @@ -91,27 +92,26 @@ class HnswModel(override val uid: String) extends Serializable with HasTopK with
queryData.persist($(storageLevel))
queryData.count()
}

this.queryIds.persist($(storageLevel))
println(s"total ${this.queryIds.count()} queries loaded.")

println(s"process with ${$(disFunc)} function")

val minId = queryIds.min()
val maxId = queryIds.max()

println(s"queryMinId: $minId queryMaxId: $maxId")
println("start to run ps")
PSContext.getOrCreate(SparkContext.getOrCreate())

val modelContext = new ModelContext($(psPartitionNum), minId, maxId + 1, -1, "HnswModel",
val modelContext = new ModelContext($(psPartitionNum), minId, maxId + 1, -1, this.getClass.getSimpleName,
SparkContext.getOrCreate().hadoopConfiguration)

this.psModel = HnswPSModel.apply(modelContext, this.data, $(useBalancePartition), $(balancePartitionPercent))

this.psModel = ANNPSModel.apply(modelContext, this.data, $(useBalancePartition), $(balancePartitionPercent))

println("start init ps...")
val timeInitPS = System.currentTimeMillis()

// init queries matrix
if (!$(isInternal)) {
this.psModel.initQueries(queryData)
queryData.unpersist(blocking = false)
Expand All @@ -120,67 +120,68 @@ class HnswModel(override val uid: String) extends Serializable with HasTopK with
this.psModel.initQueries(this.data)
}
println(s"init ps cost: ${(System.currentTimeMillis() - timeInitPS) / 1000.0} s")


// checkpoint for vectors and queries
println("save checkpoint...")
val timeWriteCheckpoint = System.currentTimeMillis()
psModel.checkpoint(0, Array("queryVector", "searchRes"))
println(s"write checkpoint cost: ${(System.currentTimeMillis() - timeWriteCheckpoint) / 1000.0} s")

}

def setANNPartsWithSheets(parts: RDD[HnswPartition]): Unit = {
def setANNPartsWithSheets(parts: RDD[T]): Unit = {
this.makeSheets()
this.partitionSheets = parts.map(p => (0, p))
for (i <- 1 until $(sheetsNum)) {
this.partitionSheets = this.partitionSheets.union(parts.map(p => (i, p.setSheetId(i))))
this.partitionSheets = this.partitionSheets.union(parts.map(p => (i, p.setSheetId(i).asInstanceOf[T])))
}
this.partitionSheets.persist($(storageLevel))
println(s"origin parts num: ${parts.count()}, ${this.partitionSheets.count()} parts of ${$(sheetsNum)} sheets")
this.data.unpersist(blocking = false)
}

def makeSheets(): Unit = {
this.querySheets = this.queryIds.randomSplit(Array.fill($(sheetsNum))(1.0))
}

def processANNParts(): Unit = {
assert(this.partitionSheets != null, s"need to set ann partition sheets")

val brQIdsArray = this.querySheets.map(sheet => SparkContext.getOrCreate().broadcast(sheet.collect()))

println(s"start to process nearest neighbors")
val timeFindKNN = System.currentTimeMillis()
this.partitionSheets.foreach(sheet => sheet._2.process(psModel, brQIdsArray(sheet._1), KNN, $(batchSize)))
this.partitionSheets.unpersist(blocking = false)
println(s"find knn with top ${$(topK)} cost: ${(System.currentTimeMillis() - timeFindKNN) / 1000.0} s")
}

def processANNParts(parts: RDD[HnswPartition]): Unit = {
def processANNParts(parts: RDD[T]): Unit = {
this.setANNPartsWithSheets(parts)
this.processANNParts()
}

def saveKNNResults(): DataFrame = {
println(s"start to make saving data")
val timeMakeSaving = System.currentTimeMillis()

val retRDD = HnswModel.save(this.psModel, this.queryIds, this.KNN, $(batchSize))
val retRDD = ANNModel.save(this.psModel, this.queryIds, this.KNN, $(batchSize))
.map(a => (a._1, a._2.map(t => s"${t.getNeighbor}:${t.getDistance}").mkString(" ")))
.map(row => Row.fromSeq(Seq[Any](row._1, row._2)))
println(s"make saving data cost: ${System.currentTimeMillis() - timeMakeSaving} ms")

val schema = StructType(Seq(
StructField("query", LongType, nullable = false),
StructField("nbr:dis", StringType, nullable = false)))

this.ss.createDataFrame(retRDD, schema)
}

override def copy(extra: ParamMap): Params = defaultCopy(extra)
}

object HnswModel {
def save(psModel: HnswPSModel, qIds: RDD[Long], topK: Int,
object ANNModel {
def save(psModel: ANNPSModel, qIds: RDD[Long], topK: Int,
batchSize: Int): RDD[(Long, Array[NeighborDistance])] = {
qIds.mapPartitions{ partQ =>
val partQIds = partQ.toArray
Expand All @@ -191,6 +192,8 @@ object HnswModel {
val iter = partRes.entrySet().iterator()
val savedPart = new ArrayBuffer[(Long, Array[NeighborDistance])]()
while (iter.hasNext) {
val ks = new ArrayBuffer[Long]()
val ds = new ArrayBuffer[Float]()
val entry = iter.next()
val key = entry.getKey
val value = entry.getValue
Expand Down
Loading