-
Notifications
You must be signed in to change notification settings - Fork 5.6k
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
Add nce op #5480
Add nce op #5480
Conversation
1. Add nce forward and backward kernel for CPU
I think TensorFlow has a nice design about candidate sampling methods and we can use it as a reference. It supports not only NCE, but also importance sampling and negative sampling, which are also popular methods. It also naturally adapts to GPU version. |
@zhouxiao-coder We have already discussed with @wanghaoshuang about systematically support the sampling methods. It will be refined later. In this PR, we only want to quickly port the old NCE layer into the new framework. |
paddle/operators/nce_op.cc
Outdated
// set dims of output(Out) | ||
std::vector<int64_t> out_dims; | ||
out_dims.push_back(x_dims[0]); | ||
ctx->SetOutputDim("Cost", framework::make_ddim(out_dims)); |
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.
The output shape is [batch_size, 1] in smooth_l1, cos_sim, sequared_l2_distance, softmax_with_cross_entropy, and this can be discussed and unified 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.
Fixed.
paddle/operators/nce_op.cc
Outdated
AddOutput("SampleLogits", "An intermediate tensor.").AsIntermediate(); | ||
AddOutput("SampleLabels", "An intermediate tensor.").AsIntermediate(); | ||
AddAttr<int>("num_classes", "Total number of classes."); | ||
AddAttr<int>("num_sampled_classes", "The number of negative classes.") |
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.
Might num_neg_samples
be better if it indicates the number of negative samples for each positive sample. I just compare with the NCELayer, but I am not sure what num_sampled_classes
represents for and which is better. Maybe I just haven't got the point.
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.
Agree with @guoshengCS . But maybe can use num_neg_classes
to also incorporate @wanghaoshuang ‘s original consideration.
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.
Renamed num_sampled_classes
to num_neg_samples
paddle/operators/nce_op.cc
Outdated
std::vector<int> sampled_labels = | ||
ctx->Attrs().Get<std::vector<int>>("sampled_labels"); | ||
PADDLE_ENFORCE_EQ(num_classes, ctx->GetInputDim("Weight")[0]); | ||
PADDLE_ENFORCE_LT(num_sampled_classes, num_classes); |
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.
If num_sampled_classes
indicates the number of negative samples, the above PADDLE_ENFORCE_LT
may not be needed.
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.
num_classes
means the total number of classes in all samples. So i think this checking is necessary.
如果sampled_classes
中有重复的class, 是有可能num_sampled_classes
> num_classes
的, 也不能说噪声样本数量大于num_classes
就是错的,但是从计算性能上考虑,噪声样本数量大于num_classes
是没有必要的,所以有了这里的checking.
另外paddle v2和tesoflow中都没有这个限制。
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.
我还是先去掉这个checking吧
paddle/operators/nce_op.cc
Outdated
AddInput("Input", "(Tensor) A tensor of shape [batch_size, dim]."); | ||
AddInput("Label", | ||
"(Tensor) A tensor of shape [batch_size, num_true_class]. " | ||
"'num_true_class' is the number of target class in each sample."); |
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.
Is this used for multi-label and must all samples have the same label number.
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.
It would be useful to allow a variable number of target classes per example. For now, if you have a variable number of target classes, you can pad them out to a constant number by either repeating them or by padding with an otherwise unused class.
paddle/operators/nce_op.h
Outdated
} | ||
} else { | ||
for (; j < sample_labels_dims[1]; ++j) { | ||
sample_labels_data[index++] = rand(rng); |
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.
It seems that uniform distribution is the only supported temporarily. TODO
can be added for future work.
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.
Done.
paddle/operators/nce_op.h
Outdated
auto input_mat = EigenMatrix<T>::From(*(context.Input<Tensor>("Input"))); | ||
auto weight_mat = EigenMatrix<T>::From(*(context.Input<Tensor>("Weight"))); | ||
for (size_t i = 0; i < sample_labels->numel(); ++i) { | ||
Eigen::Tensor<float, 0, Eigen::RowMajor, Eigen::DenseIndex> result = |
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.
Can EigenScalar
in the framework be used here. I am not sure.
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.
EigenScalar
will cause compiling error:
错误:请求从‘const Eigen::TensorReductionOp<Eigen::internal::SumReducer<float>, const Eigen::DimensionList<long int, 1ul>, const Eigen::TensorCwiseBinaryOp<Eigen::internal::scalar_product_op<const float, const float>, const Eigen::TensorChippingOp<-1l, const Eigen::TensorMap<Eigen::Tensor<const float, 2, 1, long int>, 0, Eigen::MakePointer> >, const Eigen::TensorChippingOp<-1l, const Eigen::TensorMap<Eigen::Tensor<const float, 2, 1, long int>, 0, Eigen::MakePointer> > >, Eigen::MakePointer>’转换到非标量类型‘paddle::operators::EigenScalar<float, 1, long int> {aka paddle::framework::EigenScalar<float, 1, long int>}’
.sum();
paddle/operators/nce_op.h
Outdated
.sum(); | ||
sample_out_data[i] += result(0); | ||
// activation_->forward | ||
sample_out_data[i] = (1. / (1. + exp(-sample_out_data[i]))); |
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.
Maybe only output values of positive samples are needed to compute, and some computation can be reduced in future.
paddle/operators/nce_op.h
Outdated
if (d_bias != nullptr) { | ||
T* d_bias_data = d_bias->mutable_data<T>(context.GetPlace()); | ||
for (size_t i = 0; i < sample_labels->numel(); ++i) { | ||
d_bias_data[sample_labels_data[i]] += sample_grad_data[i]; |
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 am not sure if the grad_data should be clear to zero first.
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.
Fixed.
samples.append((i, num, False, w)) | ||
sample_labels.append(num) | ||
# forward bias | ||
sampleOut = np.zeros(len(samples)).astype(np.float32) |
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.
sample_out
might be better to unify name style.
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.
Fixed.
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.
Some simple comments first.
paddle/operators/nce_op.cc
Outdated
"total number of class."); | ||
AddInput("Bias", | ||
"(Tensor) A tensor of shape [num_class]. 'num_class' is the total " | ||
"number of class. It is a dispensable input.") |
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 remember we have discussed before and decide to use the 2-dimensional tensor to represent a vector to distinguish it is a row vector or a column vector explicitly.
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.
Fixed.
paddle/operators/nce_op.cc
Outdated
AddOutput("SampleLogits", "An intermediate tensor.").AsIntermediate(); | ||
AddOutput("SampleLabels", "An intermediate tensor.").AsIntermediate(); | ||
AddAttr<int>("num_classes", "Total number of classes."); | ||
AddAttr<int>("num_sampled_classes", "The number of negative classes.") |
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.
Agree with @guoshengCS . But maybe can use num_neg_classes
to also incorporate @wanghaoshuang ‘s original consideration.
paddle/operators/nce_op.cc
Outdated
AddInput("SampleWeight", | ||
"(Tensor) A tensor of shape [batch_size] storing a weight for " | ||
"each sample. And it is a dispensable input. The default value of " | ||
"sample is 1.") |
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.
The same problem as Input(Bias)
about tensor's shape.
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.
Fixed.
paddle/operators/nce_op.cc
Outdated
"sample is 1.") | ||
.AsDispensable(); | ||
AddOutput("Cost", | ||
"(Tensor) A tensor of shape [batch_size]. Cost of samples."); |
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.
The same problem as Input(Bias) about tensor's shape.
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.
Fixed.
paddle/operators/nce_op.cc
Outdated
.SetDefault(10); | ||
AddAttr<std::vector<int>>("sampled_labels", ""); | ||
AddComment(R"DOC( | ||
Computes and returns the noise-contrastive estimation training loss. |
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.
Compute and return
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.
Fixed.
paddle/operators/nce_op.cc
Outdated
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. */ |
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.
Please make the indention of license follows that in accuracy_op.h
.
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.
Fixed.
paddle/operators/nce_op.cc
Outdated
AddOutput("Cost", | ||
"(Tensor) A tensor of shape [batch_size]. Cost of samples."); | ||
AddOutput("SampleLogits", "An intermediate tensor.").AsIntermediate(); | ||
AddOutput("SampleLabels", "An intermediate tensor.").AsIntermediate(); |
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.
Comments on Output(SampleLogits)
and Output(SampleLabels)
. What are these intermediate outputs used for?
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.
Fixed by adding more comments.
paddle/operators/nce_op.cc
Outdated
PADDLE_ENFORCE(ctx->HasInput("SampleLogits")); | ||
PADDLE_ENFORCE(ctx->HasInput("SampleLabels")); | ||
PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Cost")), | ||
"The input(Out@GRAD) should not be null"); |
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.
If the comment is a complete sentence, please add a period at the end of the sentence.
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.
Fixed.
namespace paddle { | ||
namespace operators { | ||
|
||
using Tensor = framework::Tensor; |
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.
using framework::Tensor;
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.
Fixed.
public: | ||
NCEOpMaker(framework::OpProto* proto, framework::OpAttrChecker* op_checker) | ||
: OpProtoAndCheckerMaker(proto, op_checker) { | ||
AddInput("Input", "(Tensor) A tensor of shape [batch_size, dim]."); |
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 have a question here. From the current implementation, this operator only supports uniform distribution which is hardcoded. How can we extend the codes to support more distribution? Should we make distribution method an attribute, or leave the sampling process outside this operator? What is your suggestion?
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.
Yes. You are right. More distribution sampler is necessary. The terms in NLP application always meet heavy-tailed distribution. So we need a long uniform distribution sampler. And the distribution`s PDF is 1/(x+1)lnR in which R is the range of sampling. I will implement the log uniform sampler and other common distribution samplers as independent math function in another pr.
1. Remove checking for num_neg_samples. 2. Fix dims of Output(Cost) and Input(Bias). 3. Renamed num_sampled_classes to num_neg_samples. 4. Add TODO for add more distribution sampler. 5. Init grad_data of bias by zero. 6. Refine comments. 7. Register a kernel for type double.
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.
LGTM
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. */ |
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.
The indentation should like that in nce_op.cc
Fix #5479