viirya commented on a change in pull request #26722: [SPARK-24666][ML] Fix 
infinity vectors produced by Word2Vec when numIterations are large
URL: https://github.com/apache/spark/pull/26722#discussion_r353396038
 
 

 ##########
 File path: mllib/src/main/scala/org/apache/spark/mllib/feature/Word2Vec.scala
 ##########
 @@ -439,9 +439,21 @@ class Word2Vec extends Serializable with Logging {
           }
         }.flatten
       }
-      val synAgg = partial.reduceByKey { case (v1, v2) =>
-          blas.saxpy(vectorSize, 1.0f, v2, 1, v1, 1)
-          v1
+      // SPARK-24666: do normalization for aggregating weights from partitions.
+      // Original Word2Vec either single-thread or multi-thread which do 
Hogwild-style aggregation.
+      // Our approach needs to do extra normalization, otherwise adding 
weights continuously may
+      // cause overflow on float and lead to infinity/-infinity weights.
+      val synAgg = partial.mapPartitions { iter =>
+        iter.map { case (id, vec) =>
+          (id, (vec, 1))
+        }
+      }.reduceByKey { case ((v1, count1), (v2, count2)) =>
+        blas.saxpy(vectorSize, 1.0f, v2, 1, v1, 1)
+        (v1, count1 + count2)
+      }.map { case (id, (vec, count)) =>
+        val averagedVec = Array.fill[Float](vectorSize)(0.0f)
+        blas.saxpy(vectorSize, 1.0f / count, vec, 1, averagedVec, 1)
 
 Review comment:
    sscal will scales the vector in place.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscr...@spark.apache.org
For additional commands, e-mail: reviews-h...@spark.apache.org

Reply via email to