Merge branch 'develop' of https://github.com/PaddlePaddle/paddle into add-NormOp
After Width: | Height: | Size: 57 KiB |
Before Width: | Height: | Size: 58 KiB After Width: | Height: | Size: 56 KiB |
Before Width: | Height: | Size: 50 KiB After Width: | Height: | Size: 49 KiB |
Before Width: | Height: | Size: 32 KiB After Width: | Height: | Size: 30 KiB |
@ -0,0 +1,105 @@
|
||||
## Optimizer Design
|
||||
|
||||
### The Problem
|
||||
|
||||
A PaddlePaddle program, or a block, is a sequence of operators operating variables. A training program needs to do three kinds of works:
|
||||
|
||||
1. the forward pass, which computes intermediate results and the cost(s),
|
||||
1. the backward pass, which derives gradients from intermediate results and costs, and
|
||||
1. the optimization pass, which update model parameters to optimize the cost(s).
|
||||
|
||||
These works rely on three kinds of operators:
|
||||
|
||||
1. forward operators,
|
||||
1. gradient operators, and
|
||||
1. optimization operators.
|
||||
|
||||
It's true that users should be able to create all these operators manually by calling some low-level API, but it would be much more convenient if they could only describe the forward pass and let PaddlePaddle create the backward and optimization operators automatically.
|
||||
|
||||
In this design, we propose a high-level API that automatically derives the optimisation pass and operators from the forward pass.
|
||||
|
||||
|
||||
### High-level Python API to describe the training process
|
||||
|
||||
1. User write code to describe the network:
|
||||
|
||||
```python
|
||||
images = layer.data("images")
|
||||
labels = layer.data("labels")
|
||||
w1 = pd.var("w1")
|
||||
b1 = pd.var("b1")
|
||||
hidden = layer.fc(images, w=w1, b=b1)
|
||||
cost = layer.mse(hidden, labels)
|
||||
```
|
||||
|
||||
The above code snippet will create forward operators in [Block](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/design/block.md).
|
||||
|
||||
|
||||
2. Users create a certain kind of Optimizer with some argument.
|
||||
|
||||
```python
|
||||
optimizer = AdagradOptimizer(learing_rate=0.001)
|
||||
```
|
||||
|
||||
3. Users use the optimizer to `minimize` a certain `cost` through updating parameters in parameter_list.
|
||||
|
||||
```python
|
||||
opt_op_list = optimizer.minimize(cost, parameter_list=[w1, b1])
|
||||
```
|
||||
The above code snippet will create gradient and optimization operators in Block. The return value of `minimize()` is list of optimization operators that will be run by session.
|
||||
|
||||
4. Users use Session/Executor to run this opt_op_list as target to do training.
|
||||
|
||||
```python
|
||||
sess.run(target= opt_op_list, ...)
|
||||
```
|
||||
|
||||
#### Optimizer Python interface:
|
||||
|
||||
```python
|
||||
class Optimizer(object):
|
||||
"""Optimizer Base class.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def create_backward_pass(self, loss, parameter_list=None):
|
||||
"""
|
||||
create and add gradient Operators in BlockDesc to Compute gradients of `loss`
|
||||
for parameters in parameter_list
|
||||
|
||||
Args:
|
||||
loss: an variable generated by cost function.
|
||||
parameter_list: parameters that need to compute gradient and update to optimize the lost.
|
||||
|
||||
Returns:
|
||||
list of (parameters, gradients) pair.
|
||||
"""
|
||||
return None
|
||||
|
||||
def create_optimization_pass(self, parameters_and_grads):
|
||||
"""Add optimization operators to update gradients to variables.
|
||||
|
||||
Args:
|
||||
parameters_and_grads: a list of (variable, gradient) pair to update.
|
||||
|
||||
Returns:
|
||||
optmization_op_list: a list of optimization operator that will update parameter using gradient.
|
||||
"""
|
||||
return None
|
||||
|
||||
def minimize(self, loss, parameter_list):
|
||||
"""Add operations to minimize `loss` by updating `parameter_list`.
|
||||
|
||||
This method combines interface `create_backward_pass()` and
|
||||
`create_optimization_pass()` into one.
|
||||
"""
|
||||
params_grads = self.create_backward_pass(loss, parameter_list)
|
||||
update_ops = self.create_optimization_pass(params_grads)
|
||||
return update_ops
|
||||
|
||||
```
|
||||
|
||||
Users can inherit the Optimizer above to create their own Optimizer with some special logic, such as AdagradOptimizer.
|
@ -0,0 +1,220 @@
|
||||
# Design Doc: Python API
|
||||
|
||||
Due to the refactorization of the PaddlePaddle core, we need Python classes to construct corresponding protobuf messages that describe a DL program.
|
||||
|
||||
| Python classes | Protobuf messages |
|
||||
| --- | --- |
|
||||
| Program | ProgramDesc |
|
||||
| Block | BlockDesc |
|
||||
| Operator | OpDesc |
|
||||
| Variable | VarDesc |
|
||||
|
||||
Please be aware that these Python classes need to maintain some construction-time information, which are not part of the protobuf messages.
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### Program
|
||||
|
||||
A `ProgramDesc` describes a [DL program](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/design/program.md), which is composed of an array of `BlockDesc`s. The `BlockDesc`s in a `ProgramDesc` can have a tree-like hierarchical structure. However, the `ProgramDesc` onlys stores a flattened array of `BlockDesc`s. A `BlockDesc` refers to its parent block by its index in the array. For example, operators in the step block of an RNN operator need to be able to access variables in its ancestor blocks.
|
||||
|
||||
Whenever we create a block, we need to set its parent block to the current block, hence the Python class `Program` needs to maintain a data member `current_block`.
|
||||
|
||||
```python
|
||||
class Program(objects):
|
||||
def __init__(self):
|
||||
self.desc = core.NewProgram() # a C++ ProgramDesc pointer.
|
||||
self.blocks = vector<Block>()
|
||||
self.blocks.append(Block(self, -1)) # the global block
|
||||
self.current_block = 0 # initialized to the global block
|
||||
|
||||
def global_block():
|
||||
return self.blocks[0]
|
||||
|
||||
def current_block():
|
||||
return self.get_block(self.current_block)
|
||||
|
||||
def rollback():
|
||||
self.current_block = self.current_block().parent_idx
|
||||
|
||||
def create_block():
|
||||
new_block_idx = len(self.block)
|
||||
self.blocks.append(Block(self, self.current_block))
|
||||
self.current_block = new_block_idx
|
||||
return current_block()
|
||||
```
|
||||
|
||||
`Program` is an accessor to the protobuf message `ProgramDesc`, which is created in C++ space, because the InferShape function is in C++, which manipulates `VarDesc` messages, which are in turn members of `BlockDesc`, which is a member of `ProgramDesc`.
|
||||
|
||||
`Program` creates the first block as the global block in its constructor. All parameters and their initializer operators are in the global block.
|
||||
|
||||
### Block
|
||||
|
||||
A [Block](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/design/block.md) includes
|
||||
|
||||
1. a map from variable names to an instance of the Python `Variable` class, and
|
||||
1. a list of `Operator` instances.
|
||||
|
||||
```python
|
||||
class Block(objects):
|
||||
def __init__(self, program, parent_idx):
|
||||
self.desc = core.NewBlock(program.desc)
|
||||
self.program = program
|
||||
self.vars = map<string, Variable>()
|
||||
self.ops = vector<Operator>()
|
||||
self.parent_idx = parent_idx
|
||||
|
||||
def create_var(self, ...):
|
||||
return Variable(self, ...)
|
||||
|
||||
def _create_global_var(self, ...):
|
||||
program.global_block().create_var(...)
|
||||
|
||||
def create_parameter(self, name, ...):
|
||||
# Parameter is a subclass of variable. See Parameter section for details.
|
||||
self.vars[name] = Parameter(self._create_global_var(...), ...)
|
||||
return self.vars[name]
|
||||
|
||||
def append_operator(self, ...):
|
||||
self.ops.append(Operator(self, ...))
|
||||
|
||||
def prepend_operator(self, ...): # Parameter's ctor prepands initialize operators.
|
||||
self.ops.prepend(Operator(self, ...))
|
||||
```
|
||||
|
||||
`create_parameter` is necessary because parameters are global variables, defined in the global block, but can be created in some sub-blocks. For example, an FC layer in the step block of an RNN operator.
|
||||
|
||||
`prepend_operator` is necessary because the constructor of `Parameter` needs to create the initialize (or load) operator of the parameter, and would like to put it in the *preamble* of the global block.
|
||||
|
||||
### Operator
|
||||
|
||||
The `Operator` class fills in the `OpDesc` message and calls the C++ function `InferShape` to infer the output shapes from the input shapes.
|
||||
|
||||
```python
|
||||
class Operator(object):
|
||||
def __init__(self,
|
||||
block, # Block
|
||||
type, # string
|
||||
inputs, # dict<string, Variable>
|
||||
outputs,# dict<stirng, Variable>
|
||||
attrs # dict<string, Any>
|
||||
):
|
||||
self.desc = core.NewOpDesc(block.desc, type, inputs, outputs, attrs)
|
||||
core.infer_shape(self.desc, inputs, outputs)
|
||||
|
||||
def type(self):
|
||||
return self.desc.type()
|
||||
```
|
||||
|
||||
`Operator` creates the `OpDesc` message in C++ space, so that it can call the `InferShape` function, which is in C++.
|
||||
|
||||
### Variable
|
||||
|
||||
Operators take Variables as its inputs and outputs.
|
||||
|
||||
```python
|
||||
class Variable(object):
|
||||
def __init__(self,
|
||||
block=None, # Block
|
||||
name=None, # string
|
||||
shape, # tuple
|
||||
dtype="float32", # string
|
||||
lod_level=None # int
|
||||
):
|
||||
if name is None:
|
||||
name = unique_name_generator()
|
||||
self.name = name
|
||||
self.block = block
|
||||
self.desc = core.NewVarDesc(block.desc, name, shape, lod_level)
|
||||
self.writer = None
|
||||
```
|
||||
|
||||
Please be aware of `self.writer`, that tracks operator who creates the variable. It possible that there are more than one operators who write a variable, but in Python space, each write to a variable is represented by a Variable class. This is guaranteed by the fact that **`core.NewVarDesc` must NOT create a new `VarDesc` message if its name already exists in the specified block**.
|
||||
|
||||
### Parameter
|
||||
|
||||
A parameter is a global variable with an initializer (or load) operator.
|
||||
|
||||
```python
|
||||
class Parameter(Variable):
|
||||
def __init__(self,
|
||||
block=None, # Block
|
||||
name=None, # string
|
||||
shape, # tuple
|
||||
dtype="float32", # string
|
||||
lod_level=None # int
|
||||
trainable, # bool
|
||||
initialize_op_attrs,
|
||||
optimize_op_attrs):
|
||||
super(Parameter, self).__init__(block, name, shape, dtype, lod_level)
|
||||
self.trainable = trainable
|
||||
self.optimize_op_attrs = optimize_op_attrs
|
||||
block.prepend(Operator(block, # Block
|
||||
initialize_op_attrs['type'], # string
|
||||
None, # no inputs
|
||||
self, # output is the parameter
|
||||
initialize_op_attrs)
|
||||
```
|
||||
|
||||
When users create a parameter, they can call
|
||||
|
||||
```python
|
||||
program.create_parameter(
|
||||
...,
|
||||
init_attr={
|
||||
type: "uniform_random",
|
||||
min: -1.0,
|
||||
max: 1.0,
|
||||
})
|
||||
)
|
||||
```
|
||||
|
||||
In above example, `init_attr.type` names an initialize operator. It can also name the load operator
|
||||
|
||||
```python
|
||||
init_attr={
|
||||
type: "load",
|
||||
filename: "something.numpy",
|
||||
}
|
||||
```
|
||||
|
||||
`optimize_op_attrs` is not in the `VarDesc` message, but kept in the Python instance, as it will be used in the Python space when creating the optimize operator's `OpDesc`, and will be in the `OpDesc` message.
|
||||
|
||||
## Layer Functions
|
||||
|
||||
A layer is a Python function that creates some operators and variables. Layers simplify the work of application programmers.
|
||||
|
||||
### Data Layer
|
||||
|
||||
```python
|
||||
def data_layer(name, type, column_name):
|
||||
block = the_current_program.glolal_block()
|
||||
var = block.create_global_var(
|
||||
name=name,
|
||||
shape=[None] + type.dims(),
|
||||
dtype=type.dtype)
|
||||
block.prepend_operator(block,
|
||||
type="Feed",
|
||||
inputs = None,
|
||||
outputs = [var],
|
||||
{column_name: column_name})
|
||||
return var
|
||||
```
|
||||
|
||||
The input to the feed operator is a special variable in the global scope, which is the output of [Python readers](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/design/reader/README.md).
|
||||
|
||||
### FC Layer
|
||||
|
||||
```python
|
||||
def fc_layer(input, size, ...):
|
||||
block = program.current_block()
|
||||
w = block.create_parameter(...)
|
||||
b = block.create_parameter(...)
|
||||
out = block.create_var()
|
||||
op = block.append_operator("FC", X=input, W=w, b=b, out=out)
|
||||
out.writer = op
|
||||
return out
|
||||
```
|
||||
|
||||
## Optimizer
|
||||
|
||||
[Optimizer Design Doc](./optimizer.md)
|
@ -0,0 +1,180 @@
|
||||
# Design Doc: Session
|
||||
|
||||
## Abstract
|
||||
|
||||
The *session* object encapsulates the environment in which the
|
||||
computation graph is executed.
|
||||
|
||||
We will have the *local* session and *remote* session, they offer the
|
||||
same [interface](#interface). The local session encapsulates the local
|
||||
runtime environment and the remote session encapsulates the cluster
|
||||
runtime environment.
|
||||
|
||||
The local runtime environment contains:
|
||||
|
||||
1. computation devices (i.e., CPU, GPU) handles, and
|
||||
1. the [scope](../scope.md) which holds all variables.
|
||||
|
||||
The remote runtime environment contains:
|
||||
|
||||
1. computation devices (i.e., CPU and GPU on node 0, 1) in a cluster,
|
||||
and
|
||||
1. the distributed [scope](../scope.md) in a cluster which holds all
|
||||
variables.
|
||||
|
||||
The user can create a remote session on Paddle Cloud and evaluate the
|
||||
computation graph with it. In this way, the user can control the
|
||||
remote computation resource in a cluster from his local computer.
|
||||
|
||||
|
||||
## Background
|
||||
|
||||
The current design has an implicit global session in which
|
||||
`paddle.eval()` is executed. The pain point is:
|
||||
|
||||
Since the user is not able to explicitly switch between runtime
|
||||
environments, the user cannot run a topology in two independent
|
||||
environments.
|
||||
|
||||
For example, in reinforcement learning, the user may want to have a
|
||||
stale model for inference and a fresh model for training, and only
|
||||
replace the stale model with the fresh model periodically.
|
||||
|
||||
Furthermore, we have no concept that encapsulates a remote environment
|
||||
that executes a computation graph.
|
||||
|
||||
We need the session object to address above issues.
|
||||
|
||||
|
||||
## Session
|
||||
|
||||
A session is an object that owns the runtime environment. All
|
||||
computations are executed through `session.eval()`.
|
||||
|
||||
|
||||
### Interface
|
||||
|
||||
```python
|
||||
eval(
|
||||
targets,
|
||||
feed_dict=None,
|
||||
)
|
||||
```
|
||||
|
||||
Evaluates the target Operations or Variables in `targets`.
|
||||
|
||||
- *targets*: the evaluation targets. Can be a single Operation or
|
||||
Variable, or a list with the Operations or Variables as
|
||||
elements. The value returned by `eval()` has the same shape as the
|
||||
`target` argument.
|
||||
|
||||
The PaddlePaddle program is represented by
|
||||
the [ProgramDesc](../design/program.md), `eval()` will infer the
|
||||
ProgramDesc from the given targets and run the PaddlePaddle
|
||||
program. Please
|
||||
see
|
||||
[this graph](./distributed_architecture.md#local-training-architecture) for
|
||||
the detailed illustration for the local session
|
||||
and
|
||||
[this graph](./distributed_architecture.md#distributed-training-architecture) for
|
||||
the detailed illustration for the remote session.
|
||||
|
||||
- *feed_dict*: a dictionary that contains the tensors which override
|
||||
the edges of the computation graph.
|
||||
|
||||
feed_dict not only can provide the input data, it can override any
|
||||
OP's input as well:
|
||||
|
||||
```python
|
||||
a = pd.constant(2.0, name="a")
|
||||
b = pd.variable(name="b")
|
||||
c = pd.mul(a,b)
|
||||
sess.eval(targets=c, feed_dict={"b":3.0}) # returns 6.0
|
||||
```
|
||||
|
||||
```python
|
||||
close()
|
||||
```
|
||||
|
||||
Closes the session and releases the scope that the session owns.
|
||||
|
||||
|
||||
### Create a Local Session
|
||||
|
||||
```python
|
||||
session(
|
||||
devices=None
|
||||
)
|
||||
```
|
||||
|
||||
Creates a new session. One session owns one global scope, so creating
|
||||
multiple sessions will create different scopes.
|
||||
|
||||
- *devices*: a single `string` or a list of `string` of device names,
|
||||
the corresponding devices will be the computation devices for
|
||||
`eval()`. If not specified, all available devices (e.g., all GPUs)
|
||||
will be used. The user doesn't need to specify the CPU device since
|
||||
it will be always used. Multiple sessions can use the same device.
|
||||
|
||||
|
||||
#### Example
|
||||
|
||||
```Python
|
||||
a = paddle.constant(1.0)
|
||||
b = paddle.constant(2.0)
|
||||
c = a + b
|
||||
sess = paddle.session(devices=["gpu:0", "gpu:1", "fpga:0"])
|
||||
sess.eval(c)
|
||||
sess.close()
|
||||
```
|
||||
|
||||
### Create a Remote Session
|
||||
|
||||
```python
|
||||
create_cloud_job(
|
||||
name,
|
||||
num_trainer,
|
||||
mem_per_trainer,
|
||||
gpu_per_trainer,
|
||||
cpu_per_trainer,
|
||||
num_ps,
|
||||
mem_per_ps,
|
||||
cpu_per_ps,
|
||||
)
|
||||
```
|
||||
|
||||
Creates a Paddle Cloud job. Fails if the job name exists.
|
||||
|
||||
```python
|
||||
get_cloud_job(
|
||||
name
|
||||
)
|
||||
```
|
||||
|
||||
Gets a Paddle Cloud job.
|
||||
|
||||
```python
|
||||
remote_session(
|
||||
job
|
||||
)
|
||||
```
|
||||
|
||||
- *job*: the Paddle Cloud job.
|
||||
|
||||
#### Example
|
||||
|
||||
```Python
|
||||
reader = paddle.reader.recordio("/pfs/home/peter/mnist-train-*") # data stored on Paddle Cloud
|
||||
image = reader.column(0)
|
||||
label = reader.column(1)
|
||||
fc1 = paddle.op.fc(image, size=256, act="sigmoid")
|
||||
fc2 = paddle.op.fc(fc1, size=10, act="softmax")
|
||||
cost = paddle.op.cross_entropy(fc2, label)
|
||||
opt = paddle.optimizer.sgd(cost)
|
||||
|
||||
job = paddle.create_cloud_job("test", 3, "1G", 1, 1, 2, "1G", 1)
|
||||
sess = paddle.remote_ession(job)
|
||||
for i in range(1000):
|
||||
sess.eval(opt)
|
||||
sess.close()
|
||||
```
|
@ -0,0 +1,90 @@
|
||||
# Design Doc: Gradient Operators Registration
|
||||
|
||||
|
||||
## The Problem Posed
|
||||
|
||||
In our current operator registration mechanism, for each operator, the programmer should register a *gradient operator creator* function, which takes a C++ operator instance, and returns the corresponding gradient instance.
|
||||
|
||||
However, as we decided to separate the *compilation* and *execution* of DL models, we need to reshape the creator to take a protobuf `OpDesc` message, and returns a corresponding message.
|
||||
|
||||
More than that, the new registration mechanism need to support the fact that an operators' gradient computation might be a composition of operators.
|
||||
|
||||
## Current Implementation
|
||||
|
||||
OpInfos store in a association map which key is the operator type. The `grad_op_type` indicate associated gradient operator type. Operator can create gradient operator by `OpInfo::creator_` of gradient. The pseudo code is
|
||||
|
||||
```cpp
|
||||
struct OpInfo {
|
||||
std::function<OperatorBase*(...)> creator_;
|
||||
std::string grad_op_type_;
|
||||
...
|
||||
};
|
||||
|
||||
map<string, OpInfo> OpInfoMap;
|
||||
|
||||
OperatorBase* CreateGradientOperator(const OperatorBase& op) {
|
||||
return OpInfoMap.at(op.Type()).creator_(...);
|
||||
}
|
||||
```
|
||||
|
||||
## Proposed Solution
|
||||
|
||||
The mapping relationship between an operator and its gradient operators is a function. The interface of that function is:
|
||||
|
||||
```cpp
|
||||
// (OpDesc) --> vector<OpDesc>
|
||||
std::function<std::vector<OpDescBind>(const OpDescBind&)>;
|
||||
```
|
||||
|
||||
The function takes an `OpDescBind` of the forward operator and returns one or many gradient operator descriptions. `OpDescBind` is a C++ wrapper for protobuf message `OpDesc` to manipulate `OpDesc` fast.
|
||||
|
||||
The `GradOpDescMaker` will be registered in `OpInfo`, to replace `grad_op_type_` field. The `OpInfo` should be
|
||||
|
||||
```cpp
|
||||
struct OpInfo {
|
||||
std::function<std::vector<std::unique_ptr<OpDescBind>>(const OpDescBind&)> grad_op_maker_;
|
||||
...
|
||||
};
|
||||
```
|
||||
|
||||
The `grad_op_maker_ ` is `nullptr` if the operator does not have associated gradient operators.
|
||||
|
||||
We propose a base class called `GradOpDescMakerBase` to let operator developers generate `Gradient Operators` easily. The public interface of that class is
|
||||
|
||||
```cpp
|
||||
class GradOpDescMakerBase {
|
||||
public:
|
||||
GradOpDescMakerBase(const OpDescBind& );
|
||||
virtual std::vector<std::unique_ptr<OpDescBind>> operator()()const = 0;
|
||||
};
|
||||
```
|
||||
|
||||
We can convert `GradOpDescMakerBase` to `std::function<std::vector<std::unique_ptr<OpDescBind>>(const OpDescBind&)>` by
|
||||
|
||||
```cpp
|
||||
using GradOpMaker = ...;
|
||||
std::function<std::vector<OpDescBind>(const OpDescBind&)> func;
|
||||
func = [] (const OpDescBind& fwd_op) {
|
||||
GradOpMaker maker(fwd_op);
|
||||
return maker();
|
||||
};
|
||||
```
|
||||
|
||||
We can write many helper functions since the `GradOpDescMakerBase` is a class now. The basic helper functions get the variables of `Input`, `Output`, `InputGradient` and `OutputGradient` in the forwarding operator.
|
||||
|
||||
We should chagne register macros at the same time. In the current solution, there is no difference between forwarding operators and backward operators. So `REGISTER_OP` just register one operator. If the `REGISTER_OPERATOR ` contains `OpProtoAndCheckerMaker` and `GradOpDescMaker`, we just list them in the same macro. It can be done by a macro contains `__VA_ARGS__`.
|
||||
|
||||
The user interface should be
|
||||
|
||||
```cpp
|
||||
vector<OpDesc> MinusOpGradMaker(OpDesc) {...}
|
||||
REGISTER_OPERATOR(minus, MinusOp, MinusOpProtoAndCheckerMaker, SumOpGradMaker);
|
||||
// Developers can still manually implement gradient operator.
|
||||
REGISTER_OPERATOR(minus_grad, MinusGradOp);
|
||||
```
|
||||
|
||||
The interface of current `REGISTER_OP` macro could not be changed. In `REGISTER_OP`, it will invoke `REGISTER_OPERATOR` two times and generate GradOpDescMaker inside.
|
||||
|
||||
```cpp
|
||||
REGISTER_OP(minus, MinusOp, MinusOpProtoAndCheckerMaker, minus_grad, MinusGradOp);
|
||||
```
|
@ -0,0 +1,74 @@
|
||||
# Design Doc: Selected Rows
|
||||
|
||||
`SelectedRows` is a kind of sparse tensor data type, which is designed to support `embedding` operators. The gradient of embedding table is a sparse tensor. Only a few rows are non-zero values in that tensor. It is straightforward to represent the sparse tensor by the following sparse tensor data structure:
|
||||
|
||||
```cpp
|
||||
class SelectedRows {
|
||||
private:
|
||||
vector<int> rows_;
|
||||
Tensor value_;
|
||||
int height_;
|
||||
};
|
||||
```
|
||||
|
||||
The field `height_` shows the first dimension of `SelectedRows`. The `rows` are the indices of which rows of `SelectedRows` are non-zeros. The `value_` field is an N-dim tensor and shape is `[rows.size() /* NUM_ROWS */, ...]`, which supplies values for each row. The dimension of `SelectedRows` satisfies `[height_] + value_.shape[1:]`.
|
||||
|
||||
Suppose that a SelectedRows-typed variable `x` has many rows, but only two of them have values -- row 73 is `[1, 2]` and row 84 is `[3, 4]`, the `SelectedRows` representation would be:
|
||||
|
||||
```
|
||||
x = SelectedRow {
|
||||
rows = [73, 84],
|
||||
value = [[1, 2], [3,4]]
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## SelectedRows in Protobuf
|
||||
|
||||
`SelectedRows` is a kind of `Variable`. `VarDesc` in protobuf should describe the `SelectedRows` information. Only the tensor dimension of a `SelectedRows` will be described in compile-time since the `rows_` and `value_` are related to training data.
|
||||
So we use `TensorDesc` to unify `data_type` and `dims`. A LodTensorDesc contains a `TensorDesc` and `lod_level`. The description of `SelectedRows` is a Tensor description.
|
||||
|
||||
```proto
|
||||
message TensorDesc {
|
||||
required DataType data_type = 1;
|
||||
repeated int64 dims = 2; // [UNK, 640, 480] is saved as [-1, 640, 480]
|
||||
}
|
||||
|
||||
message LodTensorDesc {
|
||||
required TensorDesc tensor = 1;
|
||||
optional int lod_level = 2;
|
||||
}
|
||||
|
||||
message VarDesc {
|
||||
required string name = 1;
|
||||
enum VarType {
|
||||
LOD_TENSOR = 0;
|
||||
SELECTED_ROWS = 1;
|
||||
}
|
||||
required VarType type = 2;
|
||||
optional LodTensorDesc lod_desc = 3;
|
||||
optional TensorDesc selected_rows_desc = 4;
|
||||
optional bool persistable = 5 [ default = false ];
|
||||
}
|
||||
```
|
||||
|
||||
## InferShape for Selected Rows
|
||||
|
||||
Just like `LoD` information, `InferShape` method will inference output tensor type as well. The operator should decide whether its output is a `SelectedRows` or `Dense` tensor.
|
||||
|
||||
For example, the gradient operator of `TableLookup` will always generate `SelectedRows`. Its `InferShape` method should be like following
|
||||
|
||||
```cpp
|
||||
void TableLookupGrad::InferShape(context) {
|
||||
...
|
||||
context.SetDataType("Embedding.Grad", kSelectedRows);
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Sparse Operators
|
||||
|
||||
There are several operators should be written to support `SelectedRows`. They are:
|
||||
|
||||
1. Operators which generates `SelectedRows` gradient. e.g. Gradient of `TableLookupOp`.
|
||||
2. Optimize operators which support `SelectedRows` gradient. e.g. `SGD` or `AdaGrad` for `SelectedRows`. However, there should be only one `SGD` operator. `OpWithKernel::Run` should select a suitable kernel for both `dense` tensor or `SelectedRows`.
|
@ -0,0 +1,35 @@
|
||||
|
||||
digraph Test {
|
||||
z -> generator -> G_img;
|
||||
G_img -> discriminator -> D_f -> d_loss_f;
|
||||
label0 -> d_loss_f -> d_loss;
|
||||
|
||||
img -> discriminator -> D_t -> d_loss_t;
|
||||
label1 -> d_loss_t -> d_loss;
|
||||
|
||||
d_loss -> d_loss_t[color=red, style=dashed];
|
||||
d_loss -> d_loss_f[color=red, style=dashed];
|
||||
d_loss_t -> D_t[color=red, style=dashed];
|
||||
d_loss_f -> D_f[color=red, style=dashed];
|
||||
D_t -> discriminator[color=red, style=dashed];
|
||||
D_f -> discriminator[color=red, style=dashed];
|
||||
|
||||
D_f -> g_loss;
|
||||
label2 -> g_loss;
|
||||
|
||||
g_loss -> D_f[color=green, style=dashed];
|
||||
D_f -> discriminator[color=green, style=dashed];
|
||||
discriminator -> G_img[color=green, style=dashed];
|
||||
G_img -> generator[color=green, style=dashed];
|
||||
|
||||
discriminator [color=red, shape=box];
|
||||
generator [color=green, shape=box];
|
||||
z [shape=diamond];
|
||||
img [shape=diamond];
|
||||
label0 [shape=diamond];
|
||||
label1 [shape=diamond];
|
||||
label2 [shape=diamond];
|
||||
|
||||
d_loss [color=red];
|
||||
g_loss [color=green];
|
||||
}
|
After Width: | Height: | Size: 58 KiB |