code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def image(self, src, title, text):
"""Rendering a image with title and text.
:param src: source link of the image.
:param title: title text of the image.
:param text: alt text of the image.
"""
# rst does not support title option
# and I couldn't find title attri... | Rendering a image with title and text.
:param src: source link of the image.
:param title: title text of the image.
:param text: alt text of the image.
| image | python | PaddlePaddle/PaddleRec | doc/markdown2rst.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/doc/markdown2rst.py | Apache-2.0 |
def footnotes(self, text):
"""Wrapper for all footnotes.
:param text: contents of all footnotes.
"""
if text:
return '\n\n' + text
else:
return '' | Wrapper for all footnotes.
:param text: contents of all footnotes.
| footnotes | python | PaddlePaddle/PaddleRec | doc/markdown2rst.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/doc/markdown2rst.py | Apache-2.0 |
def run(self):
"""Most of this method is from ``docutils.parser.rst.Directive``.
docutils version: 0.12
"""
if not self.state.document.settings.file_insertion_enabled:
raise self.warning('"%s" directive disabled.' % self.name)
source = self.state_machine.input_lines.... | Most of this method is from ``docutils.parser.rst.Directive``.
docutils version: 0.12
| run | python | PaddlePaddle/PaddleRec | doc/markdown2rst.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/doc/markdown2rst.py | Apache-2.0 |
def save_static_model(program, model_path, epoch_id, prefix='rec_static'):
"""
save model to the target path
"""
model_path = os.path.join(model_path, str(epoch_id))
_mkdir_if_not_exist(model_path)
model_prefix = os.path.join(model_path, prefix)
paddle.static.save(program, model_prefix)
... |
save model to the target path
| save_static_model | python | PaddlePaddle/PaddleRec | models/demo/movie_recommand/utils/save_load.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/demo/movie_recommand/utils/save_load.py | Apache-2.0 |
def _compute_expert_weights(self):
"""Computes the weight vector for the experts.
Args: None.
Returns:
A tuple: (expert_weights, selector_outputs).
expert_weights is the final weight vector of the experts.
selector_outputs is a (num_nonzero, num_experts)-matrix ... | Computes the weight vector for the experts.
Args: None.
Returns:
A tuple: (expert_weights, selector_outputs).
expert_weights is the final weight vector of the experts.
selector_outputs is a (num_nonzero, num_experts)-matrix whose i-th row
represents the outp... | _compute_expert_weights | python | PaddlePaddle/PaddleRec | models/multitask/dselect_k/net.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/multitask/dselect_k/net.py | Apache-2.0 |
def _compute_example_conditioned_expert_weights(self, routing_inputs):
"""Computes the example-conditioned weights for the experts.
Args:
routing_inputs: a tensor of shape=(batch_size, num_features) containing
the input examples.
Returns:
A tuple: (expert_weig... | Computes the example-conditioned weights for the experts.
Args:
routing_inputs: a tensor of shape=(batch_size, num_features) containing
the input examples.
Returns:
A tuple: (expert_weights, selector_outputs).
expert_weights is a tensor with shape=(batch_s... | _compute_example_conditioned_expert_weights | python | PaddlePaddle/PaddleRec | models/multitask/dselect_k/net.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/multitask/dselect_k/net.py | Apache-2.0 |
def reset(self):
"""
Resets all of the metric state.
"""
self.loss = 0
self.n = 0 |
Resets all of the metric state.
| reset | python | PaddlePaddle/PaddleRec | models/rank/autofis/metrics.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/autofis/metrics.py | Apache-2.0 |
def positionwise_feed_forward(self, x, dropout_rate):
"""
Position-wise Feed-Forward Networks.
This module consists of two linear transformations with a ReLU activation
in between, which is applied to each position separately and identically.
"""
pff_input = x
for... |
Position-wise Feed-Forward Networks.
This module consists of two linear transformations with a ReLU activation
in between, which is applied to each position separately and identically.
| positionwise_feed_forward | python | PaddlePaddle/PaddleRec | models/rank/bst/net.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/bst/net.py | Apache-2.0 |
def pre_post_process_layer_(self,
prev_out,
out,
process_cmd,
dropout_rate=0.5):
"""
Add residual connection, layer normalization and droput to the out tensor
optionall... |
Add residual connection, layer normalization and droput to the out tensor
optionally according to the value of process_cmd.
This will be used before or after multi-head attention and position-wise
feed-forward networks.
| pre_post_process_layer_ | python | PaddlePaddle/PaddleRec | models/rank/bst/net.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/bst/net.py | Apache-2.0 |
def __compute_qkv(queries, keys, values):
"""
Add linear projection to queries, keys, and values.
"""
q = self.compute_qkv_layer[0](queries)
k = self.compute_qkv_layer[1](keys)
v = self.compute_qkv_layer[2](values)
return q, k, v |
Add linear projection to queries, keys, and values.
| __compute_qkv | python | PaddlePaddle/PaddleRec | models/rank/bst/net.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/bst/net.py | Apache-2.0 |
def __split_heads_qkv(queries, keys, values, n_head, d_key, d_value):
"""
Reshape input tensors at the last dimension to split multi-heads
and then transpose. Specifically, transform the input tensor with shape
[bs, max_sequence_length, n_head * hidden_dim] to the output... |
Reshape input tensors at the last dimension to split multi-heads
and then transpose. Specifically, transform the input tensor with shape
[bs, max_sequence_length, n_head * hidden_dim] to the output tensor
with shape [bs, n_head, max_sequence_length, hidden_dim].
... | __split_heads_qkv | python | PaddlePaddle/PaddleRec | models/rank/bst/net.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/bst/net.py | Apache-2.0 |
def __combine_heads(x):
"""
Transpose and then reshape the last two dimensions of inpunt tensor x
so that it becomes one dimension, which is reverse to __split_heads.
"""
if len(x.shape) != 4:
raise ValueError("Input(x) should be a 4-D Tensor."... |
Transpose and then reshape the last two dimensions of inpunt tensor x
so that it becomes one dimension, which is reverse to __split_heads.
| __combine_heads | python | PaddlePaddle/PaddleRec | models/rank/bst/net.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/bst/net.py | Apache-2.0 |
def generate_sample(self, line):
"""
Read the data line by line and process it as a dictionary
"""
def data_iter():
feat_idx, feat_value, label = self._process_line(line)
s = ""
for i in [('feat_idx', feat_idx), ('feat_value', feat_value),
... |
Read the data line by line and process it as a dictionary
| generate_sample | python | PaddlePaddle/PaddleRec | models/rank/dataset/Criteo_data/get_slot_data.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/dataset/Criteo_data/get_slot_data.py | Apache-2.0 |
def batch_dot(x, y, axes=None):
"""Batchwise dot product.
# >>> x_batch = paddle.ones(shape=(32, 20, 1))
# >>> y_batch = paddle.ones(shape=(32, 30, 20))
# >>> xy_batch_dot = batch_dot(x_batch, y_batch, axes=(1, 2))
# >>> xy_batch_dot.shape
(32, 1, 30)
Shape inference:
Let `x`'s shape be... | Batchwise dot product.
# >>> x_batch = paddle.ones(shape=(32, 20, 1))
# >>> y_batch = paddle.ones(shape=(32, 30, 20))
# >>> xy_batch_dot = batch_dot(x_batch, y_batch, axes=(1, 2))
# >>> xy_batch_dot.shape
(32, 1, 30)
Shape inference:
Let `x`'s shape be `(100, 20)` and `y`'s shape be `(100, ... | batch_dot | python | PaddlePaddle/PaddleRec | models/rank/deepfefm/myutils.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/deepfefm/myutils.py | Apache-2.0 |
def forward(self, dnn_logits, first_order, combined_features):
"""
first_order: FM first order (batch_size, 1)
combined_features: FM sparse features (batch_size, sparse_field_num + 1, embedding_size)
"""
# sum square part
# (batch_size, embedding_size)
summed_feat... |
first_order: FM first order (batch_size, 1)
combined_features: FM sparse features (batch_size, sparse_field_num + 1, embedding_size)
| forward | python | PaddlePaddle/PaddleRec | models/rank/difm/net.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/difm/net.py | Apache-2.0 |
def forward(self, sparse_inputs, dense_inputs):
"""Performs the interaction operation on the tensors in the list.
Args:
sparse_inputs: sparse categorical features, (batch_size, sparse_num_field)
dense_inputs: dense features, (batch_size, dense_feature_dim)
Returns: pred... | Performs the interaction operation on the tensors in the list.
Args:
sparse_inputs: sparse categorical features, (batch_size, sparse_num_field)
dense_inputs: dense features, (batch_size, dense_feature_dim)
Returns: predictions
| forward | python | PaddlePaddle/PaddleRec | models/rank/dlrm/net.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/dlrm/net.py | Apache-2.0 |
def reader():
"""
This function needs to be implemented by the user, based on data format
"""
features = line.rstrip('\n').split('\t')
dense_feature = []
sparse_feature = []
for idx in continuous_range_:
if features[idx]... |
This function needs to be implemented by the user, based on data format
| reader | python | PaddlePaddle/PaddleRec | models/rank/gatenet/data/get_slot_data.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/gatenet/data/get_slot_data.py | Apache-2.0 |
def recv(self, reduce_func, msg, recv_mode="dst"):
"""Recv message and aggregate the message by reduce_func.
The UDF reduce_func function should has the following format.
.. code-block:: python
def reduce_func(msg):
'''
Args:
... | Recv message and aggregate the message by reduce_func.
The UDF reduce_func function should has the following format.
.. code-block:: python
def reduce_func(msg):
'''
Args:
msg: An instance of Message class.
... | recv | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def load(cls, path, mmap_mode="r"):
"""Load Graph from path and return a Graph in numpy.
Args:
path: The directory path of the stored Graph.
mmap_mode: Default :code:`mmap_mode="r"`. If not None, memory-map the graph.
"""
num_nodes = np.load(
o... | Load Graph from path and return a Graph in numpy.
Args:
path: The directory path of the stored Graph.
mmap_mode: Default :code:`mmap_mode="r"`. If not None, memory-map the graph.
| load | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def tensor(self, inplace=True):
"""Convert the Graph into paddle.Tensor format.
In paddle.Tensor format, the graph edges and node features are in paddle.Tensor format.
You can use send and recv in paddle.Tensor graph.
Args:
inplace: (Default True) Whether to conver... | Convert the Graph into paddle.Tensor format.
In paddle.Tensor format, the graph edges and node features are in paddle.Tensor format.
You can use send and recv in paddle.Tensor graph.
Args:
inplace: (Default True) Whether to convert the graph into tensor inplace.
... | tensor | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def numpy(self, inplace=True):
"""Convert the Graph into numpy format.
In numpy format, the graph edges and node features are in numpy.ndarray format.
But you can't use send and recv in numpy graph.
Args:
inplace: (Default True) Whether to convert the graph into nu... | Convert the Graph into numpy format.
In numpy format, the graph edges and node features are in numpy.ndarray format.
But you can't use send and recv in numpy graph.
Args:
inplace: (Default True) Whether to convert the graph into numpy inplace.
| numpy | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def dump(self, path):
"""Dump the graph into a directory.
This function will dump the graph information into the given directory path.
The graph can be read back with :code:`pgl.Graph.load`
Args:
path: The directory for the storage of the graph.
"""
if sel... | Dump the graph into a directory.
This function will dump the graph information into the given directory path.
The graph can be read back with :code:`pgl.Graph.load`
Args:
path: The directory for the storage of the graph.
| dump | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def _dump_feat(feat_path, feat):
"""Dump all features to .npy file.
"""
if len(feat) == 0:
return
if not os.path.exists(feat_path):
os.makedirs(feat_path)
for key in feat:
value ... | Dump all features to .npy file.
| _dump_feat | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def adj_src_index(self):
"""Return an EdgeIndex object for src.
"""
if self._adj_src_index is None:
u = self._edges[:, 0]
v = self._edges[:, 1]
self._adj_src_index = EdgeIndex.from_edges(
u=u, v=v, num_nodes=self._num_nodes)
return self... | Return an EdgeIndex object for src.
| adj_src_index | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def adj_dst_index(self):
"""Return an EdgeIndex object for dst.
"""
if self._adj_dst_index is None:
v = self._edges[:, 0]
u = self._edges[:, 1]
self._adj_dst_index = EdgeIndex.from_edges(
u=u, v=v, num_nodes=self._num_nodes)
return self... | Return an EdgeIndex object for dst.
| adj_dst_index | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def sorted_edges(self, sort_by="src"):
"""Return sorted edges with different strategies.
This function will return sorted edges with different strategy.
If :code:`sort_by="src"`, then edges will be sorted by :code:`src`
nodes and otherwise :code:`dst`.
Args:
sort_b... | Return sorted edges with different strategies.
This function will return sorted edges with different strategy.
If :code:`sort_by="src"`, then edges will be sorted by :code:`src`
nodes and otherwise :code:`dst`.
Args:
sort_by: The type for sorted edges. ("src" or "dst")
... | sorted_edges | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def nodes(self):
"""Return all nodes id from 0 to :code:`num_nodes - 1`
"""
if self._nodes is None:
if self.is_tensor():
self._nodes = paddle.arange(self.num_nodes)
else:
self._nodes = np.arange(self.num_nodes)
return self._nodes | Return all nodes id from 0 to :code:`num_nodes - 1`
| nodes | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def indegree(self, nodes=None):
"""Return the indegree of the given nodes
This function will return indegree of given nodes.
Args:
nodes: Return the indegree of given nodes,
if nodes is None, return indegree for all nodes
Return:
A numpy.nd... | Return the indegree of the given nodes
This function will return indegree of given nodes.
Args:
nodes: Return the indegree of given nodes,
if nodes is None, return indegree for all nodes
Return:
A numpy.ndarray or paddle.Tensor as the given nodes' ... | indegree | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def outdegree(self, nodes=None):
"""Return the outdegree of the given nodes.
This function will return outdegree of given nodes.
Args:
nodes: Return the outdegree of given nodes,
if nodes is None, return outdegree for all nodes
Return:
A nu... | Return the outdegree of the given nodes.
This function will return outdegree of given nodes.
Args:
nodes: Return the outdegree of given nodes,
if nodes is None, return outdegree for all nodes
Return:
A numpy.array or paddle.Tensor as the given node... | outdegree | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def successor(self, nodes=None, return_eids=False):
"""Find successor of given nodes.
This function will return the successor of given nodes.
Args:
nodes: Return the successor of given nodes,
if nodes is None, return successor for all nodes.
return_... | Find successor of given nodes.
This function will return the successor of given nodes.
Args:
nodes: Return the successor of given nodes,
if nodes is None, return successor for all nodes.
return_eids: If True return nodes together with corresponding eid
... | successor | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def sample_successor(self,
nodes,
max_degree,
return_eids=False,
shuffle=False):
"""Sample successors of given nodes.
Args:
nodes: Given nodes whose successors will be sampled.
... | Sample successors of given nodes.
Args:
nodes: Given nodes whose successors will be sampled.
max_degree: The max sampled successors for each nodes.
return_eids: Whether to return the corresponding eids.
Return:
Return a list of numpy.ndarray and each... | sample_successor | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def predecessor(self, nodes=None, return_eids=False):
"""Find predecessor of given nodes.
This function will return the predecessor of given nodes.
Args:
nodes: Return the predecessor of given nodes,
if nodes is None, return predecessor for all nodes.
... | Find predecessor of given nodes.
This function will return the predecessor of given nodes.
Args:
nodes: Return the predecessor of given nodes,
if nodes is None, return predecessor for all nodes.
return_eids: If True return nodes together with corresponding ... | predecessor | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def sample_predecessor(self,
nodes,
max_degree,
return_eids=False,
shuffle=False):
"""Sample predecessor of given nodes.
Args:
nodes: Given nodes whose predecessor will be sampled.
... | Sample predecessor of given nodes.
Args:
nodes: Given nodes whose predecessor will be sampled.
max_degree: The max sampled predecessor for each nodes.
return_eids: Whether to return the corresponding eids.
Return:
Return a list of numpy.ndarray and e... | sample_predecessor | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def send_recv(self, feature, reduce_func="sum"):
"""This method combines the send and recv function using graph_send_recv API.
Now, this method only supports default copy send function, and built-in receive
function ('sum', 'mean', 'max', 'min').
Args:
feature (Tensor): Th... | This method combines the send and recv function using graph_send_recv API.
Now, this method only supports default copy send function, and built-in receive
function ('sum', 'mean', 'max', 'min').
Args:
feature (Tensor): The node feature of a graph.
reduce_func (str): Di... | send_recv | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def send(
self,
message_func,
src_feat=None,
dst_feat=None,
edge_feat=None, ):
"""Send message from all src nodes to dst nodes.
The UDF message function should has the following format.
.. code-block:: python
def message_... | Send message from all src nodes to dst nodes.
The UDF message function should has the following format.
.. code-block:: python
def message_func(src_feat, dst_feat, edge_feat):
'''
Args:
src_feat: the node feat dict attached to th... | send | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def disjoint(cls, graph_list, merged_graph_index=False):
"""This method disjoint list of graph into a big graph.
Args:
graph_list (Graph List): A list of Graphs.
merged_graph_index: whether to keeped the graph_id that the nodes belongs to.
.. code-block:: pyth... | This method disjoint list of graph into a big graph.
Args:
graph_list (Graph List): A list of Graphs.
merged_graph_index: whether to keeped the graph_id that the nodes belongs to.
.. code-block:: python
import numpy as np
import pgl
... | disjoint | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def _join_feature(graph_list, mode="node"):
"""join node features for multiple graph"""
is_tensor = graph_list[0].is_tensor()
feat = defaultdict(lambda: [])
if mode == "node":
for graph in graph_list:
for key in graph.node_feat:
feat[key].a... | join node features for multiple graph | _join_feature | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def node_batch_iter(self, batch_size, shuffle=True):
"""Node batch iterator
Iterate all node by batch.
Args:
batch_size: The batch size of each batch of nodes.
shuffle: Whether shuffle the nodes.
Return:
Batch iterator
"""
if self.i... | Node batch iterator
Iterate all node by batch.
Args:
batch_size: The batch size of each batch of nodes.
shuffle: Whether shuffle the nodes.
Return:
Batch iterator
| node_batch_iter | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def to_mmap(self, path="./tmp"):
"""Turn the Graph into Memmap mode which can share memory between processes.
"""
self.dump(path)
graph = Graph.load(path, mmap_mode="r")
return graph | Turn the Graph into Memmap mode which can share memory between processes.
| to_mmap | python | PaddlePaddle/PaddleRec | models/rank/sign/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/graph.py | Apache-2.0 |
def construct_pred_edge(self, fe_index, s):
"""
fe_index: full_edge_index, [2, all_edges_batchwise]
s: predicted edge value, [all_edges_batchwise, 1]
construct the predicted edge set and corresponding edge weights
"""
s = s[:, 0]
fe_index = paddle.transpose(fe_i... |
fe_index: full_edge_index, [2, all_edges_batchwise]
s: predicted edge value, [all_edges_batchwise, 1]
construct the predicted edge set and corresponding edge weights
| construct_pred_edge | python | PaddlePaddle/PaddleRec | models/rank/sign/net.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/net.py | Apache-2.0 |
def construct_one_hot_label(self, label):
"""
Convert label to onehot encoding
input:[0,1,0,1]
output:[[1,0] [0,1] [1,0] [0,1]]
"""
nb_classes = int(max(label)) + 1
targets = np.array(label, dtype=np.int32).reshape(-1)
return np.eye(nb_classes)[targets] |
Convert label to onehot encoding
input:[0,1,0,1]
output:[[1,0] [0,1] [1,0] [0,1]]
| construct_one_hot_label | python | PaddlePaddle/PaddleRec | models/rank/sign/sign_reader.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/rank/sign/sign_reader.py | Apache-2.0 |
def get_length(self):
'''
map the user fields in all files, kept in self.user_fields dictionary
:return:
'''
length_user = 0
length_item = 0
f = open(self.trainfile)
line = f.readline()
while line:
user_features = line.strip().split(','... |
map the user fields in all files, kept in self.user_fields dictionary
:return:
| get_length | python | PaddlePaddle/PaddleRec | models/recall/ensfm/movielens_reader.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/recall/ensfm/movielens_reader.py | Apache-2.0 |
def bind_i(self, file):
'''
Read a feature file and bind
:param file: feature file
:return:
'''
f = open(file)
line = f.readline()
i = len(self.binded_items)
while line:
features = line.strip().split(',')
item_features = fea... |
Read a feature file and bind
:param file: feature file
:return:
| bind_i | python | PaddlePaddle/PaddleRec | models/recall/ensfm/movielens_reader.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/recall/ensfm/movielens_reader.py | Apache-2.0 |
def bind_user(self):
'''
Map the item fields in all files, kept in self.item_fields dictionary
:return:
'''
self.binded_users = {}
self.user_map = {}
self.bind_u(self.trainfile)
self.bind_u(self.testfile)
return len(self.binded_users) |
Map the item fields in all files, kept in self.item_fields dictionary
:return:
| bind_user | python | PaddlePaddle/PaddleRec | models/recall/ensfm/movielens_reader.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/recall/ensfm/movielens_reader.py | Apache-2.0 |
def bind_u(self, file):
'''
Read a feature file and bind
:param file:
:return:
'''
f = open(file)
line = f.readline()
i = len(self.binded_users)
while line:
features = line.strip().split(',')
user_features = features[0]
... |
Read a feature file and bind
:param file:
:return:
| bind_u | python | PaddlePaddle/PaddleRec | models/recall/ensfm/movielens_reader.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/recall/ensfm/movielens_reader.py | Apache-2.0 |
def get_positive_list(self, file):
'''
Obtain positive item lists for each user
:param file: train file
:return:
'''
self.max_positive_len = 0
f = open(file)
line = f.readline()
user_positive_list = {}
while line:
features = lin... |
Obtain positive item lists for each user
:param file: train file
:return:
| get_positive_list | python | PaddlePaddle/PaddleRec | models/recall/ensfm/movielens_reader.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/recall/ensfm/movielens_reader.py | Apache-2.0 |
def read_data(self, file):
'''
read raw data
:param file: data file
:return: structured data
'''
# read a data file;
f = open(file)
X_user = []
X_item = []
line = f.readline()
while line:
features = line.strip().split(',... |
read raw data
:param file: data file
:return: structured data
| read_data | python | PaddlePaddle/PaddleRec | models/recall/ensfm/movielens_reader.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/recall/ensfm/movielens_reader.py | Apache-2.0 |
def get_context_words(self, words, idx):
"""
Get the context word list of target word.
words: the words of the current line
idx: input word index
window_size: window size
"""
target_window = self.random_generator
# if (idx - target_window) > 0 else 0
... |
Get the context word list of target word.
words: the words of the current line
idx: input word index
window_size: window size
| get_context_words | python | PaddlePaddle/PaddleRec | models/recall/word2vec/word2vec_reader.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/recall/word2vec/word2vec_reader.py | Apache-2.0 |
def check_version(with_shuffle_batch=False):
"""
Log error and exit when the installed version of paddlepaddle is
not satisfied.
"""
err = "PaddlePaddle version 1.6 or higher is required, " \
"or a suitable develop version is satisfied as well. \n" \
"Please make sure the vers... |
Log error and exit when the installed version of paddlepaddle is
not satisfied.
| check_version | python | PaddlePaddle/PaddleRec | models/recall/word2vec/benchmark/w2v_infer.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/recall/word2vec/benchmark/w2v_infer.py | Apache-2.0 |
def build(self, output_filename, ids, codes, data=None, id_offset=None):
# process id offset
'''
if not id_offset:
max_id = 0
for id in ids:
if id > max_id:
max_id = id
id_offset = max_id + 1
'''
# sort by c... |
if not id_offset:
max_id = 0
for id in ids:
if id > max_id:
max_id = id
id_offset = max_id + 1
| build | python | PaddlePaddle/PaddleRec | models/treebased/builder/tree_index_builder.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/treebased/builder/tree_index_builder.py | Apache-2.0 |
def get_weights(C_ni, idx, edge_weights, ni, children_of_ni_in_level_l, tree,
args):
"""use the user preference prediction model to calculate the required weights
Returns:
all weights
Args:
C_ni (item, required): item set whose ancestor is the non-leaf node ni
ni (n... | use the user preference prediction model to calculate the required weights
Returns:
all weights
Args:
C_ni (item, required): item set whose ancestor is the non-leaf node ni
ni (node, required): a non-leaf node in level l-d
children_of_ni_in_level_l (list, required): the level l... | get_weights | python | PaddlePaddle/PaddleRec | models/treebased/jtm/tree_learning.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/treebased/jtm/tree_learning.py | Apache-2.0 |
def assign_parent(tree, l_max, l, d, ni, C_ni, args):
"""implementation of line 5 of Algorithm 2
Returns:
updated \pi_{new}
Args:
l_max (int, required): the max level of the tree
l (int, required): current assign level
d (int, required): level gap in tree_learning
... | implementation of line 5 of Algorithm 2
Returns:
updated \pi_{new}
Args:
l_max (int, required): the max level of the tree
l (int, required): current assign level
d (int, required): level gap in tree_learning
ni (node, required): a non-leaf node in level l-d
C_n... | assign_parent | python | PaddlePaddle/PaddleRec | models/treebased/jtm/tree_learning.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/treebased/jtm/tree_learning.py | Apache-2.0 |
def create_feeds(self, is_infer=False):
'''
user_input = [
paddle.static.data(
name="item_" + str(i + 1), shape=[None, 1], dtype="int64")
for i in range(self.item_nums)
]
'''
user_input = paddle.static.data(
name="item_id",
... |
user_input = [
paddle.static.data(
name="item_" + str(i + 1), shape=[None, 1], dtype="int64")
for i in range(self.item_nums)
]
| create_feeds | python | PaddlePaddle/PaddleRec | models/treebased/tdm/static_model.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/models/treebased/tdm/static_model.py | Apache-2.0 |
def as_call(self, request, context):
'''
message ASRequest{
string log_id = 1;
string user_id = 2;
user_info.UserInfo user_info = 3;
}
message ASResponse {
message Error {
uint32 code = 1;
string text = 2;
... |
message ASRequest{
string log_id = 1;
string user_id = 2;
user_info.UserInfo user_info = 3;
}
message ASResponse {
message Error {
uint32 code = 1;
string text = 2;
}
Error error = 1;
r... | as_call | python | PaddlePaddle/PaddleRec | recserving/movie_recommender/as.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/recserving/movie_recommender/as.py | Apache-2.0 |
def rank_predict(self, request, context):
'''
message RankRequest {
string log_id = 1;
user_info.UserInfo user_info = 2;
repeated item_info.ItemInfo item_infos = 3;
}
message RankResponse {
message Error {
uint32 code = 1;
... |
message RankRequest {
string log_id = 1;
user_info.UserInfo user_info = 2;
repeated item_info.ItemInfo item_infos = 3;
}
message RankResponse {
message Error {
uint32 code = 1;
string text = 2;
}
... | rank_predict | python | PaddlePaddle/PaddleRec | recserving/movie_recommender/rank.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/recserving/movie_recommender/rank.py | Apache-2.0 |
def recall(self, request, context):
'''
message RecallRequest{
string log_id = 1;
user_info.UserInfo user_info = 2;
string recall_type= 3;
uint32 request_num= 4;
}
message RecallResponse{
message Error {
uint32 code = 1;
string text = ... |
message RecallRequest{
string log_id = 1;
user_info.UserInfo user_info = 2;
string recall_type= 3;
uint32 request_num= 4;
}
message RecallResponse{
message Error {
uint32 code = 1;
string text = 2;
}
message ScorePair {
... | recall | python | PaddlePaddle/PaddleRec | recserving/movie_recommender/recall.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/recserving/movie_recommender/recall.py | Apache-2.0 |
def add_profiler_step(options_str=None):
'''
Enable the operator-level timing using PaddlePaddle's profiler.
The profiler uses a independent variable to count the profiler steps.
One call of this function is treated as a profiler step.
Args:
profiler_options - a string to initialize the P... |
Enable the operator-level timing using PaddlePaddle's profiler.
The profiler uses a independent variable to count the profiler steps.
One call of this function is treated as a profiler step.
Args:
profiler_options - a string to initialize the ProfilerOptions.
Default... | add_profiler_step | python | PaddlePaddle/PaddleRec | tools/profiler.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/profiler.py | Apache-2.0 |
def serialize_example(dense_feature, sparse_feature, label):
"""
Creates a tf.train.Example message ready to be written to a file.
"""
# Create a dictionary mapping the feature name to the tf.train.Example-compatible
# data type.
feature = {
'dense_feature': _float_feature(dense_feature),
... |
Creates a tf.train.Example message ready to be written to a file.
| serialize_example | python | PaddlePaddle/PaddleRec | tools/dataset/utils/tfrecord_writer.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/dataset/utils/tfrecord_writer.py | Apache-2.0 |
def save_inference_model(model_path,
epoch_id,
feed_vars,
fetch_vars,
exe,
prefix='rec_inference'):
"""
save inference model to target path
"""
model_path = os.path.join(model_pat... |
save inference model to target path
| save_inference_model | python | PaddlePaddle/PaddleRec | tools/utils/save_load.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/save_load.py | Apache-2.0 |
def get_last_dir(path):
"""Get the last directory of a path.
"""
if os.path.isfile(path):
# e.g: "../checkpoints/task_name/epoch0_step300/predict.txt"
# return "epoch0_step300"
last_dir = path.split("/")[-2]
elif os.path.isdir(path):
if path[-1] == '/':
# e.g... | Get the last directory of a path.
| get_last_dir | python | PaddlePaddle/PaddleRec | tools/utils/util_config.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/util_config.py | Apache-2.0 |
def create_necessary_dirs(config):
"""Create some necessary directories to save some important files.
"""
config.log_dir = os.path.join(config.log_dir, config.task_name)
config.save_dir = os.path.join(config.save_dir, config.task_name)
config.output_dir = os.path.join(config.output_dir, config.task_... | Create some necessary directories to save some important files.
| create_necessary_dirs | python | PaddlePaddle/PaddleRec | tools/utils/util_config.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/util_config.py | Apache-2.0 |
def save_files(config):
"""Save config file so that we can know the config when we look back
"""
filelist = config.files2saved
targetpath = config.log_dir
if filelist is not None:
for file_or_dir in filelist:
if os.path.isdir(file_or_dir):
last_name = get_last_di... | Save config file so that we can know the config when we look back
| save_files | python | PaddlePaddle/PaddleRec | tools/utils/util_config.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/util_config.py | Apache-2.0 |
def compute_chunks_and_cap(self, config):
"""compute the chunks by gpu allocated rate"""
sage_mode = config.sage_mode if config.sage_mode else False
gpups_memory_allocated_rate = config.gpups_memory_allocated_rate if config.gpups_memory_allocated_rate else 0.25
train_pass_cap = infer_pa... | compute the chunks by gpu allocated rate | compute_chunks_and_cap | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/dataset.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/dataset.py | Apache-2.0 |
def preload_thread(self, dataset_list, exception_queue):
""" This is a thread to fill the dataset_list
"""
try:
self.preload_worker(dataset_list)
except Exception as e:
self.could_load_sem.release()
self.ins_ready_sem.release()
log.warning(... | This is a thread to fill the dataset_list
| preload_thread | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/dataset.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/dataset.py | Apache-2.0 |
def preload_worker(self, dataset_list):
""" This is a preload worker to generate pass dataset asynchronously
"""
global pass_id
global epoch_stat
pass_id = 0
epoch_stat = 0
while 1:
dataset = None
self.could_load_sem.acquire()
... | This is a preload worker to generate pass dataset asynchronously
| preload_worker | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/dataset.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/dataset.py | Apache-2.0 |
def pass_generator(self, epoch=None):
""" pass generator, open a thread for processing the data
"""
dataset_list = []
t = threading.Thread(target=self.preload_thread, args=(dataset_list, self.exception_queue))
t.setDaemon(True)
t.start()
pass_id = 0
while... | pass generator, open a thread for processing the data
| pass_generator | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/dataset.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/dataset.py | Apache-2.0 |
def save_model(exe, output_path, day, pass_id, mode=0):
"""
Args:
output_path(str): output path
day(str|int): training day
pass_id(str|int): training pass id
"""
day = str(day)
pass_id = str(pass_id)
suffix_name = "/%s/%s/" % (day, pass_id)
model_path = output_path +... |
Args:
output_path(str): output path
day(str|int): training day
pass_id(str|int): training pass id
| save_model | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/flow_helper.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/flow_helper.py | Apache-2.0 |
def save_batch_model(exe, output_path, day):
"""
save batch model
Args:
output_path(str): output path
day(str|int): training day
"""
day = str(day)
suffix_name = "/%s/0/" % day
model_path = output_path + suffix_name
logger.info("going to save_batch_model %s" % model_path... |
save batch model
Args:
output_path(str): output path
day(str|int): training day
| save_batch_model | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/flow_helper.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/flow_helper.py | Apache-2.0 |
def write_model_donefile(output_path,
day,
pass_id,
model_base_key,
client,
donefile_name="donefile.txt"):
"""
write donefile when save model
Args:
output_path(str): output p... |
write donefile when save model
Args:
output_path(str): output path
day(str|int): training day
pass_id(str|int): training pass id
model_base_key(str|int): model base key
client(HDFSClient): hadoop client
donefile_name(str): donefile name, default is "donefile.txt... | write_model_donefile | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/flow_helper.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/flow_helper.py | Apache-2.0 |
def get_last_save_model(output_path, client):
"""
get last saved model info from donefile.txt
Args:
output_path(str): output path
client(HDFSClient): hadoop client
Returns:
[last_save_day, last_save_pass, last_path, model_base_key]
last_save_day(int): day of saved model... |
get last saved model info from donefile.txt
Args:
output_path(str): output path
client(HDFSClient): hadoop client
Returns:
[last_save_day, last_save_pass, last_path, model_base_key]
last_save_day(int): day of saved model
last_save_pass(int): pass id of saved
... | get_last_save_model | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/flow_helper.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/flow_helper.py | Apache-2.0 |
def get_last_save_base_model(output_path, client):
"""
get last saved base model info from base_donefile.txt
Args:
output_path(str): output path
client(HDFSClient): hadoop client
Returns:
[last_save_day, last_path, model_base_key]
last_save_day(int): day of saved model
... |
get last saved base model info from base_donefile.txt
Args:
output_path(str): output path
client(HDFSClient): hadoop client
Returns:
[last_save_day, last_path, model_base_key]
last_save_day(int): day of saved model
last_path(str): model path
model_base_key(... | get_last_save_base_model | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/flow_helper.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/flow_helper.py | Apache-2.0 |
def get_last_save_patch_model(output_path, client):
"""
get last saved delta model info from delta_donefile.txt
Args:
output_path(str): output path
client(HDFSClient): hadoop client
Returns:
[last_save_day, last_save_pass, last_path, model_base_key]
last_save_day(int): ... |
get last saved delta model info from delta_donefile.txt
Args:
output_path(str): output path
client(HDFSClient): hadoop client
Returns:
[last_save_day, last_save_pass, last_path, model_base_key]
last_save_day(int): day of saved model
last_save_pass(int): pass id of ... | get_last_save_patch_model | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/flow_helper.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/flow_helper.py | Apache-2.0 |
def save_inference_model(output_path, day, pass_id, exe, feed_vars,
target_vars, client):
"""
save inference model
Args:
output_path(str): output path
day(str|int): training day
pass_id(str|int): training pass id
exe(Executor)
feed_vars(list)... |
save inference model
Args:
output_path(str): output path
day(str|int): training day
pass_id(str|int): training pass id
exe(Executor)
feed_vars(list): feed var list for inference model
target_vars: target var list for inference model
client(HDFSClient): h... | save_inference_model | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/flow_helper.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/flow_helper.py | Apache-2.0 |
def write_inference_donefile(output_path,
day,
pass_id,
model_base_key,
client,
hadoop_fs_name="",
monitor_data="",
d... |
write inference donefile when save inference model
Args:
output_path(str): output path
day(str|int): training day
pass_id(str|int): training pass id
model_base_key(str|int): model base key
client(HDFSClient): hadoop client
donefile_name(str): donefile name
| write_inference_donefile | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/flow_helper.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/flow_helper.py | Apache-2.0 |
def load_edge_serial(self):
"""load edge serially, just used in metapath_split_opt
"""
for etype in self.etype_list:
if etype not in self.etype2files:
continue
load_begin_time = time.time()
self.graph.load_edge_file(etype + ":" + etype, self.ro... | load edge serially, just used in metapath_split_opt
| load_edge_serial | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/graph.py | Apache-2.0 |
def load_edge(self):
"""Pull whole graph edges from disk into cpu memory, then load into gpu.
After that, release memory on cpu.
"""
if self.metapath_split_opt:
return self.load_edge_serial()
load_begin_time = time.time()
self.graph.load_edge_file(self.edg... | Pull whole graph edges from disk into cpu memory, then load into gpu.
After that, release memory on cpu.
| load_edge | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/graph.py | Apache-2.0 |
def load_node(self):
"""Pull whole graph nodes from disk into cpu memory, then load into gpu.
After that, release memory on cpu.
"""
load_begin_time = time.time()
ret = self.graph.load_node_file(self.node_types, self.root_dir,
self.num_p... | Pull whole graph nodes from disk into cpu memory, then load into gpu.
After that, release memory on cpu.
| load_node | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/graph.py | Apache-2.0 |
def load_graph_into_cpu(self):
"""Pull whole graph from disk into memory
"""
cpuload_begin = time.time()
self.graph.load_node_and_edge(self.edge_types, self.node_types,
self.root_dir, self.num_parts,
self.reverse... | Pull whole graph from disk into memory
| load_graph_into_cpu | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/graph.py | Apache-2.0 |
def load_graph_into_gpu(self):
"""Pull whole graph from memory into gpu
"""
gpuload_begin = time.time()
log.info("STAGE [GPU Load] begin load edges from cpu to gpu")
for i in range(len(self.etype_list)):
self.graph.upload_batch(0,
... | Pull whole graph from memory into gpu
| load_graph_into_gpu | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/graph.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/graph.py | Apache-2.0 |
def my_multi_base(function, queue, lock):
"""
function name
queue task queue
lock
"""
while True:
if queue.empty() == True:
return True
lock.acquire()
row = ""
if queue.empty() == True:
lock.release()
return True
... |
function name
queue task queue
lock
| my_multi_base | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/graph_del_zero_token.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/graph_del_zero_token.py | Apache-2.0 |
def get_global_auc(scope=paddle.static.global_scope(),
stat_pos="_generated_var_2",
stat_neg="_generated_var_3"):
"""
Get global auc of all distributed workers.
Args:
scope(Scope): Scope object, default is paddle.static.global_scope()
st... |
Get global auc of all distributed workers.
Args:
scope(Scope): Scope object, default is paddle.static.global_scope()
stat_pos(str): name of auc pos bucket Variable
stat_neg(str): name of auc neg bucket Variable
Returns:
auc_value(float), total_i... | get_global_auc | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/metric_helper.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/metric_helper.py | Apache-2.0 |
def set_zero(var_name,
scope=paddle.static.global_scope(),
place=paddle.CPUPlace(),
param_type="int64"):
"""
Set tensor of a Variable to zero.
Args:
var_name(str): name of Variable
scope(Scope): Scope object, default is paddle.static.global_scope()
... |
Set tensor of a Variable to zero.
Args:
var_name(str): name of Variable
scope(Scope): Scope object, default is paddle.static.global_scope()
place(Place): Place object, default is paddle.CPUPlace()
param_type(str): param data type, default is int64
Examples:
set_zer... | set_zero | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/metric_helper.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/metric_helper.py | Apache-2.0 |
def reset_program_state_dict(args, model, state_dict, pretrained_state_dict):
"""
Initialize the parameter from the bert config, and set the parameter by
reseting the state dict."
"""
scale = args.init_range
reset_state_dict = {}
reset_parameter_names = []
for n, p in state_dict.items()... |
Initialize the parameter from the bert config, and set the parameter by
reseting the state dict."
| reset_program_state_dict | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/model_util.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/model_util.py | Apache-2.0 |
def remove_leakage_edges_gnn(graph_holders, etype_len, final_index, empty_flag, return_weight=False):
""" remove duplicate edges, avoid data leakage"""
new_graph_holders = {}
ego_pairs = final_index.reshape([-1, 2])
magic_number = 27644437
hashnum = ego_pairs[:, 0] * magic_number + ego_pairs[:, 1]... | remove duplicate edges, avoid data leakage | remove_leakage_edges_gnn | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/model_util.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/model_util.py | Apache-2.0 |
def parse_path(path):
"""
Args:
path: path has follow format:
1, /your/local/path
2, afs:/your/remote/afs/path
3, hdfs:/your/remote/hdfs/path
4, afs://xxx.baidu.com:xxxx/your/remote/afs/path
5, hdfs://xxx.baidu.com:xxxx/your/remote/hdfs/path
... |
Args:
path: path has follow format:
1, /your/local/path
2, afs:/your/remote/afs/path
3, hdfs:/your/remote/hdfs/path
4, afs://xxx.baidu.com:xxxx/your/remote/afs/path
5, hdfs://xxx.baidu.com:xxxx/your/remote/hdfs/path
Return:
mode: 3 di... | parse_path | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/util.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/util.py | Apache-2.0 |
def remove_prefix_of_hadoop_path(hadoop_path):
"""
Args:
hadoop_path: afs://xxx.baidu.com:xxxx/your/remote/hadoop/path
Return:
output_path: /your/remote/hadoop/path
"""
output_path = hadoop_path.split(":")[-1]
output_path = re.split("^\d+", output_path)[-1]
return output_pat... |
Args:
hadoop_path: afs://xxx.baidu.com:xxxx/your/remote/hadoop/path
Return:
output_path: /your/remote/hadoop/path
| remove_prefix_of_hadoop_path | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/util.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/util.py | Apache-2.0 |
def get_sub_path(type2files_dict, sub_types_list, is_edge):
""" get sub path in metapath split """
final_path = []
is_reverse_edge_map = []
for sub_type in sub_types_list:
combine = []
#combine.append(sub_type)
if sub_type in type2files_dict:
combine.append(sub_type)
... | get sub path in metapath split | get_sub_path | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/util.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/util.py | Apache-2.0 |
def get_first_node_type(meta_path):
""" get first node type from meta path """
meta_path_vec = []
if meta_path[0] == '[':
# multi tensor pair
assert(meta_path[-1] == ']')
meta_path_vec.extend(meta_path[1:-2].split(','))
else:
meta_path_vec.append(meta_path)
f... | get first node type from meta path | get_first_node_type | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/util.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/util.py | Apache-2.0 |
def gzshell_upload(fs_name, fs_user, fs_password, local_path, remote_path):
""" upload data with gzshell in afs """
gzshell = os.getenv("GZSHELL")
client_conf = os.getenv("CLIENT_CONF")
cmd = "%s --uri=%s --username=%s --password=%s --conf=%s \
--thread=100 -put %s/ %s" % (gzshell, fs_name, ... | upload data with gzshell in afs | gzshell_upload | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/util.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/util.py | Apache-2.0 |
def gzshell_download(fs_name, fs_user, fs_password, remote_path, local_path):
""" download data with gzshell in afs """
gzshell = os.getenv("GZSHELL")
client_conf = os.getenv("CLIENT_CONF")
cmd = "%s --uri=%s --username=%s --password=%s --conf=%s \
--thread=100 -get %s %s" % (gzshell, fs_nam... | download data with gzshell in afs | gzshell_download | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/util.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/util.py | Apache-2.0 |
def sample_list_to_str(sage_mode, samples):
"""
turn sample list config to string
"""
str_samples = ""
if sage_mode and samples and len(samples) > 0:
for s in samples:
str_samples += str(s)
str_samples += ";"
str_samples = str_samples[:-1]
return str_sampl... |
turn sample list config to string
| sample_list_to_str | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/util.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/util.py | Apache-2.0 |
def put_files(src, dest, hadoop_bin=None, fs_name=None, fs_ugi=None):
"""hadoop upload file in src to dest """
hadoop_bin, fs_name, fs_ugi = parse_account(hadoop_bin, fs_name, fs_ugi)
dest = check_hadoop_path(dest, hadoop_bin, fs_name, fs_ugi)
cmd = make_base_cmd(hadoop_bin, fs_name, fs_ugi)
cmd1 = ... | hadoop upload file in src to dest | put_files | python | PaddlePaddle/PaddleRec | tools/utils/static_ps/util_hadoop.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/tools/utils/static_ps/util_hadoop.py | Apache-2.0 |
def train(self,
dataset=None,
batch_size=None,
learning_rate=None,
epochs_iters=None,
ips=None,
device='gpu',
resume_path=None,
dy2st=False,
amp='OFF',
use_vdl=True,
... |
Train a model.
Args:
dataset (str|None): Root path of the dataset. If None, use the setting in the config file or a
pre-defined default dataset.
batch_size (int|None): Number of samples in each mini-batch. If multiple devices are used, this
is t... | train | python | PaddlePaddle/PaddleRec | uapi_rec/base/model.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/uapi_rec/base/model.py | Apache-2.0 |
def evaluate(self,
weight_path,
dataset=None,
batch_size=None,
ips=None,
device='gpu',
amp='OFF'):
"""
Evaluate a model.
Args:
weight_path (str): Path of the weights to initialize t... |
Evaluate a model.
Args:
weight_path (str): Path of the weights to initialize the model.
dataset (str|None): Root path of the dataset. If None, use the setting in the config file or a
pre-defined default dataset.
batch_size (int|None): Number of samp... | evaluate | python | PaddlePaddle/PaddleRec | uapi_rec/base/model.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/uapi_rec/base/model.py | Apache-2.0 |
def compression(self,
weight_path,
dataset=None,
batch_size=None,
learning_rate=None,
epochs_iters=None,
device='gpu',
use_vdl=True,
save_dir=None):
"""... |
Perform quantization aware training (QAT) and export the quantized model.
Args:
weight_path (str): Path of the weights to initialize the model.
dataset (str|None): Root path of the dataset. If None, use the setting in the config file or a
pre-defined default da... | compression | python | PaddlePaddle/PaddleRec | uapi_rec/base/model.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/uapi_rec/base/model.py | Apache-2.0 |
def compression(self, config_path, train_cli_args, export_cli_args, device,
train_save_dir):
"""
Execute model compression (quantization aware training and model export) commands.
Args:
config_path (str): Path of the configuration file.
train_cli_args... |
Execute model compression (quantization aware training and model export) commands.
Args:
config_path (str): Path of the configuration file.
train_cli_args (list[utils.arg.CLIArgument]): List of command-line Arguments used for model
training.
train_c... | compression | python | PaddlePaddle/PaddleRec | uapi_rec/base/runner.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/uapi_rec/base/runner.py | Apache-2.0 |
def run_cmd(cmd,
silent=True,
cwd=None,
timeout=None,
echo=False,
pipe_stdout=False,
pipe_stderr=False,
blocking=True,
async_run=False,
text=True):
"""Wrap around `subprocess.run()` to execute a shell command... | Wrap around `subprocess.run()` to execute a shell command. | run_cmd | python | PaddlePaddle/PaddleRec | uapi_rec/base/utils/misc.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/uapi_rec/base/utils/misc.py | Apache-2.0 |
def running_train(learning_rate, epoch_iters, batch_size, data_path, yaml_path,
vdl_path, save_dir):
"""
Args:
learning_rate (float): Learning rate of model training.
epoch_iters (int): Total epochs or iterations of model training.
batch_size (int): Number of samples in... |
Args:
learning_rate (float): Learning rate of model training.
epoch_iters (int): Total epochs or iterations of model training.
batch_size (int): Number of samples in each mini-batch.
data_path (str): Root path of the dataset used in training.
yaml_path (str): Absolute path o... | running_train | python | PaddlePaddle/PaddleRec | uapi_rec/base/utils/stagelog.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/uapi_rec/base/utils/stagelog.py | Apache-2.0 |
def running_verify(checkpoint_dir,
checkpoint_name,
metrics,
save_dir=_EMPTY_ARG()):
"""
Args:
checkpoint_dir (str): Directory that contains the weights to initialize the model.
checkpoint_name (str): Base name of the weight file.
... |
Args:
checkpoint_dir (str): Directory that contains the weights to initialize the model.
checkpoint_name (str): Base name of the weight file.
metrics (list[str]): A list of names of all metrics used in model evaluation.
save_dir (str, optional): Directory that contains model snapsho... | running_verify | python | PaddlePaddle/PaddleRec | uapi_rec/base/utils/stagelog.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/uapi_rec/base/utils/stagelog.py | Apache-2.0 |
def running_compress(checkpoint_dir,
checkpoint_name,
compress_batch_size,
compress_epoch,
compress_learning_rate,
vdl_path,
save_dir,
metrics=_EMPTY_ARG()):
"""
Arg... |
Args:
checkpoint_dir (str): Directory that contains the weights to initialize the model.
checkpoint_name (str): Base name of the weight file.
compress_batch_size (int): Number of samples in each mini-batch.
compress_epoch (int): Total epochs or iterations of QAT.
compress_le... | running_compress | python | PaddlePaddle/PaddleRec | uapi_rec/base/utils/stagelog.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/uapi_rec/base/utils/stagelog.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.