text stringlengths 1 93.6k |
|---|
epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=False)
|
for step, batch in enumerate(epoch_iterator):
|
model.eval()
|
batch = tuple(t.to(args.device) for t in batch)
|
with torch.no_grad():
|
inputs = {'input_ids': batch[0],
|
'attention_mask': batch[1],
|
'token_type_ids': batch[2]}
|
input_mask = inputs['attention_mask']
|
outputs = model(**inputs)
|
sequence_output = outputs[0] # batch_size x max_seq_length x hidden_size
|
# pooled_output = outputs[1] # batch_size x hidden_size
|
active_sequence_output = torch.einsum("ijk,ij->ijk",[sequence_output, input_mask])
|
avg_sequence_output = active_sequence_output.sum(1) / input_mask.sum(dim=1).view(input_mask.size(0),1)
|
if len(global_feature_dict) == 0:
|
global_feature_dict["avg_sequence_output"] = avg_sequence_output.sum(dim=0).detach().cpu().numpy()
|
# global_feature_dict["pooled_output"] = pooled_output.sum(dim=0).detach().cpu().numpy()
|
else:
|
global_feature_dict["avg_sequence_output"] += avg_sequence_output.sum(dim=0).detach().cpu().numpy()
|
# global_feature_dict["pooled_output"] += pooled_output.sum(dim=0).detach().cpu().numpy()
|
num_examples += input_mask.size(0)
|
total_num_examples += num_examples
|
# Normalize
|
for key in global_feature_dict:
|
global_feature_dict[key] = global_feature_dict[key] / total_num_examples
|
# Save features
|
for key in global_feature_dict:
|
np.save(os.path.join(args.output_dir, '{}.npy'.format(key)), global_feature_dict[key])
|
tb_writer.close()
|
def load_and_cache_examples(args, task, tokenizer, evaluate=False):
|
processor = processors[task]()
|
output_mode = output_modes[task]
|
# Load data features from cache or dataset file
|
cached_features_file = os.path.join(args.data_dir, 'cached_{}_{}_{}_{}'.format(
|
'dev' if evaluate else 'train',
|
list(filter(None, args.model_name_or_path.split('/'))).pop(),
|
str(args.max_seq_length),
|
str(task)))
|
if os.path.exists(cached_features_file) and not args.overwrite_cache:
|
logger.info("Loading features from cached file %s", cached_features_file)
|
features = torch.load(cached_features_file)
|
else:
|
logger.info("Creating features from dataset file at %s", args.data_dir)
|
label_list = processor.get_labels()
|
examples = processor.get_dev_examples(args.data_dir) if evaluate else processor.get_train_examples(
|
args.data_dir)
|
features = convert_examples_to_features(examples,
|
tokenizer,
|
label_list=label_list,
|
max_length=args.max_seq_length,
|
output_mode=output_mode,
|
pad_on_left=False,
|
pad_token=tokenizer.convert_tokens_to_ids([tokenizer.pad_token])[0],
|
pad_token_segment_id=0,
|
)
|
logger.info("Saving features into cached file %s", cached_features_file)
|
torch.save(features, cached_features_file)
|
# Convert to Tensors and build dataset
|
all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
|
all_attention_mask = torch.tensor([f.attention_mask for f in features], dtype=torch.long)
|
all_token_type_ids = torch.tensor([f.token_type_ids for f in features], dtype=torch.long)
|
if output_mode == "classification":
|
all_labels = torch.tensor([f.label for f in features], dtype=torch.long)
|
elif output_mode == "regression":
|
all_labels = torch.tensor([f.label for f in features], dtype=torch.float)
|
dataset = TensorDataset(all_input_ids, all_attention_mask, all_token_type_ids, all_labels)
|
return dataset
|
def main():
|
parser = argparse.ArgumentParser()
|
## Required parameters
|
parser.add_argument("--data_dir", default=None, type=str, required=True,
|
help="The input data dir. Should contain the .tsv files (or other data files) for the task.")
|
parser.add_argument("--model_type", default=None, type=str, required=True,
|
help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()))
|
parser.add_argument("--model_name_or_path", default=None, type=str, required=True,
|
help="Path to pre-trained model or shortcut name selected in the list: " + ", ".join(
|
ALL_MODELS))
|
parser.add_argument("--task_name", default=None, type=str, required=True,
|
help="The name of the task to train selected in the list: " + ", ".join(processors.keys()))
|
parser.add_argument("--output_dir", default=None, type=str, required=True,
|
help="The output directory where the model predictions and checkpoints will be written.")
|
## Other parameters
|
parser.add_argument("--config_name", default="", type=str,
|
help="Pretrained config name or path if not the same as model_name")
|
parser.add_argument("--tokenizer_name", default="", type=str,
|
help="Pretrained tokenizer name or path if not the same as model_name")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.