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 set_mem_length(self, mem_length: int): """ Parameters ---------- mem_length The memory length of the model """ self._cfg.defrost() self._cfg.MODEL.mem_length = mem_length self._cfg.freeze()
Parameters ---------- mem_length The memory length of the model
set_mem_length
python
dmlc/gluon-nlp
src/gluonnlp/models/transformer_xl.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/models/transformer_xl.py
Apache-2.0
def forward(self, data, target, mem_l, rel_positions=None, data_mem_mask=None, causal_only=False, detach_memory=True): """ Parameters ---------- data The input data - layout = 'NT' Shape (B, T) - layout = 'TN' ...
Parameters ---------- data The input data - layout = 'NT' Shape (B, T) - layout = 'TN' Shape (T, B) target The ground truth - layout = 'NT' Shape (B, T) - layout =...
forward
python
dmlc/gluon-nlp
src/gluonnlp/models/transformer_xl.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/models/transformer_xl.py
Apache-2.0
def step_forward(self, step_data, mem_l): """Forward for just one step Parameters ---------- step_data Shape (B,) mem_l A list of memory objects - layout = 'NT' Shape (B, T_mem, units) - layout = 'TN' ...
Forward for just one step Parameters ---------- step_data Shape (B,) mem_l A list of memory objects - layout = 'NT' Shape (B, T_mem, units) - layout = 'TN' Shape (T_mem, B, units) Returns -...
step_forward
python
dmlc/gluon-nlp
src/gluonnlp/models/transformer_xl.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/models/transformer_xl.py
Apache-2.0
def get_pretrained_xlmr(model_name: str = 'fairseq_xlmr_base', root: str = get_model_zoo_home_dir(), load_backbone: bool = True, load_mlm: bool = False) \ -> Tuple[CN, SentencepieceTokenizer, str, str]: """Get the pretrained XLM-R weigh...
Get the pretrained XLM-R weights Parameters ---------- model_name The name of the xlmr model. root The downloading root load_backbone Whether to load the weights of the backbone network load_mlm Whether to load the weights of MLM Returns ------- cfg ...
get_pretrained_xlmr
python
dmlc/gluon-nlp
src/gluonnlp/models/xlmr.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/models/xlmr.py
Apache-2.0
def gen_self_attn_mask(data, valid_length=None, attn_type: str = 'full', layout: str = 'NT'): """Generate the mask used for the encoder, i.e, self-attention. In our implementation, 1 --> not masked, 0 --> masked Let's consider the data wi...
Generate the mask used for the encoder, i.e, self-attention. In our implementation, 1 --> not masked, 0 --> masked Let's consider the data with two samples: data = [['I', 'can', 'now', 'use', 'numpy', 'in', 'Gluon@@', 'NLP' ], ['May', 'the', 'force', 'be', 'with', 'you', '<PAD>', ...
gen_self_attn_mask
python
dmlc/gluon-nlp
src/gluonnlp/torch/attention_cell.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/attention_cell.py
Apache-2.0
def gen_mem_attn_mask(mem, mem_valid_length, data, data_valid_length=None, layout: str = 'NT'): """Generate the mask used for the decoder. All query slots are attended to the memory slots. In our implementation, 1 --> not masked, 0 --> masked Let's consider the data + mem with a batch...
Generate the mask used for the decoder. All query slots are attended to the memory slots. In our implementation, 1 --> not masked, 0 --> masked Let's consider the data + mem with a batch of two samples: mem = [['I', 'can', 'now', 'use'], ['May', 'the', 'force', '<PAD>']] mem_valid_lengt...
gen_mem_attn_mask
python
dmlc/gluon-nlp
src/gluonnlp/torch/attention_cell.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/attention_cell.py
Apache-2.0
def masked_softmax(att_score, mask, axis: int = -1): """Ignore the masked elements when calculating the softmax. The mask can be broadcastable. Parameters ---------- att_score : Symborl or NDArray Shape (..., length, ...) mask : Symbol or NDArray or None Shape (..., length, ......
Ignore the masked elements when calculating the softmax. The mask can be broadcastable. Parameters ---------- att_score : Symborl or NDArray Shape (..., length, ...) mask : Symbol or NDArray or None Shape (..., length, ...) 1 --> The element is not masked 0 --> The ...
masked_softmax
python
dmlc/gluon-nlp
src/gluonnlp/torch/attention_cell.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/attention_cell.py
Apache-2.0
def multi_head_dot_attn(query, key, value, mask=None, edge_scores=None, dropout: float = 0.0, scaled: bool = True, normalized: bool = False, eps: float = 1E-6, layout: str = 'N...
Multihead dot product attention between the query, key, value. scaled is False, normalized is False: D(h_q, h_k) = <h_q, h_k> scaled is True, normalized is False: D(h_q, h_k) = <h_q, h_k> / sqrt(dim_q) scaled is False, normalized is True: D(h_q, h_k) = <h_q / ||h_q||, h_k / ||h_k||>...
multi_head_dot_attn
python
dmlc/gluon-nlp
src/gluonnlp/torch/attention_cell.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/attention_cell.py
Apache-2.0
def relative_position_bucket(relative_position, bidirectional: bool = True, num_buckets: int = 32, max_distance: int = 128): """Map the relative position to buckets. The major difference between our implementation and that in [mesh_tensorflow](https://github.com/tensorflow/mesh...
Map the relative position to buckets. The major difference between our implementation and that in [mesh_tensorflow](https://github.com/tensorflow/mesh/blob/c59988047e49b4d2af05603e3170724cdbadc467/mesh_tensorflow/transformer/transformer_layers.py#L595-L637) is that we use 'query_i - mem_j' as the (i, j)-th...
relative_position_bucket
python
dmlc/gluon-nlp
src/gluonnlp/torch/layers.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/layers.py
Apache-2.0
def get_activation(act, inplace=False): """ Parameters ---------- act Name of the activation inplace Whether to perform inplace activation Returns ------- activation_layer The activation """ if act is None: return lambda x: x if isinstance(ac...
Parameters ---------- act Name of the activation inplace Whether to perform inplace activation Returns ------- activation_layer The activation
get_activation
python
dmlc/gluon-nlp
src/gluonnlp/torch/layers.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/layers.py
Apache-2.0
def get_norm_layer(normalization: str = 'layer_norm', axis: int = -1, epsilon: float = 1e-5, in_channels: int = 0, **kwargs): """Get the normalization layer based on the provided type Parameters ---------- normalization The type of the layer normalization from ['layer_norm'] ...
Get the normalization layer based on the provided type Parameters ---------- normalization The type of the layer normalization from ['layer_norm'] axis The axis to normalize the epsilon The epsilon of the normalization layer in_channels Input channel Returns...
get_norm_layer
python
dmlc/gluon-nlp
src/gluonnlp/torch/layers.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/layers.py
Apache-2.0
def __init__(self, units: int = 512, hidden_size: int = 2048, activation_dropout: float = 0.0, dropout: float = 0.1, gated_proj: bool = False, activation='relu', normalization: str = 'layer_norm', layer_norm_eps: float = 1E-5, pre_norm: bool = False): """ ...
Parameters ---------- units hidden_size activation_dropout dropout activation normalization layer_norm or no_norm layer_norm_eps pre_norm Pre-layer normalization as proposed in the paper: "[ACL2018] The ...
__init__
python
dmlc/gluon-nlp
src/gluonnlp/torch/layers.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/layers.py
Apache-2.0
def forward(self, data): """ Parameters ---------- data : Shape (B, seq_length, C_in) Returns ------- out : Shape (B, seq_length, C_out) """ residual = data if self._pre_norm: data = self.layer_norm(dat...
Parameters ---------- data : Shape (B, seq_length, C_in) Returns ------- out : Shape (B, seq_length, C_out)
forward
python
dmlc/gluon-nlp
src/gluonnlp/torch/layers.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/layers.py
Apache-2.0
def __init__(self, units: int, learnable=False): """Use a geometric sequence of timescales. It is calculated as [sin(wi x), cos(wi x), sin(wi x), cos(wi x), ...] By default, we initialize wi to be (1 / 10000) ^ (1 / (units//2 - 1)) Parameters ---------- units ...
Use a geometric sequence of timescales. It is calculated as [sin(wi x), cos(wi x), sin(wi x), cos(wi x), ...] By default, we initialize wi to be (1 / 10000) ^ (1 / (units//2 - 1)) Parameters ---------- units The number of units for positional embedding ...
__init__
python
dmlc/gluon-nlp
src/gluonnlp/torch/layers.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/layers.py
Apache-2.0
def forward(self, positions): """ Parameters ---------- positions : th.Tensor Shape (..., ) Returns ------- ret : Shape (..., units) """ emb = positions.unsqueeze(-1) * self.freq sin_emb = th.sin(emb) cos_e...
Parameters ---------- positions : th.Tensor Shape (..., ) Returns ------- ret : Shape (..., units)
forward
python
dmlc/gluon-nlp
src/gluonnlp/torch/layers.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/layers.py
Apache-2.0
def to_torch_dtype(dtype): """Convert the dtype to pytorch data type Parameters ---------- dtype The input dtype Returns ------- ret Converted dtype """ if isinstance(dtype, th.dtype) or dtype is None: return dtype dtype = np.dtype(dtype) if dtype in...
Convert the dtype to pytorch data type Parameters ---------- dtype The input dtype Returns ------- ret Converted dtype
to_torch_dtype
python
dmlc/gluon-nlp
src/gluonnlp/torch/utils.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/utils.py
Apache-2.0
def to_numpy_dtype(dtype): """Convert the dtype to numpy dtype Parameters ---------- dtype Input dtype Returns ------- ret The converted dtype """ if dtype is None: return None if dtype in torch_dtype_to_numpy_dict: return torch_dtype_to_numpy_di...
Convert the dtype to numpy dtype Parameters ---------- dtype Input dtype Returns ------- ret The converted dtype
to_numpy_dtype
python
dmlc/gluon-nlp
src/gluonnlp/torch/utils.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/utils.py
Apache-2.0
def share_parameters(source, target): """Share parameters recursively from source model to target model. For example, if you want ``dense1`` to share ``dense0``'s weights, you can do:: dense0 = nn.Linear(20) dense1 = nn.Linear(20) share_parameters(dense0, dense) which equals to ...
Share parameters recursively from source model to target model. For example, if you want ``dense1`` to share ``dense0``'s weights, you can do:: dense0 = nn.Linear(20) dense1 = nn.Linear(20) share_parameters(dense0, dense) which equals to dense1.weight = dense0.weight d...
share_parameters
python
dmlc/gluon-nlp
src/gluonnlp/torch/utils.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/utils.py
Apache-2.0
def _named_members(module, get_members_fn, prefix='', recurse=True): r"""Helper method for yielding various names + members of modules. Unlike upstream torch implementation, this implementation returns members that are known under multiple names, such as shared parameters. """ ...
Helper method for yielding various names + members of modules. Unlike upstream torch implementation, this implementation returns members that are known under multiple names, such as shared parameters.
_named_members
python
dmlc/gluon-nlp
src/gluonnlp/torch/utils.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/utils.py
Apache-2.0
def move_to(obj, device=None): """ Parameters ---------- obj Nested torch object device The target device Returns ------- new_obj The objects that have been moved to device. """ if th.is_tensor(obj): return obj.to(device) elif isinstance(obj,...
Parameters ---------- obj Nested torch object device The target device Returns ------- new_obj The objects that have been moved to device.
move_to
python
dmlc/gluon-nlp
src/gluonnlp/torch/utils.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/utils.py
Apache-2.0
def _pad_arrs_to_max_length(arrs, pad_val, dtype, batch_dim=0, round_to=None): """Inner Implementation of the Pad batchify Parameters ---------- arrs List of arrays pad_val The padding value dtype The type of the tensor batch_dim The dimension to insert the b...
Inner Implementation of the Pad batchify Parameters ---------- arrs List of arrays pad_val The padding value dtype The type of the tensor batch_dim The dimension to insert the batch dimension. This controls how we should construct the mini-batch. roun...
_pad_arrs_to_max_length
python
dmlc/gluon-nlp
src/gluonnlp/torch/data/batchify.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/data/batchify.py
Apache-2.0
def __call__(self, data): """Batchify the input data. The input can be list of numpy.ndarray, list of numbers or list of th.Tensor. The arrays will be padded to the largest dimension at `axis` and then stacked to form the final output. Parameters ---------- data...
Batchify the input data. The input can be list of numpy.ndarray, list of numbers or list of th.Tensor. The arrays will be padded to the largest dimension at `axis` and then stacked to form the final output. Parameters ---------- data : List[np.ndarray] or List[List[dtyp...
__call__
python
dmlc/gluon-nlp
src/gluonnlp/torch/data/batchify.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/data/batchify.py
Apache-2.0
def _stack_arrs(arrs, batch_dim, dtype): """ Parameters ---------- arrs batch_dim The batch dimension dtype torch dtype Returns ------- stacked_arr The resulting stacked array """ if isinstance(arrs[0], np.ndarray): stacked_arr = np.stack(ar...
Parameters ---------- arrs batch_dim The batch dimension dtype torch dtype Returns ------- stacked_arr The resulting stacked array
_stack_arrs
python
dmlc/gluon-nlp
src/gluonnlp/torch/data/batchify.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/data/batchify.py
Apache-2.0
def __call__(self, data: t_List[t_Dict]) -> t_Dict: """ Parameters ---------- data The samples to batchify. Each sample should be a dictionary Returns ------- ret The resulting dictionary that stores the merged samples. """ ...
Parameters ---------- data The samples to batchify. Each sample should be a dictionary Returns ------- ret The resulting dictionary that stores the merged samples.
__call__
python
dmlc/gluon-nlp
src/gluonnlp/torch/data/batchify.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/data/batchify.py
Apache-2.0
def __call__(self, data: t_List[t_NamedTuple]) -> t_NamedTuple: """Batchify the input data. Parameters ---------- data The samples to batchfy. Each sample should be a namedtuple. Returns ------- ret A namedtuple of length N. Contains the ba...
Batchify the input data. Parameters ---------- data The samples to batchfy. Each sample should be a namedtuple. Returns ------- ret A namedtuple of length N. Contains the batchified result of each attribute in the input.
__call__
python
dmlc/gluon-nlp
src/gluonnlp/torch/data/batchify.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/data/batchify.py
Apache-2.0
def forward(self, data, valid_length): """ Generate the representation given the inputs. This is used in training or fine-tuning a bert model. Parameters ---------- F data - layout = 'NT' Shape (batch_size, seq_length, C) ...
Generate the representation given the inputs. This is used in training or fine-tuning a bert model. Parameters ---------- F data - layout = 'NT' Shape (batch_size, seq_length, C) - layout = 'TN' Shape (seq_length,...
forward
python
dmlc/gluon-nlp
src/gluonnlp/torch/models/bert.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/models/bert.py
Apache-2.0
def forward(self, inputs, token_types, valid_length): # pylint: disable=arguments-differ """Generate the representation given the inputs. This is used in training or fine-tuning a bert model. Parameters ---------- inputs - layout = 'NT' Shape...
Generate the representation given the inputs. This is used in training or fine-tuning a bert model. Parameters ---------- inputs - layout = 'NT' Shape (batch_size, seq_length) - layout = 'TN' Shape (seq_length, batch_size) ...
forward
python
dmlc/gluon-nlp
src/gluonnlp/torch/models/bert.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/models/bert.py
Apache-2.0
def get_initial_embedding(self, inputs, token_types=None): """Get the initial token embeddings that considers the token type and positional embeddings Parameters ---------- inputs - layout = 'NT' Shape (batch_size, seq_length) - layout = 'TN' ...
Get the initial token embeddings that considers the token type and positional embeddings Parameters ---------- inputs - layout = 'NT' Shape (batch_size, seq_length) - layout = 'TN' Shape (seq_length, batch_size) token_types ...
get_initial_embedding
python
dmlc/gluon-nlp
src/gluonnlp/torch/models/bert.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/models/bert.py
Apache-2.0
def apply_pooling(self, sequence): """Generate the representation given the inputs. This is used for pre-training or fine-tuning a bert model. Get the first token of the whole sequence which is [CLS] sequence - layout = 'NT' Shape (batch_size, sequence_lengt...
Generate the representation given the inputs. This is used for pre-training or fine-tuning a bert model. Get the first token of the whole sequence which is [CLS] sequence - layout = 'NT' Shape (batch_size, sequence_length, units) - layout = 'TN' ...
apply_pooling
python
dmlc/gluon-nlp
src/gluonnlp/torch/models/bert.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/models/bert.py
Apache-2.0
def from_cfg(cls, cfg, use_pooler=True) -> 'BertModel': """ Parameters ---------- cfg Configuration use_pooler Whether to output the pooled feature Returns ------- ret The constructed BertModel """ cfg ...
Parameters ---------- cfg Configuration use_pooler Whether to output the pooled feature Returns ------- ret The constructed BertModel
from_cfg
python
dmlc/gluon-nlp
src/gluonnlp/torch/models/bert.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/models/bert.py
Apache-2.0
def __init__(self, backbone_cfg): """ Parameters ---------- backbone_cfg The cfg of the backbone model """ super().__init__() self.backbone_model = BertModel.from_cfg(backbone_cfg) # Construct nsp_classifier for next sentence prediction ...
Parameters ---------- backbone_cfg The cfg of the backbone model
__init__
python
dmlc/gluon-nlp
src/gluonnlp/torch/models/bert.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/models/bert.py
Apache-2.0
def forward(self, inputs, token_types, valid_length, masked_positions): """Generate the representation given the inputs. This is used in training or fine-tuning a bert model. Parameters ---------- inputs - layout = 'NT' Shape (batch_size, seq_length)...
Generate the representation given the inputs. This is used in training or fine-tuning a bert model. Parameters ---------- inputs - layout = 'NT' Shape (batch_size, seq_length) - layout = 'TN' Shape (seq_length, batch_size) ...
forward
python
dmlc/gluon-nlp
src/gluonnlp/torch/models/bert.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/models/bert.py
Apache-2.0
def forward(self, inputs, token_types, valid_length, masked_positions): """Generate the representation given the inputs. This is used in training or fine-tuning a bert model. Parameters ---------- inputs - layout = 'NT' Shape (batch_size, seq_length)...
Generate the representation given the inputs. This is used in training or fine-tuning a bert model. Parameters ---------- inputs - layout = 'NT' Shape (batch_size, seq_length) - layout = 'TN' Shape (seq_length, batch_size) ...
forward
python
dmlc/gluon-nlp
src/gluonnlp/torch/models/bert.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/models/bert.py
Apache-2.0
def __init__(self, units: int = 512, hidden_size: int = 2048, num_heads: int = 8, attention_dropout_prob: float = 0.1, hidden_dropout_prob: float = 0.1, activation_dropout_prob: float = 0.0, layer_norm_eps: float = 1e-12, pre_norm: bool = False, use_qkv_bias: bool = Tr...
Parameters ---------- units hidden_size num_heads attention_dropout_prob hidden_dropout_prob activation_dropout_prob layer_norm_eps pre_norm Whether to attach the normalization layer before attention layer If pre_no...
__init__
python
dmlc/gluon-nlp
src/gluonnlp/torch/models/transformer.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/models/transformer.py
Apache-2.0
def forward(self, data, attn_mask): """ Parameters ---------- data : If layout == 'NT' Shape (batch_size, seq_length, C_in) Else Shape (seq_length, batch_size, C_in) attn_mask : Shape (batch_size, seq_length, seq...
Parameters ---------- data : If layout == 'NT' Shape (batch_size, seq_length, C_in) Else Shape (seq_length, batch_size, C_in) attn_mask : Shape (batch_size, seq_length, seq_length) Returns ------- ...
forward
python
dmlc/gluon-nlp
src/gluonnlp/torch/models/transformer.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/models/transformer.py
Apache-2.0
def __init__(self, units: int = 512, mem_units: Optional[int] = None, hidden_size: int = 2048, num_heads: int = 8, activation_dropout: float = 0.0, dropout: float = 0.1, attention_dropout: float = 0.1, layer_norm_eps: float = 1E-5, activation: str = 'relu', gated_proj:...
Parameters ---------- units mem_units The number of units in the memory. By default, it is initialized to be the same as the units. hidden_size num_heads activation_dropout dropout attention_dropout layer_norm_eps ...
__init__
python
dmlc/gluon-nlp
src/gluonnlp/torch/models/transformer.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/models/transformer.py
Apache-2.0
def forward(self, data, mem, self_causal_mask, mem_attn_mask): """ Parameters ---------- data : - layout = 'NT' Shape (batch_size, seq_length, C_in) - layout = 'TN' Shape (seq_length, batch_size, C_in) mem : - la...
Parameters ---------- data : - layout = 'NT' Shape (batch_size, seq_length, C_in) - layout = 'TN' Shape (seq_length, batch_size, C_in) mem : - layout = 'NT' Shape (batch_size, mem_length, C_mem) ...
forward
python
dmlc/gluon-nlp
src/gluonnlp/torch/models/transformer.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/models/transformer.py
Apache-2.0
def init_states(self, batch_size, device=None, dtype='float32'): """Initialize the states required for incremental decoding Parameters ---------- batch_size device dtype Returns ------- init_key - layout = 'NT' Shape (...
Initialize the states required for incremental decoding Parameters ---------- batch_size device dtype Returns ------- init_key - layout = 'NT' Shape (batch_size, 0, N, C_key) - layout = 'TN' Shape (...
init_states
python
dmlc/gluon-nlp
src/gluonnlp/torch/models/transformer.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/models/transformer.py
Apache-2.0
def incremental_decode(self, data, states, mem, mem_valid_length, mem_attn_mask=None): """Incrementally generate the output given the decoder input. Parameters ---------- data Shape (batch_size, C_in) states The previous states, contains 1. la...
Incrementally generate the output given the decoder input. Parameters ---------- data Shape (batch_size, C_in) states The previous states, contains 1. layout = 'NT': - prev_multi_key Shape (batch_size, prev_seq_leng...
incremental_decode
python
dmlc/gluon-nlp
src/gluonnlp/torch/models/transformer.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/models/transformer.py
Apache-2.0
def forward(self, data, valid_length, mem_data, mem_valid_length): """Run forward Parameters ---------- data - layout = 'NT' Shape (batch_size, seq_length, C_in) - layout = 'TN' Shape (seq_length, batch_size, C_in) valid_le...
Run forward Parameters ---------- data - layout = 'NT' Shape (batch_size, seq_length, C_in) - layout = 'TN' Shape (seq_length, batch_size, C_in) valid_length Shape (batch_size,) mem_data - layout = '...
forward
python
dmlc/gluon-nlp
src/gluonnlp/torch/models/transformer.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/models/transformer.py
Apache-2.0
def init_states(self, batch_size, device=None, dtype='float32'): """Initialize the states required for incremental decoding Parameters ---------- batch_size The batch size device The device dtype The data type of the states Re...
Initialize the states required for incremental decoding Parameters ---------- batch_size The batch size device The device dtype The data type of the states Returns ------- states A list of states, each incl...
init_states
python
dmlc/gluon-nlp
src/gluonnlp/torch/models/transformer.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/models/transformer.py
Apache-2.0
def incremental_decode(self, data, states, mem, mem_valid_length): """Incrementally generate the output given the decoder input. Parameters ---------- data Shape (batch_size, C_in) states The previous states, contain a list of 1. layout = 'NT'...
Incrementally generate the output given the decoder input. Parameters ---------- data Shape (batch_size, C_in) states The previous states, contain a list of 1. layout = 'NT' - prev_multi_key Shape (batch_size, prev_...
incremental_decode
python
dmlc/gluon-nlp
src/gluonnlp/torch/models/transformer.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/models/transformer.py
Apache-2.0
def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for...
Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss.
step
python
dmlc/gluon-nlp
src/gluonnlp/torch/optimizers/fused_lans.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/optimizers/fused_lans.py
Apache-2.0
def get_warmup_linear_const_decay_poly_schedule(optimizer, total_steps, warmup_ratio=0.002, const_ratio=0., degree=1.0, last_epoch=-1): """Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0, after a warmup ...
Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0, after a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer and a constant period. Args: optimizer (:class:`~torch.optim.Optimizer`): ...
get_warmup_linear_const_decay_poly_schedule
python
dmlc/gluon-nlp
src/gluonnlp/torch/optimizers/schedules.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/torch/optimizers/schedules.py
Apache-2.0
def clone_merge(self, cfg_filename_or_other_cfg): """Create a new cfg by cloning and merging with the given cfg Parameters ---------- cfg_filename_or_other_cfg Returns ------- """ ret = self.clone() if isinstance(cfg_filename_or_other_cfg, str):...
Create a new cfg by cloning and merging with the given cfg Parameters ---------- cfg_filename_or_other_cfg Returns -------
clone_merge
python
dmlc/gluon-nlp
src/gluonnlp/utils/config.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/config.py
Apache-2.0
def glob(url, separator=','): """Return a list of paths matching a pathname pattern. The pattern may contain simple shell-style wildcards. Input may also include multiple patterns, separated by separator. Parameters ---------- url : str The name of the files separator : str, defaul...
Return a list of paths matching a pathname pattern. The pattern may contain simple shell-style wildcards. Input may also include multiple patterns, separated by separator. Parameters ---------- url : str The name of the files separator : str, default is ',' The separator in url...
glob
python
dmlc/gluon-nlp
src/gluonnlp/utils/misc.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/misc.py
Apache-2.0
def file_line_number(path: str) -> int: """ Parameters ---------- path The path to calculate the number of lines in a file. Returns ------- ret The number of lines """ ret = 0 with open(path, 'rb') as f: for _ in f: ret += 1 return re...
Parameters ---------- path The path to calculate the number of lines in a file. Returns ------- ret The number of lines
file_line_number
python
dmlc/gluon-nlp
src/gluonnlp/utils/misc.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/misc.py
Apache-2.0
def md5sum(filename): """Calculate the md5sum of a file Parameters ---------- filename Name of the file Returns ------- ret The md5sum """ with open(filename, mode='rb') as f: d = hashlib.md5() for buf in iter(functools.partial(f.read, 1024*100), b''...
Calculate the md5sum of a file Parameters ---------- filename Name of the file Returns ------- ret The md5sum
md5sum
python
dmlc/gluon-nlp
src/gluonnlp/utils/misc.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/misc.py
Apache-2.0
def sha1sum(filename): """Calculate the sha1sum of a file Parameters ---------- filename Name of the file Returns ------- ret The sha1sum """ with open(filename, mode='rb') as f: d = hashlib.sha1() for buf in iter(functools.partial(f.read, 1024*100),...
Calculate the sha1sum of a file Parameters ---------- filename Name of the file Returns ------- ret The sha1sum
sha1sum
python
dmlc/gluon-nlp
src/gluonnlp/utils/misc.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/misc.py
Apache-2.0
def logging_config(folder: Optional[str] = None, name: Optional[str] = None, logger: logging.Logger = logging.root, level: int = logging.INFO, console_level: int = logging.INFO, console: bool = True, overwr...
Config the logging module. It will set the logger to save to the specified file path. Parameters ---------- folder The folder to save the log name Name of the saved logger The logger level Logging level console_level Logging level of the console log ...
logging_config
python
dmlc/gluon-nlp
src/gluonnlp/utils/misc.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/misc.py
Apache-2.0
def logerror(logger: logging.Logger = logging.root): """A decorator that wraps the passed in function and logs exceptions. Parameters ---------- logger: logging.Logger The logger to which to log the error. """ def log_wrapper(function): @functools.wraps(function) def wra...
A decorator that wraps the passed in function and logs exceptions. Parameters ---------- logger: logging.Logger The logger to which to log the error.
logerror
python
dmlc/gluon-nlp
src/gluonnlp/utils/misc.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/misc.py
Apache-2.0
def grouper(iterable, n, fillvalue=None): """Collect data into fixed-length chunks or blocks""" # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx args = [iter(iterable)] * n return itertools.zip_longest(*args, fillvalue=fillvalue)
Collect data into fixed-length chunks or blocks
grouper
python
dmlc/gluon-nlp
src/gluonnlp/utils/misc.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/misc.py
Apache-2.0
def repeat(iterable, count=None): """Repeat a basic iterator for multiple rounds Parameters ---------- iterable The basic iterable count Repeat the basic iterable for "count" times. If it is None, it will be an infinite iterator. Returns ------- new_iterable A n...
Repeat a basic iterator for multiple rounds Parameters ---------- iterable The basic iterable count Repeat the basic iterable for "count" times. If it is None, it will be an infinite iterator. Returns ------- new_iterable A new iterable in which the basic iterator h...
repeat
python
dmlc/gluon-nlp
src/gluonnlp/utils/misc.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/misc.py
Apache-2.0
def load_checksum_stats(path: str) -> dict: """ Parameters ---------- path Path to the stored checksum Returns ------- file_stats """ file_stats = dict() with open(path, 'r', encoding='utf-8') as f: for line in f: name, hex_hash, file_size = line.str...
Parameters ---------- path Path to the stored checksum Returns ------- file_stats
load_checksum_stats
python
dmlc/gluon-nlp
src/gluonnlp/utils/misc.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/misc.py
Apache-2.0
def download_file_from_google_drive(file_id, dest_path, overwrite=False, showsize=False): """Downloads a shared file from google drive into a given folder. Optionally unzips it. Parameters ---------- file_id: str the file identifier. You can obtain it fro...
Downloads a shared file from google drive into a given folder. Optionally unzips it. Parameters ---------- file_id: str the file identifier. You can obtain it from the sharable link. dest_path: str the destination where to save the downloaded ...
download_file_from_google_drive
python
dmlc/gluon-nlp
src/gluonnlp/utils/misc.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/misc.py
Apache-2.0
def download(url: str, path: Optional[str] = None, overwrite: Optional[bool] = False, sha1_hash: Optional[str] = None, retries: Optional[int] = 5, verify_ssl: Optional[bool] = True, anonymous_credential: Optional[bool] = True) -> str: """...
Download a given URL Parameters ---------- url URL to download path Destination path to store downloaded file. By default stores to the current directory with same name as in url. overwrite Whether to overwrite destination file if already exists. sha1_hash ...
download
python
dmlc/gluon-nlp
src/gluonnlp/utils/misc.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/misc.py
Apache-2.0
def check_version(min_version: str, warning_only: bool = False, library: Optional[ModuleType] = None): """Check the version of gluonnlp satisfies the provided minimum version. An exception is thrown if the check does not pass. Parameters ---------- min_version ...
Check the version of gluonnlp satisfies the provided minimum version. An exception is thrown if the check does not pass. Parameters ---------- min_version Minimum version warning_only Printing a warning instead of throwing an exception. library The target library for ver...
check_version
python
dmlc/gluon-nlp
src/gluonnlp/utils/misc.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/misc.py
Apache-2.0
def init_comm(backend, gpus): """Init communication backend Parameters ---------- backend The communication backend gpus Returns ------- store The kvstore num_workers The total number of workers rank local_rank is_master_node ctx_l """ ...
Init communication backend Parameters ---------- backend The communication backend gpus Returns ------- store The kvstore num_workers The total number of workers rank local_rank is_master_node ctx_l
init_comm
python
dmlc/gluon-nlp
src/gluonnlp/utils/misc.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/misc.py
Apache-2.0
def get_mxnet_visible_ctx(): """Get the visible contexts in MXNet. - If GPU is available it will return all the visible GPUs, which can be controlled via "CUDA_VISIBLE_DEVICES". - If no GPU is available it will return the cpu device. Returns ------- ctx_l The recommende...
Get the visible contexts in MXNet. - If GPU is available it will return all the visible GPUs, which can be controlled via "CUDA_VISIBLE_DEVICES". - If no GPU is available it will return the cpu device. Returns ------- ctx_l The recommended contexts to use for MXNet
get_mxnet_visible_ctx
python
dmlc/gluon-nlp
src/gluonnlp/utils/misc.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/misc.py
Apache-2.0
def __init__(self, params=None): """Maintain a set of shadow variables "v" that is calculated by v[:] = (1 - 1/t) v + 1/t \theta The t is the number of training steps. It is also known as "Polyak-Rupert averaging" applied to SGD and was rediscovered in "Towards Optimal One...
Maintain a set of shadow variables "v" that is calculated by v[:] = (1 - 1/t) v + 1/t heta The t is the number of training steps. It is also known as "Polyak-Rupert averaging" applied to SGD and was rediscovered in "Towards Optimal One Pass Large Scale Learning withAveraged Stoch...
__init__
python
dmlc/gluon-nlp
src/gluonnlp/utils/parameter.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/parameter.py
Apache-2.0
def apply(self, params): """ Tell the moving average tracker which parameters we are going to track. Parameters ---------- params : ParameterDict The parameters that we are going to track and calculate the moving average. """ assert self._track_params is None...
Tell the moving average tracker which parameters we are going to track. Parameters ---------- params : ParameterDict The parameters that we are going to track and calculate the moving average.
apply
python
dmlc/gluon-nlp
src/gluonnlp/utils/parameter.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/parameter.py
Apache-2.0
def copy_back(self, params=None): """ Copy the average parameters back to the given parameters Parameters ---------- params : ParameterDict The parameters that we will copy tha average params to. If it is not given, the tracked parameters will be updated ...
Copy the average parameters back to the given parameters Parameters ---------- params : ParameterDict The parameters that we will copy tha average params to. If it is not given, the tracked parameters will be updated
copy_back
python
dmlc/gluon-nlp
src/gluonnlp/utils/parameter.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/parameter.py
Apache-2.0
def grad_global_norm(parameters: Iterable[Parameter]) -> float: """Calculate the 2-norm of gradients of parameters, and how much they should be scaled down such that their 2-norm does not exceed `max_norm`, if `max_norm` if provided. If gradients exist for more than one context for a parameter, user needs t...
Calculate the 2-norm of gradients of parameters, and how much they should be scaled down such that their 2-norm does not exceed `max_norm`, if `max_norm` if provided. If gradients exist for more than one context for a parameter, user needs to explicitly call ``trainer.allreduce_grads`` so that the gradients...
grad_global_norm
python
dmlc/gluon-nlp
src/gluonnlp/utils/parameter.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/parameter.py
Apache-2.0
def clip_grad_global_norm(parameters: Iterable[Parameter], max_norm: float, check_isfinite: bool = True) -> Tuple[float, float, bool]: """Rescales gradients of parameters so that the sum of their 2-norm is smaller than `max_norm`. If gradients exist for more t...
Rescales gradients of parameters so that the sum of their 2-norm is smaller than `max_norm`. If gradients exist for more than one context for a parameter, user needs to explicitly call ``trainer.allreduce_grads`` so that the gradients are summed first before calculating the 2-norm. .. note:: T...
clip_grad_global_norm
python
dmlc/gluon-nlp
src/gluonnlp/utils/parameter.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/parameter.py
Apache-2.0
def move_to_ctx(arr, ctx): """Move a nested structure of array to the given context Parameters ---------- arr The input array ctx The MXNet context Returns ------- new_arr The array that has been moved to context """ if isinstance(arr, tuple): re...
Move a nested structure of array to the given context Parameters ---------- arr The input array ctx The MXNet context Returns ------- new_arr The array that has been moved to context
move_to_ctx
python
dmlc/gluon-nlp
src/gluonnlp/utils/parameter.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/parameter.py
Apache-2.0
def deduplicate_param_dict(param_dict): """Get a parameter dict that has been deduplicated Parameters ---------- param_dict The parameter dict returned by `model.collect_params()` Returns ------- dedup_param_dict """ dedup_param_dict = dict() param_uuid_set = set() ...
Get a parameter dict that has been deduplicated Parameters ---------- param_dict The parameter dict returned by `model.collect_params()` Returns ------- dedup_param_dict
deduplicate_param_dict
python
dmlc/gluon-nlp
src/gluonnlp/utils/parameter.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/parameter.py
Apache-2.0
def count_parameters(params) -> Tuple[int, int]: """ Parameters ---------- params The input parameter dict Returns ------- num_params The number of parameters that requires gradient num_fixed_params The number of parameters that does not require gradient """...
Parameters ---------- params The input parameter dict Returns ------- num_params The number of parameters that requires gradient num_fixed_params The number of parameters that does not require gradient
count_parameters
python
dmlc/gluon-nlp
src/gluonnlp/utils/parameter.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/parameter.py
Apache-2.0
def get_trimmed_lengths(lengths: List[int], max_length: int, do_merge: bool = False) -> np.ndarray: """Get the trimmed lengths of multiple text data. It will make sure that the trimmed length is smaller than or equal to the max_length - do_merge is True ...
Get the trimmed lengths of multiple text data. It will make sure that the trimmed length is smaller than or equal to the max_length - do_merge is True Make sure that sum(trimmed_lengths) <= max_length. The strategy is to always try to trim the longer lengths. - do_merge is False Mak...
get_trimmed_lengths
python
dmlc/gluon-nlp
src/gluonnlp/utils/preprocessing.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/preprocessing.py
Apache-2.0
def match_tokens_with_char_spans(token_offsets: np.ndarray, spans: np.ndarray) -> np.ndarray: """Match the span offsets with the character-level offsets. For each span, we perform the following: 1: Cutoff the boundary span[0] = max(span[0], token_offsets[0, 0]) ...
Match the span offsets with the character-level offsets. For each span, we perform the following: 1: Cutoff the boundary span[0] = max(span[0], token_offsets[0, 0]) span[1] = min(span[1], token_offsets[-1, 1]) 2: Find start + end We try to select the smallest number of tokens that c...
match_tokens_with_char_spans
python
dmlc/gluon-nlp
src/gluonnlp/utils/preprocessing.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/preprocessing.py
Apache-2.0
def register(self, *args): """ Register the given object under either the nickname or `obj.__name__`. It can be used as either a decorator or not. See docstring of this class for usage. """ if len(args) == 2: # Register an object with nick name by function call ...
Register the given object under either the nickname or `obj.__name__`. It can be used as either a decorator or not. See docstring of this class for usage.
register
python
dmlc/gluon-nlp
src/gluonnlp/utils/registry.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/registry.py
Apache-2.0
def create(self, name: str, *args, **kwargs) -> object: """Create the class object with the given args and kwargs Parameters ---------- name The name in the registry args kwargs Returns ------- ret The created object ...
Create the class object with the given args and kwargs Parameters ---------- name The name in the registry args kwargs Returns ------- ret The created object
create
python
dmlc/gluon-nlp
src/gluonnlp/utils/registry.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/registry.py
Apache-2.0
def serialize(path, tbl): """Serialize tbl with out-of-band data to path for zero-copy shared memory usage. If the object to be serialized itself, or the objects it uses for data storage (such as numpy arrays) implement the the pickle protocol version 5 pickle.PickleBuffer type in __reduce_ex__, then t...
Serialize tbl with out-of-band data to path for zero-copy shared memory usage. If the object to be serialized itself, or the objects it uses for data storage (such as numpy arrays) implement the the pickle protocol version 5 pickle.PickleBuffer type in __reduce_ex__, then this function can store these ...
serialize
python
dmlc/gluon-nlp
src/gluonnlp/utils/shm.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/shm.py
Apache-2.0
def load(path): """Load serialized object with out-of-band data from path based on zero-copy shared memory. Parameters ---------- path : pathlib.Path Folder used to save serialized data with serialize(). Usually a folder /dev/shm """ num_buffers = len(list(path.iterdir())) - 1 # exclu...
Load serialized object with out-of-band data from path based on zero-copy shared memory. Parameters ---------- path : pathlib.Path Folder used to save serialized data with serialize(). Usually a folder /dev/shm
load
python
dmlc/gluon-nlp
src/gluonnlp/utils/shm.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/shm.py
Apache-2.0
def is_match_states_batch_size(states, states_batch_axis, batch_size) -> bool: """Test whether the generated states have the specified batch size Parameters ---------- states The states structure states_batch_axis The states batch axis structure batch_size The batch size...
Test whether the generated states have the specified batch size Parameters ---------- states The states structure states_batch_axis The states batch axis structure batch_size The batch size Returns ------- ret
is_match_states_batch_size
python
dmlc/gluon-nlp
src/gluonnlp/utils/testing.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/testing.py
Apache-2.0
def verify_nmt_model(model, batch_size: int = 4, src_seq_length: int = 5, tgt_seq_length: int = 10, atol: float = 1E-4, rtol: float = 1E-3): """Verify the correctness of an NMT model. Raise error message if it detects problems. ...
Verify the correctness of an NMT model. Raise error message if it detects problems. Parameters ---------- model The machine translation model batch_size The batch size to test the nmt model src_seq_length Length of the source sequence tgt_seq_length Length of the...
verify_nmt_model
python
dmlc/gluon-nlp
src/gluonnlp/utils/testing.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/testing.py
Apache-2.0
def verify_nmt_inference(train_model, inference_model, batch_size=4, src_seq_length=5, tgt_seq_length=10, atol=1E-4, rtol=1E-3): """Verify the correctness of an NMT inference model. Raise error message if it detects any problems. Parameters ---------- ...
Verify the correctness of an NMT inference model. Raise error message if it detects any problems. Parameters ---------- train_model The training model inference_model The inference model batch_size Batch size src_seq_length Length of the source sequence t...
verify_nmt_inference
python
dmlc/gluon-nlp
src/gluonnlp/utils/testing.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/testing.py
Apache-2.0
def _cast_nested_to_fp16(nested_dat): """Cast the nested input to fp16 Parameters ---------- dat The input nested data structure Returns ------- output The casted output data """ if isinstance(nested_dat, (mx.np.ndarray, np.ndarray)): if nested_dat.dtype == ...
Cast the nested input to fp16 Parameters ---------- dat The input nested data structure Returns ------- output The casted output data
_cast_nested_to_fp16
python
dmlc/gluon-nlp
src/gluonnlp/utils/testing.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/testing.py
Apache-2.0
def verify_backbone_fp16(model_cls, cfg, ctx, inputs, atol=1E-2, rtol=1E-2, check_amp=True): """Test whether the backbone model has the comparable parameter gradient + Parameters ---------- model_cls The modeling class cfg The configuration ctx T...
Test whether the backbone model has the comparable parameter gradient + Parameters ---------- model_cls The modeling class cfg The configuration ctx The context inputs The input tensors of the model. We will atol The absolute tolerance rtol ...
verify_backbone_fp16
python
dmlc/gluon-nlp
src/gluonnlp/utils/testing.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/testing.py
Apache-2.0
def get_ec2_tvm_flags() -> Dict[str, Dict]: r"""Return the recommended flags for TVM compilation in AWS EC2 instances. Including C4, C5, G4, P3. For more details about AWS EC2 instances, refer to https://aws.amazon.com/ec2/instance-types/. Returns ------- info_dict A dictionary that c...
Return the recommended flags for TVM compilation in AWS EC2 instances. Including C4, C5, G4, P3. For more details about AWS EC2 instances, refer to https://aws.amazon.com/ec2/instance-types/. Returns ------- info_dict A dictionary that contains the mapping between instance type and the ...
get_ec2_tvm_flags
python
dmlc/gluon-nlp
src/gluonnlp/utils/tvm_utils.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/tvm_utils.py
Apache-2.0
def update_tvm_convert_map() -> None: """A Monkey Patch to update convert map in tvm/relay/frontend/mxnet.py""" op = (('masked_softmax', _mx_masked_softmax),) _convert_map.update({key: value for key, value in op})
A Monkey Patch to update convert map in tvm/relay/frontend/mxnet.py
update_tvm_convert_map
python
dmlc/gluon-nlp
src/gluonnlp/utils/tvm_utils.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/utils/tvm_utils.py
Apache-2.0
def test_test(): """Test that fixing a random seed works.""" py_rnd = random.randint(0, 100) np_rnd = np.random.randint(0, 100) mx_rnd = mx.nd.random_uniform(shape=(1, )).asscalar() random.seed(1) mx.random.seed(1) np.random.seed(1) assert py_rnd == random.randint(0, 100) assert np...
Test that fixing a random seed works.
test_test
python
dmlc/gluon-nlp
tests/test_pytest.py
https://github.com/dmlc/gluon-nlp/blob/master/tests/test_pytest.py
Apache-2.0
def is_image_file(filename): """Checks if a file is an image. Args: filename (string): path to a file Returns: bool: True if the filename ends with a known image extension """ filename_lower = filename.lower() return any(filename_lower.endswith(ext) for ext in IMG_EXTENSIONS)
Checks if a file is an image. Args: filename (string): path to a file Returns: bool: True if the filename ends with a known image extension
is_image_file
python
ajbrock/BigGAN-PyTorch
datasets.py
https://github.com/ajbrock/BigGAN-PyTorch/blob/master/datasets.py
MIT
def __getitem__(self, index): """ Args: index (int): Index Returns: tuple: (image, target) where target is class_index of the target class. """ if self.load_in_mem: img = self.data[index] target = self.labels[index] else: path, target = self.imgs[index] ...
Args: index (int): Index Returns: tuple: (image, target) where target is class_index of the target class.
__getitem__
python
ajbrock/BigGAN-PyTorch
datasets.py
https://github.com/ajbrock/BigGAN-PyTorch/blob/master/datasets.py
MIT
def __getitem__(self, index): """ Args: index (int): Index Returns: tuple: (image, target) where target is index of the target class. """ img, target = self.data[index], self.labels[index] # doing this so that it is consistent with all other datasets # to return a PIL Image ...
Args: index (int): Index Returns: tuple: (image, target) where target is index of the target class.
__getitem__
python
ajbrock/BigGAN-PyTorch
datasets.py
https://github.com/ajbrock/BigGAN-PyTorch/blob/master/datasets.py
MIT
def torch_cov(m, rowvar=False): '''Estimate a covariance matrix given data. Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, `X = [x_1, x_2, ... x_N]^T`, then the covariance matrix element `C_{ij}` is the covariance of `x_i` and `x_j`. The el...
Estimate a covariance matrix given data. Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, `X = [x_1, x_2, ... x_N]^T`, then the covariance matrix element `C_{ij}` is the covariance of `x_i` and `x_j`. The element `C_{ii}` is the variance of `x_i`...
torch_cov
python
ajbrock/BigGAN-PyTorch
inception_utils.py
https://github.com/ajbrock/BigGAN-PyTorch/blob/master/inception_utils.py
MIT
def numpy_calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6): """Numpy implementation of the Frechet Distance. Taken from https://github.com/bioinf-jku/TTUR The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1...
Numpy implementation of the Frechet Distance. Taken from https://github.com/bioinf-jku/TTUR The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). Stable version by Dougal J. Sutherland. Params: ...
numpy_calculate_frechet_distance
python
ajbrock/BigGAN-PyTorch
inception_utils.py
https://github.com/ajbrock/BigGAN-PyTorch/blob/master/inception_utils.py
MIT
def torch_calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6): """Pytorch implementation of the Frechet Distance. Taken from https://github.com/bioinf-jku/TTUR The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C...
Pytorch implementation of the Frechet Distance. Taken from https://github.com/bioinf-jku/TTUR The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). Stable version by Dougal J. Sutherland. Params...
torch_calculate_frechet_distance
python
ajbrock/BigGAN-PyTorch
inception_utils.py
https://github.com/ajbrock/BigGAN-PyTorch/blob/master/inception_utils.py
MIT
def __call__(self, img): """ Args: img (PIL Image): Image to be cropped. Returns: PIL Image: Cropped image. """ size = (min(img.size), min(img.size)) # Only step forward along this edge if it's the long edge i = (0 if size[0] == img.size[0] else np.random.randint(l...
Args: img (PIL Image): Image to be cropped. Returns: PIL Image: Cropped image.
__call__
python
ajbrock/BigGAN-PyTorch
utils.py
https://github.com/ajbrock/BigGAN-PyTorch/blob/master/utils.py
MIT
def log(self, record=None, **kwargs): """ Assumption: no newlines in the input. """ if record is None: record = {} record.update(kwargs) record['_stamp'] = time.time() with open(self.fname, 'a') as f: f.write(json.dumps(record, ensure_ascii=True) + '\n')
Assumption: no newlines in the input.
log
python
ajbrock/BigGAN-PyTorch
utils.py
https://github.com/ajbrock/BigGAN-PyTorch/blob/master/utils.py
MIT
def progress(items, desc='', total=None, min_delay=0.1, displaytype='s1k'): """ Returns a generator over `items`, printing the number and percentage of items processed and the estimated remaining processing time before yielding the next item. `total` gives the total number of items (required if `items` has no...
Returns a generator over `items`, printing the number and percentage of items processed and the estimated remaining processing time before yielding the next item. `total` gives the total number of items (required if `items` has no length), and `min_delay` gives the minimum time in seconds between subsequent ...
progress
python
ajbrock/BigGAN-PyTorch
utils.py
https://github.com/ajbrock/BigGAN-PyTorch/blob/master/utils.py
MIT
def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: for p in g...
Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss.
step
python
ajbrock/BigGAN-PyTorch
utils.py
https://github.com/ajbrock/BigGAN-PyTorch/blob/master/utils.py
MIT
def _data_parallel_master(self, intermediates): """Reduce the sum and square-sum, compute the statistics, and broadcast it.""" # Always using same "device order" makes the ReduceAdd operation faster. # Thanks to:: Tete Xiao (http://tetexiao.com/) intermediates = sorted(intermediates, ke...
Reduce the sum and square-sum, compute the statistics, and broadcast it.
_data_parallel_master
python
ajbrock/BigGAN-PyTorch
sync_batchnorm/batchnorm.py
https://github.com/ajbrock/BigGAN-PyTorch/blob/master/sync_batchnorm/batchnorm.py
MIT
def _compute_mean_std(self, sum_, ssum, size): """Compute the mean and standard-deviation with sum and square-sum. This method also maintains the moving average on the master device.""" assert size > 1, 'BatchNorm computes unbiased standard-deviation, which requires size > 1.' mean = sum...
Compute the mean and standard-deviation with sum and square-sum. This method also maintains the moving average on the master device.
_compute_mean_std
python
ajbrock/BigGAN-PyTorch
sync_batchnorm/batchnorm.py
https://github.com/ajbrock/BigGAN-PyTorch/blob/master/sync_batchnorm/batchnorm.py
MIT
def __init__(self, master_callback): """ Args: master_callback: a callback to be invoked after having collected messages from slave devices. """ self._master_callback = master_callback self._queue = queue.Queue() self._registry = collections.OrderedDict() ...
Args: master_callback: a callback to be invoked after having collected messages from slave devices.
__init__
python
ajbrock/BigGAN-PyTorch
sync_batchnorm/comm.py
https://github.com/ajbrock/BigGAN-PyTorch/blob/master/sync_batchnorm/comm.py
MIT
def register_slave(self, identifier): """ Register an slave device. Args: identifier: an identifier, usually is the device id. Returns: a `SlavePipe` object which can be used to communicate with the master device. """ if self._activated: assert ...
Register an slave device. Args: identifier: an identifier, usually is the device id. Returns: a `SlavePipe` object which can be used to communicate with the master device.
register_slave
python
ajbrock/BigGAN-PyTorch
sync_batchnorm/comm.py
https://github.com/ajbrock/BigGAN-PyTorch/blob/master/sync_batchnorm/comm.py
MIT
def run_master(self, master_msg): """ Main entry for the master device in each forward pass. The messages were first collected from each devices (including the master device), and then an callback will be invoked to compute the message to be sent back to each devices (including t...
Main entry for the master device in each forward pass. The messages were first collected from each devices (including the master device), and then an callback will be invoked to compute the message to be sent back to each devices (including the master device). Args: ...
run_master
python
ajbrock/BigGAN-PyTorch
sync_batchnorm/comm.py
https://github.com/ajbrock/BigGAN-PyTorch/blob/master/sync_batchnorm/comm.py
MIT
def execute_replication_callbacks(modules): """ Execute an replication callback `__data_parallel_replicate__` on each module created by original replication. The callback will be invoked with arguments `__data_parallel_replicate__(ctx, copy_id)` Note that, as all modules are isomorphism, we assign eac...
Execute an replication callback `__data_parallel_replicate__` on each module created by original replication. The callback will be invoked with arguments `__data_parallel_replicate__(ctx, copy_id)` Note that, as all modules are isomorphism, we assign each sub-module with a context (shared among multi...
execute_replication_callbacks
python
ajbrock/BigGAN-PyTorch
sync_batchnorm/replicate.py
https://github.com/ajbrock/BigGAN-PyTorch/blob/master/sync_batchnorm/replicate.py
MIT
def patch_replication_callback(data_parallel): """ Monkey-patch an existing `DataParallel` object. Add the replication callback. Useful when you have customized `DataParallel` implementation. Examples: > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False) > sync_bn = DataParal...
Monkey-patch an existing `DataParallel` object. Add the replication callback. Useful when you have customized `DataParallel` implementation. Examples: > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False) > sync_bn = DataParallel(sync_bn, device_ids=[0, 1]) > patch_replic...
patch_replication_callback
python
ajbrock/BigGAN-PyTorch
sync_batchnorm/replicate.py
https://github.com/ajbrock/BigGAN-PyTorch/blob/master/sync_batchnorm/replicate.py
MIT
def dump_tfhub_to_hdf5(module_path, hdf5_path, redownload=False): """Loads TFHub weights and saves them to intermediate HDF5 file. Args: module_path ([Path-like]): Path to TFHub module. hdf5_path ([Path-like]): Path to output HDF5 file. Returns: [h5py.File]: Loaded hdf5 file containing module weight...
Loads TFHub weights and saves them to intermediate HDF5 file. Args: module_path ([Path-like]): Path to TFHub module. hdf5_path ([Path-like]): Path to output HDF5 file. Returns: [h5py.File]: Loaded hdf5 file containing module weights.
dump_tfhub_to_hdf5
python
ajbrock/BigGAN-PyTorch
TFHub/converter.py
https://github.com/ajbrock/BigGAN-PyTorch/blob/master/TFHub/converter.py
MIT
def read_img(t_imgfname, input_size, img_mean): # optional pre-processing arguments """Read one image and its corresponding mask with optional pre-processing. Args: input_queue: tf queue with paths to the image and its mask. input_size: a tuple with (height, width) values. If not given, return images of...
Read one image and its corresponding mask with optional pre-processing. Args: input_queue: tf queue with paths to the image and its mask. input_size: a tuple with (height, width) values. If not given, return images of original size. random_scale: whether to randomly scale the images prior to rand...
read_img
python
iyah4888/SIGGRAPH18SSS
main_hyper.py
https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/main_hyper.py
MIT