pytorch/caffe2/python/layers/batch_lr_loss.py
Xianjie Chen d0621a2449 NextScopedBlob with well-defined behavior and respect namescope
Summary:
Remove the use of `NextName` in layer model helper, so that the same function return `model_helper` that should construct identical `Net`, when under the same NameScope.

The `NextScopedBlob` should only take effect when there is real name conflicting, otherwise it returns ScopedBlobReference.

This is critical for parameter blobs. In long run, we need to be able to specify parameter blobs more explicitly. (kennyhorror is working on this). This solution works in short term for e.g., two tower sparse nn models.

Reviewed By: kennyhorror

Differential Revision: D4555423

fbshipit-source-id: 2c4b99a61392e5d51aa878f7346466a8f14be187
2017-02-16 17:16:36 -08:00

50 lines
1.5 KiB
Python

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, schema
from caffe2.python.layers.layers import (
ModelLayer,
)
from caffe2.python.layers.tags import (
Tags
)
import numpy as np
class BatchLRLoss(ModelLayer):
def __init__(self, model, input_record, name='batch_lr_loss', **kwargs):
super(BatchLRLoss, self).__init__(model, name, input_record, **kwargs)
schema.is_schema_subset(
schema.Struct(
('label', schema.Scalar()),
('prediction', schema.Scalar())
),
input_record
)
self.tags.update({Tags.TRAIN_ONLY})
self.output_schema = schema.Scalar(
np.float32,
model.net.NextScopedBlob(name + '_output'))
# This should be a bit more complicated than it is right now
def add_ops(self, net):
class_probabilities = net.MakeTwoClass(
self.input_record.prediction.field_blobs(),
net.NextScopedBlob('two_class_predictions')
)
label = self.input_record.label.field_blobs()
if self.input_record.label.field_types()[0] != np.int32:
label = [
net.Cast(label, net.NextScopedBlob('int32_label'), to='int32')]
xent = net.LabelCrossEntropy(
[class_probabilities] + label,
net.NextScopedBlob('cross_entropy'),
)
net.AveragedLoss(xent, self.output_schema.field_blobs())