text stringlengths 1 93.6k |
|---|
self.optimizer.zero_grad()
|
def clear_buffered_stats(self):
|
self._buffered_stats.clear()
|
def get_num_updates(self):
|
"""Get the number of parameters updates."""
|
return self._num_updates
|
def _prepare_sample(self, sample):
|
if sample is None or len(sample) == 0:
|
return None
|
return utils.move_to_cuda(sample)
|
def dummy_train_step(self, dummy_batch):
|
"""Dummy training step for warming caching allocator."""
|
self.train_step(dummy_batch, update_params=False)
|
self.zero_grad()
|
self.clear_buffered_stats()
|
def compute_score_with_logits(logits, labels):
|
logits = torch.max(logits, 1)[1].data # argmax
|
one_hots = torch.zeros(*labels.size()).to(logits.device)
|
one_hots.scatter_(1, logits.view(-1, 1), 1)
|
scores = (one_hots * labels)
|
return scores
|
# <FILESEP>
|
"""Contains various utility functions for Dynet models."""
|
import dynet as dy
|
import numpy as np
|
def add_dim(variable, dim=0):
|
""" Adds a dimension to a vector dy.Expression.
|
Inputs:
|
variable (dy.Expression): A vector Dynet expression.
|
dim (int, optional): The dimension to add.
|
Returns:
|
dy.Expression with one more dimension (of size 1).
|
"""
|
var_size = variable.dim()[0][0]
|
if dim == 0:
|
return dy.reshape(variable, (1, var_size))
|
else:
|
return dy.reshape(variable, (var_size, 1))
|
def is_vector(exp):
|
""" Returns whether the expression is a vector.
|
Inputs:
|
exp (dy.Expression): The expression to check.
|
Returns:
|
bool, representing whether the expression is a vector.
|
"""
|
return len(exp.dim()[0]) == 1
|
def split_exp(exp, num=2):
|
""" Splits an expression into n parts.
|
Inputs:
|
exp (dy.Expression): A vector Dynet expression.
|
num (int, optional): The number of parts to split it into.
|
Returns:
|
list of dy.Expression, containing the split expression.
|
"""
|
assert is_vector(exp)
|
size = exp.dim()[0][0]
|
split_amount = int(size / num)
|
parts = []
|
for i in range(num):
|
parts.append(exp[i * split_amount: (i + 1) * split_amount])
|
return parts
|
def linear_transform(exp, params):
|
""" Multiplies a dy.Expression and a set of parameters.
|
Inputs:
|
exp (dy.Expression): A Dynet tensor.
|
params (dy.Parameters): Dynet parameters.
|
Returns:
|
dy.Expression representing exp * params.
|
"""
|
if is_vector(exp):
|
exp = add_dim(exp)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.