Commit 22085000 by Kenton Lee

Initial commit.

parents
*.pyc
*.so
*.jsonlines
logs
conll-2012
*.txt
*.txt.filtered
*.v*_*_conll
This diff is collapsed. Click to expand it.
# End-to-end Neural Coreference Resolution
### Introduction
This repository contains the code for replicating results from
* [End-to-end Neural Coreference Resolution](https://homes.cs.washington.edu/~kentonl/pub/lhlz-emnlp.2017.pdf)
* [Kenton Lee](https://homes.cs.washington.edu/~kentonl), [Luheng He](https://homes.cs.washington.edu/~luheng), [Mike Lewis](https://research.fb.com/people/lewis-mike) and [Luke Zettlemoyer](https://www.cs.washington.edu/people/faculty/lsz)
* In Proceedings of the Conference on Empirical Methods in Natural Language Process (EMNLP), 2017
A demo of the code can be found here: https://kentonl.github.io/e2e-coref.
### Requirements
* Python 2.7
* TensorFlow 1.0.0
* pyhocon (for parsing the configurations)
* NLTK (for sentence splitting and tokenization in the demo)
### Setting Up
* Download pretrained word embeddings and build custom kernels by running `setup_all.sh`.
* There are 3 platform-dependent ways to build custom TensorFlow kernels. Please comment/uncomment the appropriate lines in the script.
* Run one of the following:
* To use the pretrained model only, run `setup_pretrained.sh`
* To train your own models, run `setup_training.sh`
* This assumes access to OntoNotes 5.0. Please edit the `ontonotes_path` variable.
## Training Instructions
* Experiment configurations are found in `experiments.conf`
* Choose an experiment that you would like to run, e.g. `best`
* For a single-machine experiment, run the following two commands:
* `python singleton.py <experiment>`
* `python evaluator.py <experiment>`
* For a distributed multi-gpu experiment, edit the `cluster` property of the configuration and run the following commands:
* `python parameter_server.py <experiment>`
* `python worker.py <experiment>` (for every worker in your cluster)
* `python evaluator.py <experiment>` (on the same machine as your first worker)
* Results are stored in the `logs` directory and can be viewed via TensorBoard.
* For final evaluation of the checkpoint with the maximum dev F1:
* Run `python test_single.py <experiment>` for the single-model evaluation.
* Run `python test_ensemble.py <experiment1> <experiment2> <experiment3>...` for the ensemble-model evaluation.
## Demo Instructions
* For the command-line demo with the pretrained model:
* Run `python demo.py final`
* For the web demo with the pretrained model:
* Run `python demo.py final 8080`
* Edit the URL at the end of `docs/main.js` to point to the demo location, e.g. `localhost:8080`
* Open `docs/index.html` in a web browser.
* To run the demo with other experiments, replace `final` with your configuration name.
## Batched Prediction Instructions
* Create a file where each line is in the following json format (make sure to strip the newlines so each line is well-formed json):
```
{
"clusters": [],
"doc_key": "nw",
"sentences": [["This", "is", "the", "first", "sentence", "."], ["This", "is", "the", "second", "."]],
"speakers": [["spk1", "spk1", "spk1", "spk1", "spk1", "spk1"], ["spk2", "spk2", "spk2", "spk2", "spk2"]]
}
```
* `clusters` should be left empty and is only used for evaluation purposes.
* `doc_key` indicates the genre, which can be one of the following: `"bc", "bn", "mz", "nw", "pt", "tc", "wb"`
* `speakers` indicates the speaker of each word. These can be all empty strings if there is only one known speaker.
* Change the value of `eval_path` in the configuration file to the path to this new file.
* Run `python decoder.py <experiment> <output_file>`, which outputs the original file extended with annotations of the predicted clusters, the top spans, and the head attention scores.
* To visualize the predictions, place the output file in the `viz` directory and run `run.sh`. This will run a web server hosting the files in the `viz` directory. If run locally, it can be reached at `http://localhost:8080?path=<output_file>`
## Other Quirks
* It does not use GPUs by default. Instead, it looks for the `GPU` environment variable, which the code treats as shorthand for `CUDA_VISIBLE_DEVICES`.
* The evaluator should not be run on GPUs, since evaluating full documents does not fit within GPU memory constraints.
* The training runs indefinitely and needs to be terminated manually. The model generally converges at about 400k steps and within 48 hours.
#!/usr/bin/env python
import re
import os
import sys
import json
import tempfile
import subprocess
import operator
import collections
BEGIN_DOCUMENT_REGEX = re.compile(r"#begin document \((.*)\); part (\d+)")
COREF_RESULTS_REGEX = re.compile(r".*Coreference: Recall: \([0-9.]+ / [0-9.]+\) ([0-9.]+)%\tPrecision: \([0-9.]+ / [0-9.]+\) ([0-9.]+)%\tF1: ([0-9.]+)%.*", re.DOTALL)
def get_doc_key(doc_id, part):
return "{}_{}".format(doc_id, int(part))
def output_conll(input_file, output_file, predictions):
prediction_map = {}
for doc_key, clusters in predictions.items():
start_map = collections.defaultdict(list)
end_map = collections.defaultdict(list)
word_map = collections.defaultdict(list)
for cluster_id, mentions in enumerate(clusters):
for start, end in mentions:
if start == end:
word_map[start].append(cluster_id)
else:
start_map[start].append((cluster_id, end))
end_map[end].append((cluster_id, start))
for k,v in start_map.items():
start_map[k] = [cluster_id for cluster_id, end in sorted(v, key=operator.itemgetter(1), reverse=True)]
for k,v in end_map.items():
end_map[k] = [cluster_id for cluster_id, start in sorted(v, key=operator.itemgetter(1), reverse=True)]
prediction_map[doc_key] = (start_map, end_map, word_map)
word_index = 0
for line in input_file.readlines():
row = line.split()
if len(row) == 0:
output_file.write("\n")
elif row[0].startswith("#"):
begin_match = re.match(BEGIN_DOCUMENT_REGEX, line)
if begin_match:
doc_key = get_doc_key(begin_match.group(1), begin_match.group(2))
start_map, end_map, word_map = prediction_map[doc_key]
word_index = 0
output_file.write(line)
output_file.write("\n")
else:
assert get_doc_key(row[0], row[1]) == doc_key
coref_list = []
if word_index in end_map:
for cluster_id in end_map[word_index]:
coref_list.append("{})".format(cluster_id))
if word_index in word_map:
for cluster_id in word_map[word_index]:
coref_list.append("({})".format(cluster_id))
if word_index in start_map:
for cluster_id in start_map[word_index]:
coref_list.append("({}".format(cluster_id))
if len(coref_list) == 0:
row[-1] = "-"
else:
row[-1] = "|".join(coref_list)
output_file.write(" ".join(row))
output_file.write("\n")
word_index += 1
def official_conll_eval(gold_path, predicted_path, metric, official_stdout=False):
cmd = ["conll-2012/scorer/v8.01/scorer.pl", metric, gold_path, predicted_path, "none"]
process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
stdout, stderr = process.communicate()
process.wait()
if stderr is not None:
print stderr
if official_stdout:
print "Official result for {}".format(metric)
print stdout
coref_results_match = re.match(COREF_RESULTS_REGEX, stdout)
recall = float(coref_results_match.group(1))
precision = float(coref_results_match.group(2))
f1 = float(coref_results_match.group(3))
return { "r": recall, "p": precision, "f": f1 }
def evaluate_conll(gold_path, predictions, official_stdout=False):
with tempfile.NamedTemporaryFile(delete=False) as prediction_file:
with open(gold_path, "r") as gold_file:
output_conll(gold_file, prediction_file, predictions)
print("Predicted conll file: {}".format(prediction_file.name))
return { m: official_conll_eval(gold_file.name, prediction_file.name, m, official_stdout) for m in ("muc", "bcub", "ceafe") }
#include <set>
#include <map>
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/op_kernel.h"
using namespace tensorflow;
REGISTER_OP("Spans")
.Attr("max_width: int")
.Input("sentence_indices: int32")
.Output("starts: int32")
.Output("ends: int32");
class SpansOp : public OpKernel {
public:
explicit SpansOp(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("max_width", &_max_width));
}
void Compute(OpKernelContext* context) override {
TTypes<int32>::ConstVec sentence_indices = context->input(0).vec<int32>();
int length = sentence_indices.dimension(0);
std::vector<std::pair<int, int>> spans;
for (int i = 0; i < length; ++i) {
for (int j = i; j < length && (j - i) < _max_width; ++j) {
if (sentence_indices(i) == sentence_indices(j)) {
spans.emplace_back(i, j);
}
}
}
Tensor* starts_tensor = nullptr;
Tensor* ends_tensor = nullptr;
TensorShape outputs_shape({static_cast<int64>(spans.size())});
OP_REQUIRES_OK(context, context->allocate_output(0, outputs_shape, &starts_tensor));
OP_REQUIRES_OK(context, context->allocate_output(1, outputs_shape, &ends_tensor));
TTypes<int32>::Vec starts = starts_tensor->vec<int32>();
TTypes<int32>::Vec ends = ends_tensor->vec<int32>();
for (int i = 0; i < spans.size(); ++i) {
const std::pair<int, int>& span = spans[i];
starts(i) = span.first;
ends(i) = span.second;
}
}
private:
int _max_width;
};
REGISTER_KERNEL_BUILDER(Name("Spans").Device(DEVICE_CPU), SpansOp);
REGISTER_OP("Antecedents")
.Input("mention_starts: int32")
.Input("mention_ends: int32")
.Input("gold_starts: int32")
.Input("gold_ends: int32")
.Input("cluster_ids: int32")
.Input("max_antecedents: int32")
.Output("antecedents: int32")
.Output("antecedent_labels: bool")
.Output("antecedents_len: int32");
class AntecedentsOp : public OpKernel {
public:
explicit AntecedentsOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
TTypes<int32>::ConstVec mention_starts = context->input(0).vec<int32>();
TTypes<int32>::ConstVec mention_ends = context->input(1).vec<int32>();
TTypes<int32>::ConstVec gold_starts = context->input(2).vec<int32>();
TTypes<int32>::ConstVec gold_ends = context->input(3).vec<int32>();
TTypes<int32>::ConstVec cluster_ids = context->input(4).vec<int32>();
CHECK_EQ(mention_starts.dimension(0), mention_ends.dimension(0));
CHECK_EQ(gold_starts.dimension(0), gold_ends.dimension(0));
int num_mentions = mention_starts.dimension(0);
int num_gold = gold_starts.dimension(0);
int max_antecedents = std::min(num_mentions, context->input(5).scalar<int32>()(0));
Tensor* antecedents_tensor = nullptr;
TensorShape antecedents_shape({num_mentions, max_antecedents});
OP_REQUIRES_OK(context, context->allocate_output(0, antecedents_shape, &antecedents_tensor));
TTypes<int32>::Matrix antecedents = antecedents_tensor->matrix<int32>();
Tensor* labels_tensor = nullptr;
TensorShape labels_shape({num_mentions, max_antecedents + 1});
OP_REQUIRES_OK(context, context->allocate_output(1, labels_shape, &labels_tensor));
TTypes<bool>::Matrix labels = labels_tensor->matrix<bool>();
Tensor* antecedents_len_tensor = nullptr;
TensorShape antecedents_len_shape({num_mentions});
OP_REQUIRES_OK(context, context->allocate_output(2, antecedents_len_shape, &antecedents_len_tensor));
TTypes<int32>::Vec antecedents_len = antecedents_len_tensor->vec<int32>();
std::map<std::pair<int, int>, int> mention_indices;
for (int i = 0; i < num_mentions; ++i) {
mention_indices[std::pair<int, int>(mention_starts(i), mention_ends(i))] = i;
}
std::vector<int> mention_cluster_ids(num_mentions, -1);
for (int i = 0; i < num_gold; ++i) {
auto iter = mention_indices.find(std::pair<int, int>(gold_starts(i), gold_ends(i)));
if (iter != mention_indices.end()) {
mention_cluster_ids[iter->second] = cluster_ids(i);
}
}
for (int i = 0; i < num_mentions; ++i) {
int antecedent_count = 0;
bool null_label = true;
for (int j = std::max(0, i - max_antecedents); j < i; ++j) {
if (mention_cluster_ids[i] >= 0 && mention_cluster_ids[i] == mention_cluster_ids[j]) {
labels(i, antecedent_count + 1) = true;
null_label = false;
} else {
labels(i, antecedent_count + 1) = false;
}
antecedents(i, antecedent_count) = j;
++antecedent_count;
}
for (int j = antecedent_count; j < max_antecedents; ++j) {
labels(i, j + 1) = false;
antecedents(i, j) = 0;
}
labels(i, 0) = null_label;
antecedents_len(i) = antecedent_count;
}
}
};
REGISTER_KERNEL_BUILDER(Name("Antecedents").Device(DEVICE_CPU), AntecedentsOp);
REGISTER_OP("ExtractMentions")
.Input("mention_scores: float32")
.Input("candidate_starts: int32")
.Input("candidate_ends: int32")
.Input("num_output_mentions: int32")
.Output("output_mention_indices: int32");
class ExtractMentionsOp : public OpKernel {
public:
explicit ExtractMentionsOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
TTypes<float>::ConstVec mention_scores = context->input(0).vec<float>();
TTypes<int32>::ConstVec candidate_starts = context->input(1).vec<int32>();
TTypes<int32>::ConstVec candidate_ends = context->input(2).vec<int32>();
int num_output_mentions = context->input(3).scalar<int32>()(0);
int num_input_mentions = mention_scores.dimension(0);
Tensor* output_mention_indices_tensor = nullptr;
TensorShape output_mention_indices_shape({num_output_mentions});
OP_REQUIRES_OK(context, context->allocate_output(0, output_mention_indices_shape, &output_mention_indices_tensor));
TTypes<int32>::Vec output_mention_indices = output_mention_indices_tensor->vec<int32>();
std::vector<int> sorted_input_mention_indices(num_input_mentions);
std::iota(sorted_input_mention_indices.begin(), sorted_input_mention_indices.end(), 0);
std::sort(sorted_input_mention_indices.begin(), sorted_input_mention_indices.end(),
[&mention_scores](int i1, int i2) {
return mention_scores(i2) < mention_scores(i1);
});
std::vector<int> top_mention_indices;
int current_mention_index = 0;
while (top_mention_indices.size() < num_output_mentions) {
int i = sorted_input_mention_indices[current_mention_index];
bool any_crossing = false;
for (const int j : top_mention_indices) {
if (is_crossing(candidate_starts, candidate_ends, i, j)) {
any_crossing = true;
break;
}
}
if (!any_crossing) {
top_mention_indices.push_back(i);
}
++current_mention_index;
}
std::sort(top_mention_indices.begin(), top_mention_indices.end(),
[&candidate_starts, &candidate_ends] (int i1, int i2) {
if (candidate_starts(i1) < candidate_starts(i2)) {
return true;
} else if (candidate_starts(i1) > candidate_starts(i2)) {
return false;
} else if (candidate_ends(i1) < candidate_ends(i2)) {
return true;
} else if (candidate_ends(i1) > candidate_ends(i2)) {
return false;
} else {
return i1 < i2;
}
});
for (int i = 0; i < num_output_mentions; ++i) {
output_mention_indices(i) = top_mention_indices[i];
}
}
private:
bool is_crossing(TTypes<int32>::ConstVec &candidate_starts, TTypes<int32>::ConstVec &candidate_ends, int i1, int i2) {
int s1 = candidate_starts(i1);
int s2 = candidate_starts(i2);
int e1 = candidate_ends(i1);
int e2 = candidate_ends(i2);
return (s1 < s2 && s2 <= e1 && e1 < e2) || (s2 < s1 && s1 <= e2 && e2 < e1);
}
};
REGISTER_KERNEL_BUILDER(Name("ExtractMentions").Device(DEVICE_CPU), ExtractMentionsOp);
REGISTER_OP("DistanceBins")
.Input("distances: int32")
.Output("bins: int32");
class DistanceBinsOp : public OpKernel {
public:
explicit DistanceBinsOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
TTypes<int32>::ConstMatrix distances = context->input(0).matrix<int32>();
int d0 = distances.dimension(0);
int d1 = distances.dimension(1);
Tensor* bins_tensor = nullptr;
TensorShape bins_shape({d0, d1});
OP_REQUIRES_OK(context, context->allocate_output(0, bins_shape, &bins_tensor));
TTypes<int32>::Matrix bins = bins_tensor->matrix<int32>();
for (int i = 0; i < d0; ++i) {
for (int j = 0; j < d1; ++j) {
bins(i, j) = get_bin(distances(i, j));
}
}
}
private:
int get_bin(int d) {
if (d <= 0) {
return 0;
} else if (d == 1) {
return 1;
} else if (d == 2) {
return 2;
} else if (d == 3) {
return 3;
} else if (d == 4) {
return 4;
} else if (d <= 7) {
return 5;
} else if (d <= 15) {
return 6;
} else if (d <= 31) {
return 7;
} else if (d <= 63) {
return 8;
} else {
return 9;
}
}
};
REGISTER_KERNEL_BUILDER(Name("DistanceBins").Device(DEVICE_CPU), DistanceBinsOp);
This diff is collapsed. Click to expand it.
import tensorflow as tf
from tensorflow.python import pywrap_tensorflow
coref_op_library = tf.load_op_library("./coref_kernels.so")
spans = coref_op_library.spans
tf.NotDifferentiable("Spans")
antecedents = coref_op_library.antecedents
tf.NotDifferentiable("Antecedents")
extract_mentions = coref_op_library.extract_mentions
tf.NotDifferentiable("ExtractMentions")
distance_bins = coref_op_library.distance_bins
tf.NotDifferentiable("DistanceBins")
#!/usr/bin/env python
import os
import sys
import time
import json
import numpy as np
import tensorflow as tf
import coref_model as cm
import util
if __name__ == "__main__":
util.set_gpus()
name = sys.argv[1]
output_filename = sys.argv[2]
print "Running experiment: {}.".format(name)
config = util.get_config("experiments.conf")[name]
config["log_dir"] = util.mkdirs(os.path.join(config["log_root"], name))
util.print_config(config)
model = cm.CorefModel(config)
model.load_eval_data()
saver = tf.train.Saver()
log_dir = config["log_dir"]
with tf.Session() as session:
checkpoint_path = os.path.join(log_dir, "model.max.ckpt")
saver.restore(session, checkpoint_path)
with open(output_filename, "w") as f:
for example_num, (tensorized_example, example) in enumerate(model.eval_data):
feed_dict = {i:t for i,t in zip(model.input_tensors, tensorized_example)}
_, _, _, mention_starts, mention_ends, antecedents, antecedent_scores, head_scores = session.run(model.predictions + [model.head_scores], feed_dict=feed_dict)
predicted_antecedents = model.get_predicted_antecedents(antecedents, antecedent_scores)
example["predicted_clusters"], _ = model.get_predicted_clusters(mention_starts, mention_ends, predicted_antecedents)
example["top_spans"] = zip((int(i) for i in mention_starts), (int(i) for i in mention_ends))
example["head_scores"] = head_scores.tolist()
f.write(json.dumps(example))
f.write("\n")
if example_num % 100 == 0:
print "Decoded {} examples.".format(example_num + 1)
#!/usr/bin/env python
import os
import sys
import time
import json
import numpy as np
import cgi
import BaseHTTPServer
import ssl
import tensorflow as tf
import coref_model as cm
import util
import nltk
nltk.download("punkt")
from nltk.tokenize import sent_tokenize, word_tokenize
def create_example(text):
raw_sentences = sent_tokenize(text)
sentences = [word_tokenize(s) for s in raw_sentences]
speakers = [["" for _ in sentence] for sentence in sentences]
return {
"doc_key": "nw",
"clusters": [],
"sentences": sentences,
"speakers": speakers,
}
def print_predictions(example):
words = util.flatten(example["sentences"])
for cluster in example["predicted_clusters"]:
print(u"Predicted cluster: {}".format([" ".join(words[m[0]:m[1]+1]) for m in cluster]))
def make_predictions(text, model):
example = create_example(text)
tensorized_example = model.tensorize_example(example, is_training=False)
feed_dict = {i:t for i,t in zip(model.input_tensors, tensorized_example)}
_, _, _, mention_starts, mention_ends, antecedents, antecedent_scores, head_scores = session.run(model.predictions + [model.head_scores], feed_dict=feed_dict)
predicted_antecedents = model.get_predicted_antecedents(antecedents, antecedent_scores)
example["predicted_clusters"], _ = model.get_predicted_clusters(mention_starts, mention_ends, predicted_antecedents)
example["top_spans"] = zip((int(i) for i in mention_starts), (int(i) for i in mention_ends))
example["head_scores"] = head_scores.tolist()
return example
if __name__ == "__main__":
util.set_gpus()
name = sys.argv[1]
if len(sys.argv) > 2:
port = int(sys.argv[2])
else:
port = None
if len(sys.argv) > 3:
# For https. See https://certbot.eff.org
keyfile = sys.argv[3]
certfile = sys.argv[4]
else:
keyfile = None
certfile = None
print "Running experiment: {}.".format(name)
config = util.get_config("experiments.conf")[name]
config["log_dir"] = util.mkdirs(os.path.join(config["log_root"], name))
util.print_config(config)
model = cm.CorefModel(config)
saver = tf.train.Saver()
log_dir = config["log_dir"]
with tf.Session() as session:
checkpoint_path = os.path.join(log_dir, "model.max.ckpt")
saver.restore(session, checkpoint_path)
if port is not None:
class CorefRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
idx = self.path.find("?")
if idx >= 0:
args = cgi.parse_qs(self.path[idx+1:])
if "text" in args:
text_arg = args["text"]
if len(text_arg) == 1 and len(text_arg[0]) <= 10000:
text = text_arg[0].decode("utf-8")
print(u"Document text: {}".format(text))
example = make_predictions(text, model)
print_predictions(example)
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write("jsonCallback({})".format(json.dumps(example)))
return
self.send_response(400)
self.send_header("Content-Type", "application/json")
self.end_headers()
server = BaseHTTPServer.HTTPServer(("", port), CorefRequestHandler)
if keyfile is not None:
server.socket = ssl.wrap_socket(server.socket, keyfile=keyfile, certfile=certfile, server_side=True)
print("Running server at port {}".format(port))
server.serve_forever()
else:
while True:
text = raw_input("Document text: ")
print_predictions(make_predictions(text, model))
<!DOCTYPE HTML>
<html>
<head>
<title>End-to-End Neural Coreference Resolution Demo</title>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="main.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>End-to-end Neural Coreference Resolution</h2>
<p>This is the demo for the coreference resolution system described in: </p>
<div class="well text-left" style="display:inline-block">
<b><a href="https://homes.cs.washington.edu/~kentonl/pub/lhlz-emnlp.2017.pdf">End-to-end Neural Coreference Resolution</a></b>
<br>
<a href="https://homes.cs.washington.edu/~kentonl">Kenton Lee</a>,
<a href="https://homes.cs.washington.edu/~luheng">Luheng He</a>,
<a href="https://research.fb.com/people/lewis-mike">Mike Lewis</a> and
<a href="https://www.cs.washington.edu/people/faculty/lsz">Luke Zettlemoyer</a>
<br>
<em>In Proceedings of the Conference on Empirical Methods in Natural Language Process (EMNLP), 2017.</em>
</div>
<p>Submit an input document below. A simple example is provided.</p>
<p>On the right side, the highest-scoring spans are shown. On the left side, the predicted coreference cluster (mentions of the same entity) are shown.</p>
<p>Hover over the mentions on either side to highlight their location in the document and render the attention weights of the words.</p>
<p>The code is available <a href="https://github.com/kentonl/e2e-coref">here</a>.</p>
</div>
</div>
<form role="form" id="input-form">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<h4>Input Document</h4>
<textarea id="input-doc" class="form-control" rows="5" required>Unlike many elite athletes, Federer had a long-term plan from an early age to preserve his body, paying close attention to fitness with the trainer Pierre Paganini. Unlike many young tennis stars, Federer avoided overplaying, managing his schedule sagaciously.</textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button type="submit" id="form-submit" class="btn btn-primary">Submit</button>
&nbsp;&nbsp;&nbsp;&nbsp;
<input id="show-attention" type="checkbox" class="custom-control-input">
<span class="custom-control-description">Render attention weights on hover</span>
</div>
</div>
</form>
<br>
<br>
<div class="row">
<div class="col-md-3">
<h4 id="predicted-clusters-title"></h4>
<ul id="predicted-clusters" class="list-group"></ul>
</div>
<div class="col-md-6">
<h4 id="text-title"></h4>
<p id="text" class="lead"></p>
</div>
<div class="col-md-3">
<h4 id="top-spans-title"></h4>
<ul id="top-spans" class="list-group"></ul>
</div>
</div>
</body>
</html>
function logsumexp(x) {
var a = Math.max.apply(null, x);
var total = 0.0;
for (var i = 0; i < x.length; i++) {
total += Math.exp(x[i] - a);
}
return Math.log(total) + a;
}
function set_mention_callbacks(hover_callbacks, unhover_callbacks, head_scores, mention_start, mention_end) {
var scores = [];
for (var token = mention_start; token <= mention_end; token++) {
scores.push(head_scores[token]);
}
var log_norm = logsumexp(scores);
hover_callbacks.add(function() {
var show_attention = $("#show-attention").is(":checked");
for (var token = mention_start; token <= mention_end; token++) {
var token_span = $("#t" + token);
token_span.css("font-weight", "normal");
if (show_attention) {
var p = Math.exp(head_scores[token] - log_norm);
var r = Math.round(-36 * p + 255);
var g = Math.round(-187 * p + 255);
var b = Math.round(-200 * p + 255);
var c = p > 0.75 ? "lightgray" : "black";
token_span
.css("color", c)
.css("background-color", "rgb(" + r + "," + g + "," + b + ")");
}
}
$("#lrb" + mention_start).text("(");
$("#rrb" + mention_end).text(")");
});
unhover_callbacks.add(function() {
for (var token = mention_start; token <= mention_end; token++) {
$("#t" + token)
.css("color", "black")
.css("font-weight", "300")
.css("background-color", "white");
}
$("#lrb" + mention_start).text("");
$("#rrb" + mention_end).text("");
});
}
function render_predicted_clusters(clusters_div, clusters_data, text, head_scores) {
clusters_div.empty();
$.each(clusters_data, function(i, cluster) {
var item = $("<li>")
.addClass("list-group-item")
.appendTo(clusters_div);
var hover_callbacks = $.Callbacks();
var unhover_callbacks = $.Callbacks();
$.each(cluster, function(j, mention) {
if (j != 0) {
$("<span>").html(", ").appendTo(item);
}
var mention_start = mention[0];
var mention_end = mention[1];
set_mention_callbacks(hover_callbacks, unhover_callbacks, head_scores, mention_start, mention_end);
var mention_text = text.slice(mention_start, mention_end + 1).join(" ");
$("<span>")
.html(mention_text)
.appendTo(item);
});
item.hover(hover_callbacks.fire, unhover_callbacks.fire);
});
}
function render_top_spans(top_spans_div, top_spans_data, text, head_scores) {
top_spans_div.empty();
$.each(top_spans_data, function(i, mention) {
var item = $("<li>")
.addClass("list-group-item")
.appendTo(top_spans_div);
var hover_callbacks = $.Callbacks();
var unhover_callbacks = $.Callbacks();
var mention_start = mention[0];
var mention_end = mention[1];
set_mention_callbacks(hover_callbacks, unhover_callbacks, head_scores, mention_start, mention_end);
var mention_text = text.slice(mention_start, mention_end + 1).join(" ");
$("<span>")
.html(mention_text)
.appendTo(item);
item.hover(hover_callbacks.fire, unhover_callbacks.fire);
});
}
function jsonCallback(data) {
var text_div = $("#text");
text_div.empty();
var text = [].concat.apply([], data.sentences);
$.each(text, function(i, token) {
var lrb = $("<span>")
.attr("id", "lrb" + i)
.appendTo(text_div);
var text_span = $("<span>")
.attr("id", "t" + i)
.html(token)
.appendTo(text_div);
var rrb = $("<span>")
.attr("id", "rrb" + i)
.appendTo(text_div);
$("<span>").text(" ").appendTo(text_div);
});
render_predicted_clusters($("#predicted-clusters"), data.predicted_clusters, text, data.head_scores);
render_top_spans($("#top-spans"), data.top_spans, text, data.head_scores);
$("#top-spans-title").text("Top Spans");
$("#text-title").text("Document");
$("#predicted-clusters-title").text("Predicted Clusters");
}
$(document).ready(function() {
$("#input-form").submit(function(event){
event.preventDefault();
var text = $("#input-doc").val().replace("’", "'");
$.getJSON("https://appositive.cs.washington.edu:8080?callback=?", {"text": text});
});
});
#!/usr/bin/env python
import os
import re
import sys
sys.path.append(os.getcwd())
import time
import random
import shutil
import numpy as np
import tensorflow as tf
import coref_model as cm
import util
def copy_checkpoint(source, target):
for ext in (".index", ".data-00000-of-00001"):
shutil.copyfile(source + ext, target + ext)
if __name__ == "__main__":
util.set_gpus()
if len(sys.argv) > 1:
name = sys.argv[1]
print "Running experiment: {} (from command-line argument).".format(name)
else:
name = os.environ["EXP"]
print "Running experiment: {} (from environment variable).".format(name)
config = util.get_config("experiments.conf")[name]
config["log_dir"] = util.mkdirs(os.path.join(config["log_root"], name))
util.print_config(config)
model = cm.CorefModel(config)
saver = tf.train.Saver()
log_dir = config["log_dir"]
writer = tf.summary.FileWriter(log_dir, flush_secs=20)
evaluated_checkpoints = set()
max_f1 = 0
checkpoint_pattern = re.compile(".*model.ckpt-([0-9]*)\Z")
with tf.Session() as session:
while True:
ckpt = tf.train.get_checkpoint_state(log_dir)
if ckpt and ckpt.model_checkpoint_path and ckpt.model_checkpoint_path not in evaluated_checkpoints:
print "Evaluating {}".format(ckpt.model_checkpoint_path)
# Move it to a temporary location to avoid being deleted by the training supervisor.
tmp_checkpoint_path = os.path.join(log_dir, "model.tmp.ckpt")
copy_checkpoint(ckpt.model_checkpoint_path, tmp_checkpoint_path)
global_step = int(checkpoint_pattern.match(ckpt.model_checkpoint_path).group(1))
saver.restore(session, ckpt.model_checkpoint_path)
eval_summary, f1 = model.evaluate(session)
if f1 > max_f1:
max_f1 = f1
copy_checkpoint(tmp_checkpoint_path, os.path.join(log_dir, "model.max.ckpt"))
print "Current max F1: {:.2f}".format(max_f1)
writer.add_summary(eval_summary, global_step)
print "Evaluation written to {} at step {}".format(log_dir, global_step)
evaluated_checkpoints.add(ckpt.model_checkpoint_path)
# Word embeddings.
glove_300d {
path = glove.840B.300d.txt
size = 300
format = txt
lowercase = false
}
glove_300d_filtered {
path = glove.840B.300d.txt.filtered
size = 300
format = txt
lowercase = false
}
turian_50d {
path = turian.50d.txt
size = 50
format = txt
lowercase = false
}
# Compute clusters.
nlp {
addresses {
ps = [nlp2:2222]
worker = [n01:2222, n02:2222, n03:2222, n04:2222, n05:2222, n07:2222, n08:2222, n09:2222, n10:2222, n11:2222, n12:2222, n13:2222, n14:2222, n15:2222, n16:2222]
}
gpus = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
}
appositive {
addresses {
ps = [localhost:2222]
worker = [localhost:2223, localhost:2224]
}
gpus = [0, 1]
}
# Main configuration.
best {
# Computation limits.
max_antecedents = 250
max_training_sentences = 50
mention_ratio = 0.4
# Model hyperparameters.
filter_widths = [3, 4, 5]
filter_size = 50
char_embedding_size = 8
char_vocab_path = "char_vocab.english.txt"
embeddings = [${glove_300d_filtered}, ${turian_50d}]
lstm_size = 200
ffnn_size = 150
ffnn_depth = 2
feature_size = 20
max_mention_width = 10
use_metadata = true
use_features = true
model_heads = true
# Learning hyperparameters.
max_gradient_norm = 5.0
lexical_dropout_rate = 0.5
dropout_rate = 0.2
optimizer = adam
learning_rate = 0.001
decay_rate = 0.999
decay_frequency = 100
# Other.
train_path = train.english.jsonlines
eval_path = dev.english.jsonlines
conll_eval_path = dev.english.v4_auto_conll
genres = [bc, bn, mz, nw, pt, tc, wb]
eval_frequency = 1000
report_frequency = 100
log_root = logs
cluster = ${appositive}
}
# Multiple full models for ensembling.
best0 = ${best}
best1 = ${best}
best2 = ${best}
best3 = ${best}
best4 = ${best}
# Ablations.
glove = ${best} {
embeddings = [${glove_300d_filtered}]
}
turian = ${best} {
embeddings = [${turian_50d}]
}
nochar = ${best} {
char_embedding_size = -1
}
nometa = ${best} {
use_metadata = false
}
noheads = ${best} {
model_heads = false
}
nofeatures = ${best} {
use_features = false
}
# For evaluation. Do not use for training (i.e. only for decoder.py, ensembler.py, visualize.py and demo.py). Rename `best0` directory to `final`.
final = ${best} {
embeddings = [${glove_300d}, ${turian_50d}]
eval_path = test.english.jsonlines
conll_eval_path = test.english.v4_gold_conll
}
#!/usr/bin/env python
import sys
import json
if __name__ == "__main__":
if len(sys.argv) < 3:
sys.exit("Usage: {} <embeddings> <json1> <json2> ...".format(sys.argv[0]))
words_to_keep = set()
for json_filename in sys.argv[2:]:
with open(json_filename) as json_file:
for line in json_file.readlines():
for sentence in json.loads(line)["sentences"]:
words_to_keep.update(sentence)
print "Found {} words in {} dataset(s).".format(len(words_to_keep), len(sys.argv) - 2)
total_lines = 0
kept_lines = 0
out_filename = "{}.filtered".format(sys.argv[1])
with open(sys.argv[1]) as in_file:
with open(out_filename, "w") as out_file:
for line in in_file.readlines():
total_lines += 1
word = line.split()[0]
if word in words_to_keep:
kept_lines += 1
out_file.write(line)
print "Kept {} out of {} lines.".format(kept_lines, total_lines)
print "Wrote result to {}.".format(out_filename)
#!/usr/bin/env python
import sys
import json
def get_char_vocab(input_filenames, output_filename):
vocab = set()
for filename in input_filenames:
with open(filename) as f:
for line in f.readlines():
for sentence in json.loads(line)["sentences"]:
for word in sentence:
vocab.update(word)
vocab = sorted(list(vocab))
with open(output_filename, "w") as f:
for char in vocab:
f.write(u"{}\n".format(char).encode("utf8"))
print("Wrote {} characters to {}".format(len(vocab), output_filename))
def get_char_vocab_language(language):
get_char_vocab(["{}.{}.jsonlines".format(partition, language) for partition in ("train", "dev", "test")], "char_vocab.{}.txt".format(language))
get_char_vocab_language("english")
import numpy as np
from collections import Counter
from sklearn.utils.linear_assignment_ import linear_assignment
def f1(p_num, p_den, r_num, r_den, beta=1):
p = 0 if p_den == 0 else p_num / float(p_den)
r = 0 if r_den == 0 else r_num / float(r_den)
return 0 if p + r == 0 else (1 + beta * beta) * p * r / (beta * beta * p + r)
class CorefEvaluator(object):
def __init__(self):
self.evaluators = [Evaluator(m) for m in (muc, b_cubed, ceafe)]
def update(self, predicted, gold, mention_to_predicted, mention_to_gold):
for e in self.evaluators:
e.update(predicted, gold, mention_to_predicted, mention_to_gold)
def get_f1(self):
return sum(e.get_f1() for e in self.evaluators) / len(self.evaluators)
def get_recall(self):
return sum(e.get_recall() for e in self.evaluators) / len(self.evaluators)
def get_precision(self):
return sum(e.get_precision() for e in self.evaluators) / len(self.evaluators)
def get_prf(self):
return self.get_precision(), self.get_recall(), self.get_f1()
class Evaluator(object):
def __init__(self, metric, beta=1):
self.p_num = 0
self.p_den = 0
self.r_num = 0
self.r_den = 0
self.metric = metric
self.beta = beta
def update(self, predicted, gold, mention_to_predicted, mention_to_gold):
if self.metric == ceafe:
pn, pd, rn, rd = self.metric(predicted, gold)
else:
pn, pd = self.metric(predicted, mention_to_gold)
rn, rd = self.metric(gold, mention_to_predicted)
self.p_num += pn
self.p_den += pd
self.r_num += rn
self.r_den += rd
def get_f1(self):
return f1(self.p_num, self.p_den, self.r_num, self.r_den, beta=self.beta)
def get_recall(self):
return 0 if self.r_num == 0 else self.r_num / float(self.r_den)
def get_precision(self):
return 0 if self.p_num == 0 else self.p_num / float(self.p_den)
def get_prf(self):
return self.get_precision(), self.get_recall(), self.get_f1()
def get_counts(self):
return self.p_num, self.p_den, self.r_num, self.r_den
def evaluate_documents(documents, metric, beta=1):
evaluator = Evaluator(metric, beta=beta)
for document in documents:
evaluator.update(document)
return evaluator.get_precision(), evaluator.get_recall(), evaluator.get_f1()
def b_cubed(clusters, mention_to_gold):
num, dem = 0, 0
for c in clusters:
if len(c) == 1:
continue
gold_counts = Counter()
correct = 0
for m in c:
if m in mention_to_gold:
gold_counts[tuple(mention_to_gold[m])] += 1
for c2, count in gold_counts.iteritems():
if len(c2) != 1:
correct += count * count
num += correct / float(len(c))
dem += len(c)
return num, dem
def muc(clusters, mention_to_gold):
tp, p = 0, 0
for c in clusters:
p += len(c) - 1
tp += len(c)
linked = set()
for m in c:
if m in mention_to_gold:
linked.add(mention_to_gold[m])
else:
tp -= 1
tp -= len(linked)
return tp, p
def phi4(c1, c2):
return 2 * len([m for m in c1 if m in c2]) / float(len(c1) + len(c2))
def ceafe(clusters, gold_clusters):
clusters = [c for c in clusters if len(c) != 1]
scores = np.zeros((len(gold_clusters), len(clusters)))
for i in range(len(gold_clusters)):
for j in range(len(clusters)):
scores[i, j] = phi4(gold_clusters[i], clusters[j])
matching = linear_assignment(-scores)
similarity = sum(scores[matching[:, 0], matching[:, 1]])
return similarity, len(clusters), similarity, len(gold_clusters)
def lea(clusters, mention_to_gold):
num, dem = 0, 0
for c in clusters:
if len(c) == 1:
continue
common_links = 0
all_links = len(c) * (len(c) - 1) / 2.0
for i, m in enumerate(c):
if m in mention_to_gold:
for m2 in c[i + 1:]:
if m2 in mention_to_gold and mention_to_gold[m] == mention_to_gold[m2]:
common_links += 1
num += len(c) * common_links / float(all_links)
dem += len(c)
return num, dem
#!/usr/bin/env python
import re
import os
import sys
import json
import tempfile
import subprocess
import collections
import util
import conll
class DocumentState(object):
def __init__(self):
self.doc_key = None
self.text = []
self.text_speakers = []
self.speakers = []
self.sentences = []
self.clusters = collections.defaultdict(list)
self.stacks = collections.defaultdict(list)
def assert_empty(self):
assert self.doc_key is None
assert len(self.text) == 0
assert len(self.text_speakers) == 0
assert len(self.sentences) == 0
assert len(self.speakers) == 0
assert len(self.clusters) == 0
assert len(self.stacks) == 0
def assert_finalizable(self):
assert self.doc_key is not None
assert len(self.text) == 0
assert len(self.text_speakers) == 0
assert len(self.sentences) > 0
assert len(self.speakers) > 0
assert all(len(s) == 0 for s in self.stacks.values())
def finalize(self):
merged_clusters = []
for c1 in self.clusters.values():
existing = None
for m in c1:
for c2 in merged_clusters:
if m in c2:
existing = c2
break
if existing is not None:
break
if existing is not None:
print("Merging clusters (shouldn't happen very often.)")
existing.update(c1)
else:
merged_clusters.append(set(c1))
merged_clusters = [list(c) for c in merged_clusters]
all_mentions = util.flatten(merged_clusters)
assert len(all_mentions) == len(set(all_mentions))
return {
"doc_key": self.doc_key,
"sentences": self.sentences,
"speakers": self.speakers,
"clusters": merged_clusters
}
def normalize_word(word):
if word == "/." or word == "/?":
return word[1:]
else:
return word
def handle_line(line, document_state):
begin_document_match = re.match(conll.BEGIN_DOCUMENT_REGEX, line)
if begin_document_match:
document_state.assert_empty()
document_state.doc_key = conll.get_doc_key(begin_document_match.group(1), begin_document_match.group(2))
return None
elif line.startswith("#end document"):
document_state.assert_finalizable()
return document_state.finalize()
else:
row = line.split()
if len(row) == 0:
document_state.sentences.append(tuple(document_state.text))
del document_state.text[:]
document_state.speakers.append(tuple(document_state.text_speakers))
del document_state.text_speakers[:]
return None
assert len(row) >= 12
word = normalize_word(row[3])
coref = row[-1]
doc_key = conll.get_doc_key(row[0], row[1])
speaker = row[9]
word_index = len(document_state.text) + sum(len(s) for s in document_state.sentences)
document_state.text.append(word)
document_state.text_speakers.append(speaker)
if coref == "-":
return None
for segment in coref.split("|"):
if segment[0] == "(":
if segment[-1] == ")":
cluster_id = int(segment[1:-1])
document_state.clusters[cluster_id].append((word_index, word_index))
else:
cluster_id = int(segment[1:])
document_state.stacks[cluster_id].append(word_index)
else:
cluster_id = int(segment[:-1])
start = document_state.stacks[cluster_id].pop()
document_state.clusters[cluster_id].append((start, word_index))
return None
def minimize_partition(name, language, extension):
input_path = "{}.{}.{}".format(name, language, extension)
output_path = "{}.{}.jsonlines".format(name, language)
count = 0
print "Minimizing {}".format(input_path)
with open(input_path, "r") as input_file:
with open(output_path, "w") as output_file:
document_state = DocumentState()
for line in input_file.readlines():
document = handle_line(line, document_state)
if document is not None:
output_file.write(json.dumps(document))
output_file.write("\n")
count += 1
document_state = DocumentState()
print "Wrote {} documents to {}".format(count, output_path)
def minimize_language(language):
minimize_partition("dev", language, "v4_auto_conll")
minimize_partition("train", language, "v4_auto_conll")
minimize_partition("test", language, "v4_gold_conll")
if __name__ == "__main__":
minimize_language("english")
#!/usr/bin/env python
import os
import sys
sys.path.append(os.getcwd())
import tensorflow as tf
import util
if __name__ == "__main__":
util.set_gpus()
cluster_config = util.get_config("experiments.conf")[os.environ["EXP"]]["cluster"]
cluster = tf.train.ClusterSpec(cluster_config["addresses"])
server = tf.train.Server(cluster, job_name="ps", task_index=0)
server.join()
#!/bin/bash
# Download pretrained embeddings.
curl -O http://appositive.cs.washington.edu/resources/turian.50d.txt
curl -O https://nlp.stanford.edu/data/glove.840B.300d.zip
unzip glove.840B.300d.zip
rm glove.840B.300d.zip
# Build custom kernels.
TF_INC=$(python -c 'import tensorflow as tf; print(tf.sysconfig.get_include())')
# Linux (pip)
#g++ -std=c++11 -shared coref_kernels.cc -o coref_kernels.so -I $TF_INC -fPIC -D_GLIBCXX_USE_CXX11_ABI=0
# Linux (build from source)
g++ -std=c++11 -shared coref_kernels.cc -o coref_kernels.so -I $TF_INC -fPIC
# Mac
#g++ -std=c++11 -shared coref_kernels.cc -o coref_kernels.so -I $TF_INC -fPIC -D_GLIBCXX_USE_CXX11_ABI=0 -undefined dynamic_lookup
#!/bin/bash
curl -O http://appositive.cs.washington.edu/resources/coref/char_vocab.english.txt
curl -O http://appositive.cs.washington.edu/resources/coref/final.tgz
mkdir -p logs
tar -xzvf final.tgz -C logs
rm final.tgz
#!/bin/bash
dlx() {
wget $1/$2
tar -xvzf $2
rm $2
}
conll_url=http://conll.cemantix.org/2012/download
dlx $conll_url conll-2012-train.v4.tar.gz
dlx $conll_url conll-2012-development.v4.tar.gz
dlx $conll_url/test conll-2012-test-key.tar.gz
dlx $conll_url/test conll-2012-test-official.v9.tar.gz
dlx $conll_url conll-2012-scripts.v3.tar.gz
dlx http://conll.cemantix.org/download reference-coreference-scorers.v8.01.tar.gz
mv reference-coreference-scorers conll-2012/scorer
ontonotes_path=/projects/WebWare6/ontonotes-release-5.0
bash conll-2012/v3/scripts/skeleton2conll.sh -D $ontonotes_path/data/files/data conll-2012
function compile_partition() {
rm -f $2.$5.$3$4
cat conll-2012/$3/data/$1/data/$5/annotations/*/*/*/*.$3$4 >> $2.$5.$3$4
}
function compile_language() {
compile_partition development dev v4 _auto_conll $1
compile_partition train train v4 _auto_conll $1
compile_partition test test v4 _gold_conll $1
}
compile_language english
python minimize.py
python get_char_vocab.py
python filter_embeddings.py glove.840B.300d.txt train.english.jsonlines dev.english.jsonlines test.english.jsonlines
#!/usr/bin/env python
import os
import sys
sys.path.append(os.getcwd())
import json
import time
import random
import numpy as np
import tensorflow as tf
import coref_model as cm
import util
if __name__ == "__main__":
if len(sys.argv) > 1:
name = sys.argv[1]
else:
name = os.environ["EXP"]
config = util.get_config("experiments.conf")[name]
report_frequency = config["report_frequency"]
config["log_dir"] = util.mkdirs(os.path.join(config["log_root"], name))
util.print_config(config)
if "GPU" in os.environ:
util.set_gpus(int(os.environ["GPU"]))
else:
util.set_gpus()
model = cm.CorefModel(config)
saver = tf.train.Saver()
init_op = tf.global_variables_initializer()
log_dir = config["log_dir"]
# Create a "supervisor", which oversees the training process.
sv = tf.train.Supervisor(logdir=log_dir,
init_op=init_op,
saver=saver,
global_step=model.global_step,
save_model_secs=120)
# The supervisor takes care of session initialization, restoring from
# a checkpoint, and closing when done or an error occurs.
with sv.managed_session() as session:
model.start_enqueue_thread(session)
accumulated_loss = 0.0
initial_time = time.time()
while not sv.should_stop():
tf_loss, tf_global_step, _ = session.run([model.loss, model.global_step, model.train_op])
accumulated_loss += tf_loss
if tf_global_step % report_frequency == 0:
total_time = time.time() - initial_time
steps_per_second = tf_global_step / total_time
average_loss = accumulated_loss / report_frequency
print "[{}] loss={:.2f}, steps/s={:.2f}".format(tf_global_step, tf_loss, steps_per_second)
accumulated_loss = 0.0
# Ask for all the services to stop.
sv.stop()
#!/usr/bin/env python
import os
import sys
sys.path.append(os.getcwd())
import collections
import operator
import numpy as np
import tensorflow as tf
import coref_model as cm
import util
import conll
import metrics
if __name__ == "__main__":
if "GPU" in os.environ:
util.set_gpus(int(os.environ["GPU"]))
else:
util.set_gpus()
names = sys.argv[1:]
print "Ensembling models from {}.".format(names)
configs = util.get_config("experiments.conf")
main_config = configs[names[0]]
model = cm.CorefModel(main_config)
model.load_eval_data()
saver = tf.train.Saver()
with tf.Session() as session:
all_mention_scores = collections.defaultdict(list)
for name in names:
config = configs[name]
log_dir = os.path.join(config["log_root"], name)
checkpoint_path = os.path.join(log_dir, "model.max.ckpt")
print "Computing mention scores for {}".format(checkpoint_path)
saver.restore(session, checkpoint_path)
for example_num, (tensorized_example, example) in enumerate(model.eval_data):
feed_dict = {i:t for i,t in zip(model.input_tensors, tensorized_example)}
mention_scores = session.run(model.predictions[2], feed_dict=feed_dict)
all_mention_scores[example["doc_key"]].append(mention_scores)
if example_num % 10 == 0:
print "Computed {}/{} examples.".format(example_num + 1, len(model.eval_data))
mean_mention_scores = { doc_key : np.mean(s, 0) for doc_key, s in all_mention_scores.items() }
all_antecedent_scores = collections.defaultdict(list)
mention_start_dict = {}
mention_end_dict = {}
antecedents_dict = {}
for name in names:
config = configs[name]
log_dir = os.path.join(config["log_root"], name)
checkpoint_path = os.path.join(log_dir, "model.max.ckpt")
print "Computing antecedent scores for {}".format(checkpoint_path)
saver.restore(session, checkpoint_path)
for example_num, (tensorized_example, example) in enumerate(model.eval_data):
doc_key = example["doc_key"]
feed_dict = {i:t for i,t in zip(model.input_tensors, tensorized_example)}
feed_dict[model.predictions[2]] = mean_mention_scores[doc_key]
mention_starts, mention_ends, antecedents, antecedent_scores = session.run(model.predictions[3:7], feed_dict=feed_dict)
if doc_key in mention_start_dict:
assert (mention_starts == mention_start_dict[doc_key]).all()
assert (mention_ends == mention_end_dict[doc_key]).all()
assert (antecedents == antecedents_dict[doc_key]).all()
else:
mention_start_dict[doc_key] = mention_starts
mention_end_dict[doc_key] = mention_ends
antecedents_dict[doc_key] = antecedents
all_antecedent_scores[doc_key].append(antecedent_scores)
if example_num % 10 == 0:
print "Computed {}/{} examples.".format(example_num + 1, len(model.eval_data))
mean_antecedent_scores = { doc_key : np.mean(s, 0) for doc_key, s in all_antecedent_scores.items() }
merged_predictions = {}
coref_evaluator = metrics.CorefEvaluator()
for example_num, (tensorized_example, example) in enumerate(model.eval_data):
doc_key = example["doc_key"]
mention_starts = mention_start_dict[doc_key]
mention_ends = mention_end_dict[doc_key]
antecedents = antecedents_dict[doc_key]
antecedent_scores = mean_antecedent_scores[doc_key]
predicted_antecedents = []
for i, index in enumerate(np.argmax(antecedent_scores, axis=1) - 1):
if index < 0:
predicted_antecedents.append(-1)
else:
predicted_antecedents.append(antecedents[i, index])
merged_predictions[doc_key] = model.evaluate_coref(mention_starts, mention_ends, predicted_antecedents, example["clusters"], coref_evaluator)
conll_results = conll.evaluate_conll(main_config["conll_eval_path"], merged_predictions, official_stdout=True)
average_f = sum(results["f"] for results in conll_results.values()) / len(conll_results)
average_r = sum(results["r"] for results in conll_results.values()) / len(conll_results)
average_p = sum(results["p"] for results in conll_results.values()) / len(conll_results)
print "Merged average F1 (conll): {:.2f}%".format(average_f)
print "Merged average Recall (conll): {:.2f}%".format(average_r)
print "Merged average Precision (conll): {:.2f}%".format(average_p)
#!/usr/bin/env python
import os
import re
import sys
sys.path.append(os.getcwd())
import time
import random
import numpy as np
import tensorflow as tf
import coref_model as cm
import util
if __name__ == "__main__":
if "GPU" in os.environ:
util.set_gpus(int(os.environ["GPU"]))
else:
util.set_gpus()
if len(sys.argv) > 1:
name = sys.argv[1]
print "Running experiment: {} (from command-line argument).".format(name)
else:
name = os.environ["EXP"]
print "Running experiment: {} (from environment variable).".format(name)
config = util.get_config("experiments.conf")[name]
config["log_dir"] = util.mkdirs(os.path.join(config["log_root"], name))
util.print_config(config)
model = cm.CorefModel(config)
saver = tf.train.Saver()
log_dir = config["log_dir"]
with tf.Session() as session:
checkpoint_path = os.path.join(log_dir, "model.max.ckpt")
print "Evaluating {}".format(checkpoint_path)
saver.restore(session, checkpoint_path)
model.evaluate(session, official_stdout=True)
import os
import errno
import collections
import json
import numpy as np
import tensorflow as tf
import pyhocon
def make_summary(value_dict):
return tf.Summary(value=[tf.Summary.Value(tag=k, simple_value=v) for k,v in value_dict.items()])
def flatten(l):
return [item for sublist in l for item in sublist]
def get_config(filename):
return pyhocon.ConfigFactory.parse_file(filename)
def print_config(config):
print pyhocon.HOCONConverter.convert(config, "hocon")
def set_gpus(*gpus):
os.environ["CUDA_VISIBLE_DEVICES"] = ",".join(str(g) for g in gpus)
print "Setting CUDA_VISIBLE_DEVICES to: {}".format(os.environ["CUDA_VISIBLE_DEVICES"])
def mkdirs(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
return path
def load_char_dict(char_vocab_path):
vocab = [u"<unk>"]
with open(char_vocab_path) as f:
vocab.extend(unicode(c, "utf-8").strip() for c in f.readlines())
char_dict = collections.defaultdict(int)
char_dict.update({c:i for i,c in enumerate(vocab)})
return char_dict
def load_embedding_dict(embedding_path, embedding_size, embedding_format):
print("Loading word embeddings from {}...".format(embedding_path))
default_embedding = np.zeros(embedding_size)
embedding_dict = collections.defaultdict(lambda:default_embedding)
skip_first = embedding_format == "vec"
with open(embedding_path) as f:
for i, line in enumerate(f.readlines()):
if skip_first and i == 0:
continue
splits = line.split()
assert len(splits) == embedding_size + 1
word = splits[0]
embedding = np.array([float(s) for s in splits[1:]])
embedding_dict[word] = embedding
print("Done loading word embeddings.")
return embedding_dict
def maybe_divide(x, y):
return 0 if y == 0 else x / float(y)
def projection(inputs, output_size, initializer=None):
return ffnn(inputs, 0, -1, output_size, dropout=None, output_weights_initializer=initializer)
def shape(x, dim):
return x.get_shape()[dim].value or tf.shape(x)[dim]
def ffnn(inputs, num_hidden_layers, hidden_size, output_size, dropout, output_weights_initializer=None):
if len(inputs.get_shape()) > 2:
current_inputs = tf.reshape(inputs, [-1, shape(inputs, -1)])
else:
current_inputs = inputs
for i in xrange(num_hidden_layers):
hidden_weights = tf.get_variable("hidden_weights_{}".format(i), [shape(current_inputs, 1), hidden_size])
hidden_bias = tf.get_variable("hidden_bias_{}".format(i), [hidden_size])
current_outputs = tf.nn.relu(tf.matmul(current_inputs, hidden_weights) + hidden_bias)
if dropout is not None:
current_outputs = tf.nn.dropout(current_outputs, dropout)
current_inputs = current_outputs
output_weights = tf.get_variable("output_weights", [shape(current_inputs, 1), output_size], initializer=output_weights_initializer)
output_bias = tf.get_variable("output_bias", [output_size])
outputs = tf.matmul(current_inputs, output_weights) + output_bias
if len(inputs.get_shape()) == 3:
outputs = tf.reshape(outputs, [shape(inputs, 0), shape(inputs, 1), output_size])
elif len(inputs.get_shape()) > 3:
raise ValueError("FFNN with rank {} not supported".format(len(inputs.get_shape())))
return outputs
def cnn(inputs, filter_sizes, num_filters):
num_words = shape(inputs, 0)
num_chars = shape(inputs, 1)
input_size = shape(inputs, 2)
outputs = []
for i, filter_size in enumerate(filter_sizes):
with tf.variable_scope("conv_{}".format(i)):
w = tf.get_variable("w", [filter_size, input_size, num_filters])
b = tf.get_variable("b", [num_filters])
conv = tf.nn.conv1d(inputs, w, stride=1, padding="VALID") # [num_words, num_chars - filter_size, num_filters]
h = tf.nn.relu(tf.nn.bias_add(conv, b)) # [num_words, num_chars - filter_size, num_filters]
pooled = tf.reduce_max(h, 1) # [num_words, num_filters]
outputs.append(pooled)
return tf.concat(outputs, 1) # [num_words, num_filters * len(filter_sizes)]
def normalize(v):
norm = np.linalg.norm(v)
if norm > 0:
return v / norm
else:
return v
class RetrievalEvaluator(object):
def __init__(self):
self._num_correct = 0
self._num_gold = 0
self._num_predicted = 0
def update(self, gold_set, predicted_set):
self._num_correct += len(gold_set & predicted_set)
self._num_gold += len(gold_set)
self._num_predicted += len(predicted_set)
def recall(self):
return maybe_divide(self._num_correct, self._num_gold)
def precision(self):
return maybe_divide(self._num_correct, self._num_predicted)
def metrics(self):
recall = self.recall()
precision = self.precision()
f1 = maybe_divide(2 * recall * precision, precision + recall)
return recall, precision, f1
class CustomLSTMCell(tf.contrib.rnn.RNNCell):
def __init__(self, num_units, batch_size, dropout):
self._num_units = num_units
self._dropout = dropout
self._dropout_mask = tf.nn.dropout(tf.ones([batch_size, self.output_size]), dropout)
self._initializer = self._block_orthonormal_initializer([self.output_size] * 3)
initial_cell_state = tf.get_variable("lstm_initial_cell_state", [1, self.output_size])
initial_hidden_state = tf.get_variable("lstm_initial_hidden_state", [1, self.output_size])
self._initial_state = tf.contrib.rnn.LSTMStateTuple(initial_cell_state, initial_hidden_state)
@property
def state_size(self):
return tf.contrib.rnn.LSTMStateTuple(self.output_size, self.output_size)
@property
def output_size(self):
return self._num_units
@property
def initial_state(self):
return self._initial_state
def preprocess_input(self, inputs):
return projection(inputs, 3 * self.output_size)
def __call__(self, inputs, state, scope=None):
"""Long short-term memory cell (LSTM)."""
with tf.variable_scope(scope or type(self).__name__): # "CustomLSTMCell"
c, h = state
h *= self._dropout_mask
projected_h = projection(h, 3 * self.output_size, initializer=self._initializer)
concat = inputs + projected_h
i, j, o = tf.split(concat, num_or_size_splits=3, axis=1)
i = tf.sigmoid(i)
new_c = (1 - i) * c + i * tf.tanh(j)
new_h = tf.tanh(new_c) * tf.sigmoid(o)
new_state = tf.contrib.rnn.LSTMStateTuple(new_c, new_h)
return new_h, new_state
def _orthonormal_initializer(self, scale=1.0):
def _initializer(shape, dtype=tf.float32, partition_info=None):
M1 = np.random.randn(shape[0], shape[0]).astype(np.float32)
M2 = np.random.randn(shape[1], shape[1]).astype(np.float32)
Q1, R1 = np.linalg.qr(M1)
Q2, R2 = np.linalg.qr(M2)
Q1 = Q1 * np.sign(np.diag(R1))
Q2 = Q2 * np.sign(np.diag(R2))
n_min = min(shape[0], shape[1])
params = np.dot(Q1[:, :n_min], Q2[:n_min, :]) * scale
return params
return _initializer
def _block_orthonormal_initializer(self, output_sizes):
def _initializer(shape, dtype=np.float32, partition_info=None):
assert len(shape) == 2
assert sum(output_sizes) == shape[1]
initializer = self._orthonormal_initializer()
params = np.concatenate([initializer([shape[0], o], dtype, partition_info) for o in output_sizes], 1)
return params
return _initializer
*.jsonlines
<!DOCTYPE HTML>
<html>
<head>
<title>End-to-End Neural Coreference Resolution Visualization</title>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="main.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-3">
<h4>Top Spans</h4>
<ul id="top-spans" class="list-group"></ul>
</div>
<div class="col-md-6">
<h4>Document</h4>
<input id="show-attention" type="checkbox" class="custom-control-input">
<span class="custom-control-description">Render attention weights on hover</span>
<br>
<button id="back-btn" type="button" class="btn btn-default">
<span class="glyphicon glyphicon-menu-left" style="vertical-align: -2px;"></span>
</button>
<button id="forward-btn" type="button" class="btn btn-default">
<span class="glyphicon glyphicon-menu-right" style="vertical-align: -2px;"></span>
</button>
<p id="text" class="lead"></p>
</div>
<div class="col-md-3">
<h4>Predicted Clusters</h4>
<ul id="predicted-clusters" class="list-group"></ul>
</div>
</div>
</body>
</html>
function get_param(name) {
var results = new RegExp("[\?&]" + name + "=([^]*)").exec(window.location.href);
if (results == null){
return null;
}
else{
return results[1] || 0;
}
}
function logsumexp(x) {
var a = Math.max.apply(null, x);
var total = 0.0;
for (var i = 0; i < x.length; i++) {
total += Math.exp(x[i] - a);
}
return Math.log(total) + a;
}
function set_mention_callbacks(hover_callbacks, unhover_callbacks, head_scores, mention_start, mention_end) {
var scores = [];
for (var token = mention_start; token <= mention_end; token++) {
scores.push(head_scores[token]);
}
var log_norm = logsumexp(scores);
hover_callbacks.add(function() {
var show_attention = $("#show-attention").is(":checked");
for (var token = mention_start; token <= mention_end; token++) {
var token_span = $("#t" + token);
token_span.css("font-weight", "normal");
if (show_attention) {
var p = Math.exp(head_scores[token] - log_norm);
var r = Math.round(-36 * p + 255);
var g = Math.round(-187 * p + 255);
var b = Math.round(-200 * p + 255);
var c = p > 0.75 ? "lightgray" : "black";
token_span
.css("color", c)
.css("background-color", "rgb(" + r + "," + g + "," + b + ")");
}
}
$("#lrb" + mention_start).text("(");
$("#rrb" + mention_end).text(")");
});
unhover_callbacks.add(function() {
for (var token = mention_start; token <= mention_end; token++) {
$("#t" + token)
.css("color", "black")
.css("font-weight", "300")
.css("background-color", "white");
}
$("#lrb" + mention_start).text("");
$("#rrb" + mention_end).text("");
});
}
function render_predicted_clusters(clusters_div, clusters_data, text, head_scores) {
clusters_div.empty();
$.each(clusters_data, function(i, cluster) {
var item = $("<li>")
.addClass("list-group-item")
.appendTo(clusters_div);
var hover_callbacks = $.Callbacks();
var unhover_callbacks = $.Callbacks();
$.each(cluster, function(j, mention) {
if (j != 0) {
$("<span>").html(", ").appendTo(item);
}
var mention_start = mention[0];
var mention_end = mention[1];
set_mention_callbacks(hover_callbacks, unhover_callbacks, head_scores, mention_start, mention_end);
var mention_text = text.slice(mention_start, mention_end + 1).join(" ");
$("<span>")
.html(mention_text)
.appendTo(item);
});
item.hover(hover_callbacks.fire, unhover_callbacks.fire);
});
}
function render_top_spans(top_spans_div, top_spans_data, text, head_scores) {
top_spans_div.empty();
$.each(top_spans_data, function(i, mention) {
var item = $("<li>")
.addClass("list-group-item")
.appendTo(top_spans_div);
var hover_callbacks = $.Callbacks();
var unhover_callbacks = $.Callbacks();
var mention_start = mention[0];
var mention_end = mention[1];
set_mention_callbacks(hover_callbacks, unhover_callbacks, head_scores, mention_start, mention_end);
var mention_text = text.slice(mention_start, mention_end + 1).join(" ");
$("<span>")
.html(mention_text)
.appendTo(item);
item.hover(hover_callbacks.fire, unhover_callbacks.fire);
});
}
function load_example(lines) {
var example_num;
if (window.location.hash == "") {
example_num = 0;
}
else {
example_num = parseInt(window.location.hash.slice(1));
}
var data = JSON.parse(lines[example_num]);
var text_div = $("#text");
text_div.empty();
var text = [].concat.apply([], data.sentences);
$.each(text, function(i, token) {
var lrb = $("<span>")
.attr("id", "lrb" + i)
.appendTo(text_div);
var text_span = $("<span>")
.attr("id", "t" + i)
.html(token)
.appendTo(text_div);
var rrb = $("<span>")
.attr("id", "rrb" + i)
.appendTo(text_div);
$("<span>").text(" ").appendTo(text_div);
});
render_predicted_clusters($("#predicted-clusters"), data.predicted_clusters, text, data.head_scores);
render_top_spans($("#top-spans"), data.top_spans, text, data.head_scores);
if (example_num > 0) {
$("#back-btn").click(function() {
window.location.hash = example_num - 1;
});
}
if (example_num < lines.length - 1) {
$("#forward-btn").click(function() {
window.location.hash = example_num + 1;
});
}
}
$(document).ready(function() {
$.ajax({
url : get_param("path"),
dataType: "text",
success : function (data) {
var lines = data.split("\n");
$(window).on("hashchange", function() {
load_example(lines);
});
load_example(lines);
}
});
});
#!/bin/bash
python -m SimpleHTTPServer 8080
#!/usr/bin/env python
import os
import sys
sys.path.append(os.getcwd())
import json
import time
import random
import numpy as np
import tensorflow as tf
import coref_model as cm
import util
if __name__ == "__main__":
name = os.environ["EXP"]
task_index = int(os.environ["TASK"])
config = util.get_config("experiments.conf")[name]
report_frequency = config["report_frequency"]
config["log_dir"] = util.mkdirs(os.path.join(config["log_root"], name))
util.print_config(config)
cluster_config = config["cluster"]
util.set_gpus(cluster_config["gpus"][task_index])
cluster = tf.train.ClusterSpec(cluster_config["addresses"])
server = tf.train.Server(cluster,
job_name="worker",
task_index=task_index)
# Assigns ops to the local worker by default.
with tf.device(tf.train.replica_device_setter(worker_device="/job:worker/task:%d" % task_index, cluster=cluster)):
model = cm.CorefModel(config)
saver = tf.train.Saver()
init_op = tf.global_variables_initializer()
log_dir = config["log_dir"]
is_chief = (task_index == 0)
# Create a "supervisor", which oversees the training process.
sv = tf.train.Supervisor(is_chief=is_chief,
logdir=log_dir,
init_op=init_op,
saver=saver,
global_step=model.global_step,
save_model_secs=120)
# The supervisor takes care of session initialization, restoring from
# a checkpoint, and closing when done or an error occurs.
writer = tf.summary.FileWriter(os.path.join(log_dir, "w{}".format(task_index)), flush_secs=20)
with sv.managed_session(server.target) as session:
model.start_enqueue_thread(session)
if "pretrained_dir" in config:
ckpt = tf.train.get_checkpoint_state(config["pretrained_dir"])
assert ckpt.model_checkpoint_path
print "Loading pretrained model from {}".format(ckpt.model_checkpoint_path)
saver.restore(session, ckpt.model_checkpoint_path)
session.run(model.reset_global_step)
accumulated_loss = 0.0
initial_time = time.time()
while not sv.should_stop():
tf_loss, tf_global_step, _ = session.run([model.loss, model.global_step, model.train_op])
accumulated_loss += tf_loss
if tf_global_step % report_frequency == 0:
total_time = time.time() - initial_time
steps_per_second = tf_global_step / total_time
average_loss = accumulated_loss / report_frequency
print "[{}] loss={:.2f}, steps/s={:.2f}".format(tf_global_step, tf_loss, steps_per_second)
accumulated_loss = 0.0
writer.add_summary(util.make_summary({
"Train Loss": average_loss,
"Steps per second": steps_per_second
}))
# Ask for all the services to stop.
sv.stop()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment