Skip to content

Add unsortedsegment(prod/min/max/sqrt_n/mean). - #15858

Merged
rmlarsen merged 5 commits into
tensorflow:masterfrom
PhilJd:phil/unsorted_segment_reduction
Feb 7, 2018
Merged

rmlarsen merged 5 commits into
tensorflow:masterfrom
PhilJd:phil/unsorted_segment_reduction

Conversation

@PhilJd

@PhilJd PhilJd commented Jan 4, 2018

Copy link
Copy Markdown
Contributor

This pull request

  • adds CPU/GPU implementations of
    • tf.unsorted_segment_min,
    • tf.unsorted_segment_prod and a
    • GPU implementation for tf.unsorted_segment_max.
  • adds python implementations of:
    • tf.unsorted_segment_mean
    • tf.unsorted_segment_sqrt_n
  • fixes the gradient calculation for unsorted_segment_sum/max.
    Add support of drop_negatives for tf.unsorted_segment_sum #13055 introduced silent dropping of negative values on the cpu.
    However, the gradient of e.g. unsorted_segment_sum used tf.gather
    and therefore failed for negative indices on cpu.

I tried to simplify the code and to remove code duplication,
addressing this todo.
(Also I once filed an issue to add these ops but only now had time to finish it ;).)

Some notes on this pull request:

  • tf.gather returns zero on GPU for negative indices and raises an exception on
    CPU. To overcome this, the current implementation masks negative indices and
    sets them to zero later. This is of course not as efficient as the original gather.
    Would it make sense to use something like if "gpu" in op.device.lower(): to run
    different functions, depending on the device?

  • Instead of having a native op for mean/sqrt_n I added them in python.
    Making them native would require two additional template arguments
    (a functor to process the counter), resulting in more complicated code with
    probably only minor performance improvement, if at all. In my quick
    benchmarks, the python ops are nearly as fast as unsorted_segment_sum. However,
    they use more memory than a native op would, due to creating a tensor of ones.
    (bincount doesn't work here as it doesn't support negative indices)

  • I simply copy-pasted some atomicOp code in cuda_kernel_helper.h instead of
    writing this more nicely as for a short period there was a completely different
    version of this file online and I wanted to check back with you before
    doing something more sophisticated. What's the status of this?

    Additionally, I guess the function AccumulateInto in segment_reduction_ops_gpu.cu.cc
    could be removed? CudaAtomicAdd has specializations for complex types in
    cuda_kernel_helper.h

Cheers,
Phil

@tensorflow-jenkins

Copy link
Copy Markdown
Collaborator

Can one of the admins verify this patch?

@rmlarsen
rmlarsen self-requested a review January 23, 2018 00:13
@rmlarsen rmlarsen self-assigned this Jan 23, 2018
@rmlarsen rmlarsen added awaiting review Pull request awaiting review kokoro:run labels Jan 23, 2018
@KuzeydekiBuyucu

KuzeydekiBuyucu commented Jan 23, 2018 via email

Copy link
Copy Markdown

@PhilJd
PhilJd force-pushed the phil/unsorted_segment_reduction branch from 77df5e8 to 6963bb2 Compare January 23, 2018 14:08
@PhilJd

PhilJd commented Jan 23, 2018

Copy link
Copy Markdown
Contributor Author

I rebased and updated the golden API, this should fix the test failures.

@ub216

ub216 commented Jan 26, 2018

Copy link
Copy Markdown

Hey Phil

Thanks for those updates needed them for some ray-tracing operations. In addition I also need the argmax/argmin operations. Could you direct me how I could add those operations.

Cheers

@PhilJd
PhilJd force-pushed the phil/unsorted_segment_reduction branch from 525f13b to 6195ce9 Compare January 28, 2018 09:38
@PhilJd

PhilJd commented Jan 28, 2018

Copy link
Copy Markdown
Contributor Author

@rmlarsen

  • How do I update the golden API for MacOS? The api_compatibility tests pass for python3. (I can't access the build log of Ubuntu python2)
  • The new cuda_kernel_helper.h / cuda_device_functions.h are back in the master, I rebased, adapted this pull request accordingly and squashed commits.

@ub216 Do you want to implement this as a native op or are you fine with a composition of native ops? For the composition you could take a look at the implementation of the gradient of unsorted_segment_max. I.e. something like this should work (untested):

unsorted_max = tf.unsorted_segment_max(params, ids)
gathered_max = tf.gather(unsorted_max, ids)
arg_max = tf.where(tf.equal(gathered_max, params))

In any case, I think this is not the right thread to discuss this, if you're interested in implementing this as a cpp op I suggest to open a feature request issue to discuss it there ;)

@ub216

ub216 commented Jan 29, 2018

Copy link
Copy Markdown

Apologies for crashing the thread. Will start a new thread for the cpp op and thanks for the composition of ops.

@mehmetbasbug

Copy link
Copy Markdown

@PhilJd Great work!

Do you think it is possible to have an unsorted_segment_matmul op within your framework?

@rmlarsen

Copy link
Copy Markdown
Contributor

@PhilJd you have to install Python 2.7 and run the api_compatibility test to add golden's with it, I believe.

@rmlarsen

Copy link
Copy Markdown
Contributor

@PhilJd Sorry for the delay. I'll review this within the next couple of days.

@PhilJd

PhilJd commented Jan 29, 2018

Copy link
Copy Markdown
Contributor Author

@rmlarsen
Thanks for triggering the tests, I'll look into the failures tomorrow!
Regarding the api compatibility tests: I ran the command in a virtual environment with python2.7 on an Ubuntu 16.04 machine for the current commit, this doesn't seem to have solved the problem.

@mehmetbasbug
As the current implementation flattens the array there's no straightforward way to integrate it without adapting some of the code. Also, I guess this will be specific for your use case, e.g. how would you define the order of multiplication?

@rmlarsen

rmlarsen commented Jan 29, 2018 •

Copy link
Copy Markdown
Contributor

@PhilJd What you describe usually resolves the API compatibility issues. @gunan @wicke do you have any additional advice?

@gunan

gunan commented Jan 29, 2018

Copy link
Copy Markdown
Contributor

@PhilJd in the virtual environment you may need to rerun configure, rebuild and then run the commands.
Did you build within the virtual environment, or did you just run the binary inside the environment (just making sure).

@rmlarsen

Copy link
Copy Markdown
Contributor

@PhilJd could you also please rebase to resolve the conflicts?

@PhilJd
PhilJd force-pushed the phil/unsorted_segment_reduction branch from 6195ce9 to eaa7643 Compare January 30, 2018 11:42
@PhilJd

PhilJd commented Jan 30, 2018 •

Copy link
Copy Markdown
Contributor Author

@rmlarsen @gunan
Thanks for the help! I rebased and after cleaning .cache/bazel and rebuilding I could successfully update the golden API (at least it generated some lines in /tensorflow/tools/api/golden/tensorflow.pbtxt). I built tf in the virtual environment before as well, so I think removing the cache somehow did the trick.

I'm a bit clueless regarding the build failures (see below). These tests build and run fine locally on two different machines (Ubuntu 16.04 and Arch Linux, python2/3, w. CUDA 9 and CUDNN 7, Pascal GPUs). Do the test servers run with cuda_arch < 600? This is handled separately, however, I didn't touch these lines.

Cheers

error: no instance of overloaded function "atomicAdd" matches the argument list
            argument types are: (double *, double)
          detected during instantiation of "tensorflow::detail::ToTypeIfConvertible<U, T> tensorflow::CudaAtomicAdd(T *, U) [with T=double, U=double]" 

@PhilJd

PhilJd commented Jan 31, 2018

Copy link
Copy Markdown
Contributor Author

Okay, I was just too tired yesterday to remember that the complex specialization for atomicAdd relies on the double specialization. I switched the order, i.e. moved the complex specialization below the special case for double and cuda_arch < 600. Now compilation for cuda_arch 5.1 works. Sorry for the confusion! Could you trigger the tests again? Thanks!

@rmlarsen rmlarsen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apart from a few nits, this PR looks excellent to me. Thanks a lot for this contribution!

#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: The Eigen include should usually go first. It doesn't strictly need to here, but many times we've seen bugs because somebody would would set Eigen-related macros after unknowingly including "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" through a transitively include.

// reduction functors for the gpu
template <typename T>
struct SumOpGpu {
__device__ __forceinline__ void operator()(T* dest, const T& value) {

@rmlarsen rmlarsen Jan 31, 2018 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Prefer EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE to __device__ __forceinline__. Same everywhere.

@rmlarsen
rmlarsen requested review from ebrevdo and ekelsen January 31, 2018 19:40
@rmlarsen

Copy link
Copy Markdown
Contributor

@PhilJd would you consider adding support for fp16 (DT_HALF) and bfloat16 (DT_BFLOAT16)? Could be done as a followup PR.


template <typename T>
struct Lowest {
inline T operator()() const { return std::numeric_limits<T>::lowest(); }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Prefer Eigen::numext version instead - they have better support for 16-bit floating point types. Speaking of which, it would be awesome if this PR also supported those types for these new operations.

@rmlarsen rmlarsen Jan 31, 2018 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's in Eigen::NumTraits<T> - sorry that I mislead you in our internal chat, Erich :-)
See my comment.

@rmlarsen rmlarsen Jan 31, 2018 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ekelsen Thanks for spotting this, BTW!

@rmlarsen rmlarsen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apart from a few nits, this PR looks excellent to me. Thanks a lot for this contribution!


template <typename T>
struct Lowest {
inline T operator()() const { return std::numeric_limits<T>::lowest(); }

@rmlarsen rmlarsen Jan 31, 2018 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If instead of using numeric_limits here, you used the equivalent functions from Eigen
Eigen::NumTraits<T>::highest() and Eigen::NumTraits<T>::lowest()
the code would handle DT_HALF and DT_BFLOAT16 correctly. See, e.g., https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/quantization_utils.h#L74

@PhilJd

PhilJd commented Feb 5, 2018

Copy link
Copy Markdown
Contributor Author

Thanks for the comments!
I tried to enable bfloat16, but I struggle to do so for unsorted_segment_{mean,sqrt_n}. I enabled bfloat16 for cwise_max and fixed double registration in the reshape op but I don't know enough about the inner workings of tf to quickly implement the real_div op for bfloat16. So for now I disabled the test cases for mean/sqrtn + bfloat16.
In theory, these ops should work with bfloat16 once real_div is implemented. Would you be fine with enabling the test cases as soon as someone implemented div?

PhilJd and others added 4 commits February 5, 2018 16:20
This commit adds CPU/GPU implementations for prod/min/max
ops and python implementations for mean/sqrt_n. Also, it adapts and unifies the
corresponding tests of all unsorted reductions.
Note: The new gradient of unsorted_segment_max fixes the crash occuring when
negative indices on CPU are used.
…s the std::complex specialization of atomicAdd below the double specialization of atomicAdd for cuda_arch 600.
@PhilJd
PhilJd force-pushed the phil/unsorted_segment_reduction branch from 238dc3a to e9dd60f Compare February 5, 2018 15:22
@rmlarsen

rmlarsen commented Feb 5, 2018

Copy link
Copy Markdown
Contributor

@PhilJd Thanks a lot for adding partial support for additional types! We can certainly leave complete support for bfloat16 for a future change.

@rmlarsen rmlarsen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One minor typo.

Comment thread tensorflow/python/ops/math_grad.py Outdated
a different number of elements. Therefore we consider three cases:
1) A segment input contains no zeros and we can safely divide by the input
tensor.
2) A segment contains exactly on zero. Then the gradient of each input of

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/on/one/

2) A segment contains exactly on zero. Then the gradient of each input of
the segment is zero except for the 0-input, there the gradient is
the product of the remaining segment entries.
3) A segment contains at least two zeros. The gradient is zero for all

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very nice. Thanks for documenting the algorithm carefully.

@rmlarsen rmlarsen added the kokoro:force-run Tests on submitted change label Feb 5, 2018
@kokoro-team kokoro-team removed the kokoro:force-run Tests on submitted change label Feb 5, 2018
@PhilJd

PhilJd commented Feb 5, 2018

Copy link
Copy Markdown
Contributor Author

I'll look into the test failures tomorrow morning!

@PhilJd

PhilJd commented Feb 6, 2018

Copy link
Copy Markdown
Contributor Author

The GPU CC build should be fixed, the failure of the Android Demo App seems unrelated (tar exited with 1). I'm not sure why Ubuntu Python3 PIP failed, I can't reproduce it locally...

@gunan gunan added the kokoro:force-run Tests on submitted change label Feb 6, 2018
@kokoro-team kokoro-team removed the kokoro:force-run Tests on submitted change label Feb 6, 2018
@rmlarsen

rmlarsen commented Feb 7, 2018

Copy link
Copy Markdown
Contributor

@PhilJd Thanks again for a great contribution!

@rmlarsen
rmlarsen merged commit 3d86d8c into tensorflow:master Feb 7, 2018
@PhilJd
PhilJd deleted the phil/unsorted_segment_reduction branch February 8, 2018 10:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting review Pull request awaiting review cla: yes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants