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_r352937085
 
 

 ##########
 File path: mllib/src/main/scala/org/apache/spark/mllib/feature/Word2Vec.scala
 ##########
 @@ -438,11 +438,23 @@ class Word2Vec extends Serializable with Logging {
             None
           }
         }.flatten
-      }
-      val synAgg = partial.reduceByKey { case (v1, v2) =>
-          blas.saxpy(vectorSize, 1.0f, v2, 1, v1, 1)
-          v1
+      }.persist()
+      // 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 keyCounts = partial.countByKey()
+      val synAgg = partial.mapPartitions { iter =>
+        iter.map { case (id, vec) =>
+          val v1 = Array.fill[Float](vectorSize)(0.0f)
+          blas.saxpy(vectorSize, 1.0f / keyCounts(id), vec, 1, v1, 1)
+          (id, v1)
+        }
+      }.reduceByKey { case (v1, v2) =>
 
 Review comment:
   During `reduceByKey`, we already do sum up and can lead to infinity? Once it 
is done, i think it does not make sense anymore to divide?

----------------------------------------------------------------
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