code stringlengths 17 6.64M |
|---|
def generate_instruction_following_data(output_dir='./', seed_tasks_path='./seed_tasks.jsonl', num_instructions_to_generate=20000, model_name='text-davinci-003', num_prompt_instructions=3, request_batch_size=5, temperature=1.0, top_p=1.0, num_cpus=16):
seed_tasks = [json.loads(l) for l in open(seed_tasks_path, 'r... |
def main(task, **kwargs):
globals()[task](**kwargs)
|
def train(base_model: str='', data_path: str='yahma/alpaca-cleaned', output_dir: str='./lora-alpaca', batch_size: int=128, micro_batch_size: int=8, num_epochs: int=1, learning_rate: float=0.0003, cutoff_len: int=2048, val_set_size: int=2000, lora_r: int=8, lora_alpha: int=16, lora_dropout: float=0.05, lora_target_mod... |
@dataclass
class ModelArguments():
model_name_or_path: Optional[str] = field(default='facebook/opt-125m')
|
@dataclass
class DataArguments():
data_path: str = field(default=None, metadata={'help': 'Path to the training data.'})
|
@dataclass
class TrainingArguments(transformers.TrainingArguments):
cache_dir: Optional[str] = field(default=None)
optim: str = field(default='adamw_torch')
model_max_length: int = field(default=512, metadata={'help': 'Maximum sequence length. Sequences will be right padded (and possibly truncated).'})
|
def smart_tokenizer_and_embedding_resize(special_tokens_dict: Dict, tokenizer: transformers.PreTrainedTokenizer, model: transformers.PreTrainedModel):
'Resize tokenizer and embedding.\n\n Note: This is the unoptimized version that may make your embedding size not be divisible by 64.\n '
num_new_tokens =... |
def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict:
'Tokenize a list of strings.'
tokenized_list = [tokenizer(text, return_tensors='pt', padding='longest', max_length=tokenizer.model_max_length, truncation=True) for text in strings]
input_ids = labels = [tokenize... |
def preprocess(sources: Sequence[str], targets: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict:
'Preprocess the data by tokenizing.'
examples = [(s + t) for (s, t) in zip(sources, targets)]
(examples_tokenized, sources_tokenized) = [_tokenize_fn(strings, tokenizer) for strings in (exa... |
class SupervisedDataset(Dataset):
'Dataset for supervised fine-tuning.'
def __init__(self, data_path: str, tokenizer: transformers.PreTrainedTokenizer):
super(SupervisedDataset, self).__init__()
logging.warning('Loading data...')
list_data_dict = utils.jload(data_path)
logging... |
@dataclass
class DataCollatorForSupervisedDataset(object):
'Collate examples for supervised fine-tuning.'
tokenizer: transformers.PreTrainedTokenizer
def __call__(self, instances: Sequence[Dict]) -> Dict[(str, torch.Tensor)]:
(input_ids, labels) = tuple(([instance[key] for instance in instances] ... |
def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict:
'Make dataset and collator for supervised fine-tuning.'
train_dataset = SupervisedDataset(tokenizer=tokenizer, data_path=data_args.data_path)
data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenize... |
def train():
parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))
(model_args, data_args, training_args) = parser.parse_args_into_dataclasses()
model = transformers.AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path, cache_dir=training_args.cache_dir)
... |
@dataclasses.dataclass
class OpenAIDecodingArguments(object):
max_tokens: int = 1800
temperature: float = 0.2
top_p: float = 1.0
n: int = 1
stream: bool = False
stop: Optional[Sequence[str]] = None
presence_penalty: float = 0.0
frequency_penalty: float = 0.0
suffix: Optional[str] =... |
def openai_completion(prompts: Union[(str, Sequence[str], Sequence[dict[(str, str)]], dict[(str, str)])], decoding_args: OpenAIDecodingArguments, model_name='text-davinci-003', sleep_time=2, batch_size=1, max_instances=sys.maxsize, max_batches=sys.maxsize, return_text=False, **decoding_kwargs) -> Union[(Union[StrOrOp... |
def _make_w_io_base(f, mode: str):
if (not isinstance(f, io.IOBase)):
f_dirname = os.path.dirname(f)
if (f_dirname != ''):
os.makedirs(f_dirname, exist_ok=True)
f = open(f, mode=mode)
return f
|
def _make_r_io_base(f, mode: str):
if (not isinstance(f, io.IOBase)):
f = open(f, mode=mode)
return f
|
def jdump(obj, f, mode='w', indent=4, default=str):
'Dump a str or dictionary to a file in json format.\n\n Args:\n obj: An object to be written.\n f: A string path to the location on disk.\n mode: Mode for opening the file.\n indent: Indent for storing json dictionaries.\n d... |
def jload(f, mode='r'):
'Load a .json file into a dictionary.'
f = _make_r_io_base(f, mode)
jdict = json.load(f)
f.close()
return jdict
|
@register_model
def mvit_tiny(pretrained=False, **kwargs):
cfg = get_cfg()
cfg_file = '../SlowFast_dev/configs/ImageNet/MVIT_T_10_CONV.yaml'
cfg.merge_from_file(cfg_file)
model = MViT(cfg)
return model
|
class INatDataset(ImageFolder):
def __init__(self, root, train=True, year=2018, transform=None, target_transform=None, category='name', loader=default_loader):
self.transform = transform
self.loader = loader
self.target_transform = target_transform
self.year = year
path_js... |
def build_dataset(is_train, args):
transform = build_transform(is_train, args)
if (args.data_set == 'CIFAR'):
dataset = datasets.CIFAR100(args.data_path, train=is_train, transform=transform)
nb_classes = 100
elif (args.data_set == 'IMNET'):
root = os.path.join(args.data_path, ('tra... |
def build_transform(is_train, args):
resize_im = (args.input_size > 32)
if is_train:
transform = create_transform(input_size=args.input_size, is_training=True, color_jitter=args.color_jitter, auto_augment=args.aa, interpolation=args.train_interpolation, re_prob=args.reprob, re_mode=args.remode, re_cou... |
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0):
super().__init__()
out_features = (out_features or in_features)
hidden_features = (hidden_features or in_features)
self.fc1 = nn.Linear(in_features, hidden_... |
class CMlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0):
super().__init__()
out_features = (out_features or in_features)
hidden_features = (hidden_features or in_features)
self.fc1 = nn.Conv2d(in_features, hidden... |
class GlobalSparseAttn(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0, sr_ratio=1):
super().__init__()
self.num_heads = num_heads
head_dim = (dim // num_heads)
self.scale = (qk_scale or (head_dim ** (- 0.5)))
se... |
class LocalAgg(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm):
super().__init__()
self.pos_embed = nn.Conv2d(dim, dim, 3, padding=1, groups=dim)
self.norm1 = n... |
class SelfAttn(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1.0):
super().__init__()
self.pos_embed = nn.Conv2d(dim, dim, 3, padding=1, groups=dim)
... |
class LGLBlock(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1.0):
super().__init__()
if (sr_ratio > 1):
self.LocalAgg = LocalAgg(dim, num_heads,... |
class PatchEmbed(nn.Module):
' Image to Patch Embedding\n '
def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
super().__init__()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
num_patches = ((img_size[1] // patch_size[1]) * (img_... |
class EdgeVit(nn.Module):
' Vision Transformer\n A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` -\n https://arxiv.org/abs/2010.11929\n '
def __init__(self, depth=[1, 2, 5, 3], img_size=224, in_chans=3, num_classes=1000, embed_dim=[48, 96, 240, 3... |
@register_model
def edgevit_xxs(pretrained=True, **kwargs):
model = EdgeVit(depth=[1, 1, 3, 2], embed_dim=[36, 72, 144, 288], head_dim=36, mlp_ratio=([4] * 4), qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-06), sr_ratios=[4, 2, 2, 1], **kwargs)
model.default_cfg = _cfg()
return model
|
@register_model
def edgevit_xs(pretrained=True, **kwargs):
model = EdgeVit(depth=[1, 1, 3, 1], embed_dim=[48, 96, 240, 384], head_dim=48, mlp_ratio=([4] * 4), qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-06), sr_ratios=[4, 2, 2, 1], **kwargs)
model.default_cfg = _cfg()
return model
|
@register_model
def edgevit_s(pretrained=True, **kwargs):
model = EdgeVit(depth=[1, 2, 5, 3], embed_dim=[48, 96, 240, 384], head_dim=48, mlp_ratio=([4] * 4), qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-06), sr_ratios=[4, 2, 2, 1], **kwargs)
model.default_cfg = _cfg()
return model
|
def train_one_epoch(model: torch.nn.Module, criterion: DistillationLoss, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, loss_scaler, max_norm: float=0, model_ema: Optional[ModelEma]=None, mixup_fn: Optional[Mixup]=None, set_training_mode=True):
model.train(set_training_... |
@torch.no_grad()
def evaluate(data_loader, model, device):
criterion = torch.nn.CrossEntropyLoss()
metric_logger = utils.MetricLogger(delimiter=' ')
header = 'Test:'
model.eval()
for (images, target) in metric_logger.log_every(data_loader, 10, header):
images = images.to(device, non_block... |
class Imagenet(torch.utils.data.Dataset):
'ImageNet dataset.'
def __init__(self, root_path, train=True, transform=None):
if train:
self.mode = 'train'
else:
self.mode = 'val'
self.data_path = root_path
self._construct_imdb_h5()
self.transform = ... |
class DistillationLoss(torch.nn.Module):
'\n This module wraps a standard criterion and adds an extra knowledge distillation loss by\n taking a teacher model prediction and using it as additional supervision.\n '
def __init__(self, base_criterion: torch.nn.Module, teacher_model: torch.nn.Module, dis... |
class RASampler(torch.utils.data.Sampler):
'Sampler that restricts data loading to a subset of the dataset for distributed,\n with repeated augmentation.\n It ensures that different each augmented version of a sample will be visible to a\n different process (GPU)\n Heavily based on torch.utils.data.Di... |
class SmoothedValue(object):
'Track a series of values and provide access to smoothed values over a\n window or the global series average.\n '
def __init__(self, window_size=20, fmt=None):
if (fmt is None):
fmt = '{median:.4f} ({global_avg:.4f})'
self.deque = deque(maxlen=wi... |
class MetricLogger(object):
def __init__(self, delimiter='\t'):
self.meters = defaultdict(SmoothedValue)
self.delimiter = delimiter
def update(self, **kwargs):
for (k, v) in kwargs.items():
if isinstance(v, torch.Tensor):
v = v.item()
assert is... |
def _load_checkpoint_for_ema(model_ema, checkpoint):
'\n Workaround for ModelEma._load_checkpoint to accept an already-loaded object\n '
mem_file = io.BytesIO()
torch.save(checkpoint, mem_file)
mem_file.seek(0)
model_ema._load_checkpoint(mem_file)
|
def setup_for_distributed(is_master):
'\n This function disables printing when not in master process\n '
import builtins as __builtin__
builtin_print = __builtin__.print
def print(*args, **kwargs):
force = kwargs.pop('force', False)
if (is_master or force):
builtin_p... |
def is_dist_avail_and_initialized():
if (not dist.is_available()):
return False
if (not dist.is_initialized()):
return False
return True
|
def get_world_size():
if (not is_dist_avail_and_initialized()):
return 1
return dist.get_world_size()
|
def get_rank():
if (not is_dist_avail_and_initialized()):
return 0
return dist.get_rank()
|
def is_main_process():
return (get_rank() == 0)
|
def save_on_master(*args, **kwargs):
if is_main_process():
torch.save(*args, **kwargs)
|
def init_distributed_mode(args):
if (('RANK' in os.environ) and ('WORLD_SIZE' in os.environ)):
args.rank = int(os.environ['RANK'])
args.world_size = int(os.environ['WORLD_SIZE'])
args.gpu = int(os.environ['LOCAL_RANK'])
elif ('SLURM_PROCID' in os.environ):
args.rank = int(os.en... |
class BatchGraph():
def __init__(self):
self.graph = DGLGraph()
self.number_of_nodes = 0
self.graphid_to_nodeids = {}
self.num_of_subgraphs = 0
def add_subgraph(self, _g):
assert isinstance(_g, DGLGraph)
num_new_nodes = _g.number_of_nodes()
self.graphi... |
class GGNNBatchGraph(BatchGraph):
def get_network_inputs(self, cuda=False, device=None):
features = self.graph.ndata['features']
edge_types = self.graph.edata['etype']
if cuda:
self.cuda(device=device)
return (self.graph, features.cuda(device=device), edge_types.cu... |
class DataEntry():
def __init__(self, datset, num_nodes, features, edges, target):
self.dataset = datset
self.num_nodes = num_nodes
self.target = target
self.graph = DGLGraph()
self.features = torch.FloatTensor(features)
self.graph.add_nodes(self.num_nodes, data={'... |
class DataSet():
def __init__(self, train_src, valid_src=None, test_src=None, batch_size=32, n_ident=None, g_ident=None, l_ident=None):
self.train_examples = []
self.valid_examples = []
self.test_examples = []
self.train_batches = []
self.valid_batches = []
self.te... |
class DevignModel(nn.Module):
def __init__(self, input_dim, output_dim, max_edge_types, num_steps=8):
super(DevignModel, self).__init__()
self.inp_dim = input_dim
self.out_dim = output_dim
self.max_edge_types = max_edge_types
self.num_timesteps = num_steps
self.ggn... |
class GGNNSum(nn.Module):
def __init__(self, input_dim, output_dim, max_edge_types, num_steps=8):
super(GGNNSum, self).__init__()
self.inp_dim = input_dim
self.out_dim = output_dim
self.max_edge_types = max_edge_types
self.num_timesteps = num_steps
self.ggnn = Gate... |
def evaluate_loss(model, loss_function, num_batches, data_iter, cuda=False):
model.eval()
with torch.no_grad():
_loss = []
(all_predictions, all_targets) = ([], [])
for _ in range(num_batches):
(graph, targets) = data_iter()
targets = targets.cuda()
... |
def evaluate_metrics(model, loss_function, num_batches, data_iter):
model.eval()
with torch.no_grad():
_loss = []
(all_predictions, all_targets) = ([], [])
for _ in range(num_batches):
(graph, targets) = data_iter()
targets = targets.cuda()
predictio... |
def train(model, dataset, max_steps, dev_every, loss_function, optimizer, save_path, log_every=50, max_patience=5):
debug('Start Training')
train_losses = []
best_model = None
patience_counter = 0
best_f1 = 0
try:
for step_count in range(max_steps):
model.train()
... |
def load_default_identifiers(n, g, l):
if (n is None):
n = n_identifier
if (g is None):
g = g_identifier
if (l is None):
l = l_identifier
return (n, g, l)
|
def initialize_batch(entries, batch_size, shuffle=False):
total = len(entries)
indices = np.arange(0, (total - 1), 1)
if shuffle:
np.random.shuffle(indices)
batch_indices = []
start = 0
end = len(indices)
curr = start
while (curr < end):
c_end = (curr + batch_size)
... |
def tally_param(model):
total = 0
for param in model.parameters():
total += param.data.nelement()
return total
|
def debug(*msg, sep='\t'):
caller = inspect.stack()[1]
file_name = caller.filename
ln = caller.lineno
now = datetime.now()
time = now.strftime('%m/%d/%Y - %H:%M:%S')
print((((((('[' + str(time)) + '] File "') + file_name) + '", line ') + str(ln)) + ' '), end='\t')
for m in msg:
pr... |
class CSharpProcessor():
@classmethod
def create_dead_for_loop(cls, body):
control_variable = ('_i_' + str(np.random.choice(list(range(10)))))
p = np.random.uniform(0, 1)
if (p < 0.5):
prefix = (((((('for ( int ' + control_variable) + ' = 0 ; ') + control_variable) + ' > 0... |
class GoProcessor():
@classmethod
def create_dead_for_loop(cls, body):
control_variable = ('_i_' + str(np.random.choice(list(range(10)))))
return (((f'for {control_variable} := 0 ; {control_variable} < 0; {control_variable}++' + ' { ') + body) + ' } ')
@classmethod
def create_dead_wh... |
class JavaAndCPPProcessor():
@classmethod
def create_dead_for_loop(cls, body):
control_variable = ('_i_' + str(np.random.choice(list(range(10)))))
p = np.random.uniform(0, 1)
if (p < 0.5):
prefix = (((((('for ( int ' + control_variable) + ' = 0 ; ') + control_variable) + '... |
class JavascriptProcessor():
@classmethod
def create_dead_for_loop(cls, body):
control_variable = ('_i_' + str(np.random.choice(list(range(10)))))
p = np.random.uniform(0, 1)
if (p < 0.5):
prefix = (((((('for ( let ' + control_variable) + ' = 0 ; ') + control_variable) + '... |
class PhpProcessor():
@classmethod
def create_dead_for_loop(cls, body):
control_variable = ('$_i_' + str(np.random.choice(list(range(10)))))
p = np.random.uniform(0, 1)
if (p < 0.5):
prefix = f'for ( {control_variable} = 0 ; {control_variable} > 0 ; {control_variable}++ ... |
class PythonProcessor():
@classmethod
def create_dead_for_loop(cls, body):
control_variable = ('_i_' + str(np.random.choice(list(range(10)))))
loop = f'NEWLINE for {control_variable} in range ( 0 ) : NEWLINE INDENT {body} NEWLINE DEDENT '
return loop
@classmethod
def create_d... |
def get_python_tokens(code, root=None):
if isinstance(code, bytes):
code = code.decode()
tokens = []
for token in tokenize.tokenize(BytesIO(code.encode('utf-8')).readline):
if ((token.type == 0) or (token.type >= 58)):
continue
elif (token.type == 4):
tokens... |
class RubyProcessor():
@classmethod
def create_dead_for_loop(cls, body):
control_variable = ('_i_' + str(np.random.choice(list(range(10)))))
return f'for {control_variable} in 0..0 do {body} end '
@classmethod
def create_dead_while_loop(cls, body):
p = np.random.uniform(0, 1)... |
def get_tokens(code_str, root):
if isinstance(code_str, str):
code_str = code_str.encode()
assert isinstance(root, Node)
tokens = []
if (root.type == 'comment'):
return tokens
if ('string' in str(root.type)):
return [code_str[root.start_byte:root.end_byte].decode()]
chi... |
def get_tokens_insert_before(code_str, root, insertion_code, insert_before_node):
if isinstance(code_str, str):
code_str = code_str.encode()
assert isinstance(root, Node)
tokens = []
if (root.type == 'comment'):
return tokens
if ('string' in str(root.type)):
return [code_st... |
def dfs_print(root, level=0):
for _ in range(level):
print('\t', end='')
print(root)
for child in root.children:
dfs_print(child, (level + 1))
|
def count_nodes(root):
num_nodes = 1
for child in root.children:
if (child is not None):
num_nodes += count_nodes(child)
return num_nodes
|
def extract_statement_within_size(root, max_node=10, endswith=None, code_string=None, tokenizer=None):
if (endswith is None):
endswith = ['statement']
statements = []
queue = [root]
while (len(queue) > 0):
current_node = queue[0]
queue = queue[1:]
node_count = count_nod... |
class BlockSwap(TransformationBase):
'\n Swapping if_else block\n '
def __init__(self, parser_path, language):
super(BlockSwap, self).__init__(parser_path=parser_path, language=language)
self.language = language
self.transformations = processor_function[language]
process... |
class ConfusionRemover(TransformationBase):
'\n Change the `for` loops with `while` loops and vice versa.\n '
def __init__(self, parser_path, language):
super(ConfusionRemover, self).__init__(parser_path=parser_path, language=language)
self.language = language
if (language in pr... |
class DeadCodeInserter(TransformationBase):
def __init__(self, parser_path: str, language: str):
super(DeadCodeInserter, self).__init__(parser_path=parser_path, language=language)
self.language = language
self.processor = processor_function[self.language]
self.tokenizer_function =... |
class DemoTransformation(TransformationBase):
def __init__(self, parser, language):
super(DemoTransformation, self).__init__(parser_path=parser, language=language)
def transform_code(self, code: Union[(str, bytes)]) -> Tuple[(str, object)]:
root_node = self.parse_code(code=code)
(tok... |
class ForWhileTransformer(TransformationBase):
'\n Change the `for` loops with `while` loops and vice versa.\n '
def __init__(self, parser_path, language):
super(ForWhileTransformer, self).__init__(parser_path=parser_path, language=language)
self.language = language
self.transfo... |
class NoTransformation(TransformationBase):
def __init__(self, parser_path: str, language: str) -> object:
super().__init__(parser_path, language)
if (not os.path.exists(parser_path)):
raise ValueError(f'Language parser does not exist at {parser_path}. Please run `setup.sh` to properl... |
class OperandSwap(TransformationBase):
'\n Swapping Operand "a>b" becomes "b<a"\n '
def __init__(self, parser_path, language):
super(OperandSwap, self).__init__(parser_path=parser_path, language=language)
self.language = language
self.transformations = processor_function[languag... |
def masking(tokens, p):
new_tokens = []
for t in tokens:
if (np.random.uniform() < p):
new_tokens.append('<mask>')
else:
new_tokens.append(t)
return ' '.join(new_tokens)
|
def deletion(tokens, p):
new_tokens = []
for t in tokens:
if (np.random.uniform() >= p):
new_tokens.append(t)
return ' '.join(new_tokens)
|
def token_infilling(tokens, p):
new_tokens = []
max_infilling_len = round((int((p * len(tokens))) / 2.0))
infilling_len = np.random.randint(1, max_infilling_len)
start_index = np.random.uniform(high=(len(tokens) - infilling_len))
end_index = (start_index + infilling_len)
for (i, t) in enumerat... |
class SyntacticNoisingTransformation(TransformationBase):
def __init__(self, parser_path: str, language: str, noise_ratio=0.15):
self.language = language
if (self.language == 'nl'):
self.tokenizer = nltk.word_tokenize
else:
self.tokenizer = NoTransformation(parser_... |
def get_ancestor_type_chains(node: tree_sitter.Node) -> List[str]:
types = [str(node.type)]
while (node.parent is not None):
node = node.parent
types.append(str(node.type))
return types
|
class TransformationBase():
def __init__(self, parser_path: str, language: str):
if (not os.path.exists(parser_path)):
raise ValueError(f'Language parser does not exist at {parser_path}. Please run `setup.sh` to properly set the environment!')
self.lang_object = Language(parser_path, ... |
class SemanticPreservingTransformation():
def __init__(self, parser_path: str, language: str, transform_functions: Dict[(Callable, int)]=None):
self.language = language
if (transform_functions is not None):
self.transform_functions = transform_functions
else:
self.... |
class VarRenamer(TransformationBase):
def __init__(self, parser_path: str, language: str):
super(VarRenamer, self).__init__(parser_path=parser_path, language=language)
self.language = language
self.processor = processor_function[self.language]
self.tokenizer_function = tokenizer_f... |
def sentence_bleu(references, hypothesis, weights=(0.25, 0.25, 0.25, 0.25), smoothing_function=None, auto_reweigh=False):
'\n Calculate BLEU score (Bilingual Evaluation Understudy) from\n Papineni, Kishore, Salim Roukos, Todd Ward, and Wei-Jing Zhu. 2002.\n "BLEU: a method for automatic evaluation of mac... |
def corpus_bleu(list_of_references, hypotheses, weights=(0.25, 0.25, 0.25, 0.25), smoothing_function=None, auto_reweigh=False):
"\n Calculate a single corpus-level BLEU score (aka. system-level BLEU) for all\n the hypotheses and their respective references.\n Instead of averaging the sentence level BLEU ... |
def modified_precision(references, hypothesis, n):
'\n Calculate modified ngram precision.\n The normal precision method may lead to some wrong translations with\n high-precision, e.g., the translation, in which a word of reference\n repeats several times, has very high precision.\n This function o... |
def closest_ref_length(references, hyp_len):
"\n This function finds the reference that is the closest length to the\n hypothesis. The closest reference length is referred to as *r* variable\n from the brevity penalty formula in Papineni et. al. (2002)\n :param references: A list of reference translat... |
def brevity_penalty(closest_ref_len, hyp_len):
"\n Calculate brevity penalty.\n As the modified n-gram precision still has the problem from the short\n length sentence, brevity penalty is used to modify the overall BLEU\n score according to length.\n An example from the paper. There are three refer... |
class SmoothingFunction():
'\n This is an implementation of the smoothing techniques\n for segment-level BLEU scores that was presented in\n Boxing Chen and Collin Cherry (2014) A Systematic Comparison of\n Smoothing Techniques for Sentence-Level BLEU. In WMT14.\n http://acl2014.org/acl2014/W14-33/... |
def evaluate_per_example(reference, hypothesis, lang, params='0.25,0.25,0.25,0.25'):
(alpha, beta, gamma, theta) = [float(x) for x in params.split(',')]
hypothesis = [hypothesis]
pre_references = [[reference]]
for i in range(len(pre_references)):
assert (len(hypothesis) == len(pre_references[i... |
def get_codebleu(refs, hyp, lang, params='0.25,0.25,0.25,0.25'):
if (not isinstance(refs, list)):
refs = [refs]
(alpha, beta, gamma, theta) = [float(x) for x in params.split(',')]
pre_references = [[x.strip() for x in open(file, 'r', encoding='utf-8').readlines()] for file in refs]
hypothesis ... |
def my_dataflow_match(references, candidates, lang):
LANGUAGE = Language((root_dir + '/parser/languages.so'), lang)
parser = Parser()
parser.set_language(LANGUAGE)
parser = [parser, dfg_function[lang]]
match_count = 0
total_count = 0
candidate_scores = []
for i in range(len(candidates)... |
def calc_dataflow_match(references, candidate, lang):
return corpus_dataflow_match([references], [candidate], lang)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.