Commit 22085000 by Kenton Lee

Initial commit.

parents
*.pyc
*.so
*.jsonlines
logs
conll-2012
*.txt
*.txt.filtered
*.v*_*_conll
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2017 Kenton Lee
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
# 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);
import operator
import random
import math
import json
import threading
import numpy as np
import tensorflow as tf
import util
import coref_ops
import conll
import metrics
class CorefModel(object):
def __init__(self, config):
self.config = config
self.embedding_info = [(emb["size"], emb["lowercase"]) for emb in config["embeddings"]]
self.embedding_size = sum(size for size, _ in self.embedding_info)
self.char_embedding_size = config["char_embedding_size"]
self.char_dict = util.load_char_dict(config["char_vocab_path"])
self.embedding_dicts = [util.load_embedding_dict(emb["path"], emb["size"], emb["format"]) for emb in config["embeddings"]]
self.max_mention_width = config["max_mention_width"]
self.genres = { g:i for i,g in enumerate(config["genres"]) }
self.eval_data = None # Load eval data lazily.
input_props = []
input_props.append((tf.float32, [None, None, self.embedding_size])) # Text embeddings.
input_props.append((tf.int32, [None, None, None])) # Character indices.
input_props.append((tf.int32, [None])) # Text lengths.
input_props.append((tf.int32, [None])) # Speaker IDs.
input_props.append((tf.int32, [])) # Genre.
input_props.append((tf.bool, [])) # Is training.
input_props.append((tf.int32, [None])) # Gold starts.
input_props.append((tf.int32, [None])) # Gold ends.
input_props.append((tf.int32, [None])) # Cluster ids.
self.queue_input_tensors = [tf.placeholder(dtype, shape) for dtype, shape in input_props]
dtypes, shapes = zip(*input_props)
queue = tf.PaddingFIFOQueue(capacity=10, dtypes=dtypes, shapes=shapes)
self.enqueue_op = queue.enqueue(self.queue_input_tensors)
self.input_tensors = queue.dequeue()
self.predictions, self.loss = self.get_predictions_and_loss(*self.input_tensors)
self.global_step = tf.Variable(0, name="global_step", trainable=False)
self.reset_global_step = tf.assign(self.global_step, 0)
learning_rate = tf.train.exponential_decay(self.config["learning_rate"], self.global_step,
self.config["decay_frequency"], self.config["decay_rate"], staircase=True)
trainable_params = tf.trainable_variables()
gradients = tf.gradients(self.loss, trainable_params)
gradients, _ = tf.clip_by_global_norm(gradients, self.config["max_gradient_norm"])
optimizers = {
"adam" : tf.train.AdamOptimizer,
"sgd" : tf.train.GradientDescentOptimizer
}
optimizer = optimizers[self.config["optimizer"]](learning_rate)
self.train_op = optimizer.apply_gradients(zip(gradients, trainable_params), global_step=self.global_step)
def start_enqueue_thread(self, session):
with open(self.config["train_path"]) as f:
train_examples = [json.loads(jsonline) for jsonline in f.readlines()]
def _enqueue_loop():
while True:
random.shuffle(train_examples)
for example in train_examples:
tensorized_example = self.tensorize_example(example, is_training=True)
feed_dict = dict(zip(self.queue_input_tensors, tensorized_example))
session.run(self.enqueue_op, feed_dict=feed_dict)
enqueue_thread = threading.Thread(target=_enqueue_loop)
enqueue_thread.daemon = True
enqueue_thread.start()
def tensorize_mentions(self, mentions):
if len(mentions) > 0:
starts, ends = zip(*mentions)
else:
starts, ends = [], []
return np.array(starts), np.array(ends)
def tensorize_example(self, example, is_training, oov_counts=None):
clusters = example["clusters"]
gold_mentions = sorted(tuple(m) for m in util.flatten(clusters))
gold_mention_map = {m:i for i,m in enumerate(gold_mentions)}
cluster_ids = np.zeros(len(gold_mentions))
for cluster_id, cluster in enumerate(clusters):
for mention in cluster:
cluster_ids[gold_mention_map[tuple(mention)]] = cluster_id
sentences = example["sentences"]
num_words = sum(len(s) for s in sentences)
speakers = util.flatten(example["speakers"])
assert num_words == len(speakers)
max_sentence_length = max(len(s) for s in sentences)
max_word_length = max(max(max(len(w) for w in s) for s in sentences), max(self.config["filter_widths"]))
word_emb = np.zeros([len(sentences), max_sentence_length, self.embedding_size])
char_index = np.zeros([len(sentences), max_sentence_length, max_word_length])
text_len = np.array([len(s) for s in sentences])
for i, sentence in enumerate(sentences):
for j, word in enumerate(sentence):
current_dim = 0
for k, (d, (s,l)) in enumerate(zip(self.embedding_dicts, self.embedding_info)):
if l:
current_word = word.lower()
else:
current_word = word
if oov_counts is not None and current_word not in d:
oov_counts[k] += 1
word_emb[i, j, current_dim:current_dim + s] = util.normalize(d[current_word])
current_dim += s
char_index[i, j, :len(word)] = [self.char_dict[c] for c in word]
speaker_dict = { s:i for i,s in enumerate(set(speakers)) }
speaker_ids = np.array([speaker_dict[s] for s in speakers])
doc_key = example["doc_key"]
genre = self.genres[doc_key[:2]]
gold_starts, gold_ends = self.tensorize_mentions(gold_mentions)
if is_training and len(sentences) > self.config["max_training_sentences"]:
return self.truncate_example(word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids)
else:
return word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids
def truncate_example(self, word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids):
max_training_sentences = self.config["max_training_sentences"]
num_sentences = word_emb.shape[0]
assert num_sentences > max_training_sentences
sentence_offset = random.randint(0, num_sentences - max_training_sentences)
word_offset = text_len[:sentence_offset].sum()
num_words = text_len[sentence_offset:sentence_offset + max_training_sentences].sum()
word_emb = word_emb[sentence_offset:sentence_offset + max_training_sentences,:,:]
char_index = char_index[sentence_offset:sentence_offset + max_training_sentences,:,:]
text_len = text_len[sentence_offset:sentence_offset + max_training_sentences]
speaker_ids = speaker_ids[word_offset: word_offset + num_words]
gold_spans = np.logical_and(gold_ends >= word_offset, gold_starts < word_offset + num_words)
gold_starts = gold_starts[gold_spans] - word_offset
gold_ends = gold_ends[gold_spans] - word_offset
cluster_ids = cluster_ids[gold_spans]
return word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids
def get_predictions_and_loss(self, word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids):
self.dropout = 1 - (tf.to_float(is_training) * self.config["dropout_rate"])
self.lexical_dropout = 1 - (tf.to_float(is_training) * self.config["lexical_dropout_rate"])
num_sentences = tf.shape(word_emb)[0]
max_sentence_length = tf.shape(word_emb)[1]
text_emb_list = [word_emb]
if self.config["char_embedding_size"] > 0:
char_emb = tf.gather(tf.get_variable("char_embeddings", [len(self.char_dict), self.config["char_embedding_size"]]), char_index) # [num_sentences, max_sentence_length, max_word_length, emb]
flattened_char_emb = tf.reshape(char_emb, [num_sentences * max_sentence_length, util.shape(char_emb, 2), util.shape(char_emb, 3)]) # [num_sentences * max_sentence_length, max_word_length, emb]
flattened_aggregated_char_emb = util.cnn(flattened_char_emb, self.config["filter_widths"], self.config["filter_size"]) # [num_sentences * max_sentence_length, emb]
aggregated_char_emb = tf.reshape(flattened_aggregated_char_emb, [num_sentences, max_sentence_length, util.shape(flattened_aggregated_char_emb, 1)]) # [num_sentences, max_sentence_length, emb]
text_emb_list.append(aggregated_char_emb)
text_emb = tf.concat(text_emb_list, 2)
text_emb = tf.nn.dropout(text_emb, self.lexical_dropout)
text_len_mask = tf.sequence_mask(text_len, maxlen=max_sentence_length)
text_len_mask = tf.reshape(text_len_mask, [num_sentences * max_sentence_length])
text_outputs = self.encode_sentences(text_emb, text_len, text_len_mask)
text_outputs = tf.nn.dropout(text_outputs, self.dropout)
genre_emb = tf.gather(tf.get_variable("genre_embeddings", [len(self.genres), self.config["feature_size"]]), genre) # [emb]
sentence_indices = tf.tile(tf.expand_dims(tf.range(num_sentences), 1), [1, max_sentence_length]) # [num_sentences, max_sentence_length]
flattened_sentence_indices = self.flatten_emb_by_sentence(sentence_indices, text_len_mask) # [num_words]
flattened_text_emb = self.flatten_emb_by_sentence(text_emb, text_len_mask) # [num_words]
candidate_starts, candidate_ends = coref_ops.spans(
sentence_indices=flattened_sentence_indices,
max_width=self.max_mention_width)
candidate_starts.set_shape([None])
candidate_ends.set_shape([None])
candidate_mention_emb = self.get_mention_emb(flattened_text_emb, text_outputs, candidate_starts, candidate_ends) # [num_candidates, emb]
candidate_mention_scores = self.get_mention_scores(candidate_mention_emb) # [num_mentions, 1]
candidate_mention_scores = tf.squeeze(candidate_mention_scores, 1) # [num_mentions]
k = tf.to_int32(tf.floor(tf.to_float(tf.shape(text_outputs)[0]) * self.config["mention_ratio"]))
predicted_mention_indices = coref_ops.extract_mentions(candidate_mention_scores, candidate_starts, candidate_ends, k) # ([k], [k])
predicted_mention_indices.set_shape([None])
mention_starts = tf.gather(candidate_starts, predicted_mention_indices) # [num_mentions]
mention_ends = tf.gather(candidate_ends, predicted_mention_indices) # [num_mentions]
mention_emb = tf.gather(candidate_mention_emb, predicted_mention_indices) # [num_mentions, emb]
mention_scores = tf.gather(candidate_mention_scores, predicted_mention_indices) # [num_mentions]
mention_start_emb = tf.gather(text_outputs, mention_starts) # [num_mentions, emb]
mention_end_emb = tf.gather(text_outputs, mention_ends) # [num_mentions, emb]
mention_speaker_ids = tf.gather(speaker_ids, mention_starts) # [num_mentions]
max_antecedents = self.config["max_antecedents"]
antecedents, antecedent_labels, antecedents_len = coref_ops.antecedents(mention_starts, mention_ends, gold_starts, gold_ends, cluster_ids, max_antecedents) # ([num_mentions, max_ant], [num_mentions, max_ant + 1], [num_mentions]
antecedents.set_shape([None, None])
antecedent_labels.set_shape([None, None])
antecedents_len.set_shape([None])
antecedent_scores = self.get_antecedent_scores(mention_emb, mention_scores, antecedents, antecedents_len, mention_starts, mention_ends, mention_speaker_ids, genre_emb) # [num_mentions, max_ant + 1]
loss = self.softmax_loss(antecedent_scores, antecedent_labels) # [num_mentions]
loss = tf.reduce_sum(loss) # []
return [candidate_starts, candidate_ends, candidate_mention_scores, mention_starts, mention_ends, antecedents, antecedent_scores], loss
def get_mention_emb(self, text_emb, text_outputs, mention_starts, mention_ends):
mention_emb_list = []
mention_start_emb = tf.gather(text_outputs, mention_starts) # [num_mentions, emb]
mention_emb_list.append(mention_start_emb)
mention_end_emb = tf.gather(text_outputs, mention_ends) # [num_mentions, emb]
mention_emb_list.append(mention_end_emb)
mention_width = 1 + mention_ends - mention_starts # [num_mentions]
if self.config["use_features"]:
mention_width_index = mention_width - 1 # [num_mentions]
mention_width_emb = tf.gather(tf.get_variable("mention_width_embeddings", [self.config["max_mention_width"], self.config["feature_size"]]), mention_width_index) # [num_mentions, emb]
mention_width_emb = tf.nn.dropout(mention_width_emb, self.dropout)
mention_emb_list.append(mention_width_emb)
if self.config["model_heads"]:
mention_indices = tf.expand_dims(tf.range(self.config["max_mention_width"]), 0) + tf.expand_dims(mention_starts, 1) # [num_mentions, max_mention_width]
mention_indices = tf.minimum(util.shape(text_outputs, 0) - 1, mention_indices) # [num_mentions, max_mention_width]
mention_text_emb = tf.gather(text_emb, mention_indices) # [num_mentions, max_mention_width, emb]
self.head_scores = util.projection(text_outputs, 1) # [num_words, 1]
mention_head_scores = tf.gather(self.head_scores, mention_indices) # [num_mentions, max_mention_width, 1]
mention_mask = tf.expand_dims(tf.sequence_mask(mention_width, self.config["max_mention_width"], dtype=tf.float32), 2) # [num_mentions, max_mention_width, 1]
mention_attention = tf.nn.softmax(mention_head_scores + tf.log(mention_mask), dim=1) # [num_mentions, max_mention_width, 1]
mention_head_emb = tf.reduce_sum(mention_attention * mention_text_emb, 1) # [num_mentions, emb]
mention_emb_list.append(mention_head_emb)
mention_emb = tf.concat(mention_emb_list, 1) # [num_mentions, emb]
return mention_emb
def get_mention_scores(self, mention_emb):
with tf.variable_scope("mention_scores"):
return util.ffnn(mention_emb, self.config["ffnn_depth"], self.config["ffnn_size"], 1, self.dropout) # [num_mentions, 1]
def softmax_loss(self, antecedent_scores, antecedent_labels):
gold_scores = antecedent_scores + tf.log(tf.to_float(antecedent_labels)) # [num_mentions, max_ant + 1]
marginalized_gold_scores = tf.reduce_logsumexp(gold_scores, [1]) # [num_mentions]
log_norm = tf.reduce_logsumexp(antecedent_scores, [1]) # [num_mentions]
return log_norm - marginalized_gold_scores # [num_mentions]
def get_antecedent_scores(self, mention_emb, mention_scores, antecedents, antecedents_len, mention_starts, mention_ends, mention_speaker_ids, genre_emb):
num_mentions = util.shape(mention_emb, 0)
max_antecedents = util.shape(antecedents, 1)
feature_emb_list = []
if self.config["use_metadata"]:
antecedent_speaker_ids = tf.gather(mention_speaker_ids, antecedents) # [num_mentions, max_ant]
same_speaker = tf.equal(tf.expand_dims(mention_speaker_ids, 1), antecedent_speaker_ids) # [num_mentions, max_ant]
speaker_pair_emb = tf.gather(tf.get_variable("same_speaker_emb", [2, self.config["feature_size"]]), tf.to_int32(same_speaker)) # [num_mentions, max_ant, emb]
feature_emb_list.append(speaker_pair_emb)
tiled_genre_emb = tf.tile(tf.expand_dims(tf.expand_dims(genre_emb, 0), 0), [num_mentions, max_antecedents, 1]) # [num_mentions, max_ant, emb]
feature_emb_list.append(tiled_genre_emb)
if self.config["use_features"]:
target_indices = tf.range(num_mentions) # [num_mentions]
mention_distance = tf.expand_dims(target_indices, 1) - antecedents # [num_mentions, max_ant]
mention_distance_bins = coref_ops.distance_bins(mention_distance) # [num_mentions, max_ant]
mention_distance_bins.set_shape([None, None])
mention_distance_emb = tf.gather(tf.get_variable("mention_distance_emb", [10, self.config["feature_size"]]), mention_distance_bins) # [num_mentions, max_ant]
feature_emb_list.append(mention_distance_emb)
feature_emb = tf.concat(feature_emb_list, 2) # [num_mentions, max_ant, emb]
feature_emb = tf.nn.dropout(feature_emb, self.dropout) # [num_mentions, max_ant, emb]
antecedent_emb = tf.gather(mention_emb, antecedents) # [num_mentions, max_ant, emb]
target_emb_tiled = tf.tile(tf.expand_dims(mention_emb, 1), [1, max_antecedents, 1]) # [num_mentions, max_ant, emb]
similarity_emb = antecedent_emb * target_emb_tiled # [num_mentions, max_ant, emb]
pair_emb = tf.concat([target_emb_tiled, antecedent_emb, similarity_emb, feature_emb], 2) # [num_mentions, max_ant, emb]
with tf.variable_scope("iteration"):
with tf.variable_scope("antecedent_scoring"):
antecedent_scores = util.ffnn(pair_emb, self.config["ffnn_depth"], self.config["ffnn_size"], 1, self.dropout) # [num_mentions, max_ant, 1]
antecedent_scores = tf.squeeze(antecedent_scores, 2) # [num_mentions, max_ant]
antecedent_mask = tf.log(tf.sequence_mask(antecedents_len, max_antecedents, dtype=tf.float32)) # [num_mentions, max_ant]
antecedent_scores += antecedent_mask # [num_mentions, max_ant]
antecedent_scores += tf.expand_dims(mention_scores, 1) + tf.gather(mention_scores, antecedents) # [num_mentions, max_ant]
antecedent_scores = tf.concat([tf.zeros([util.shape(mention_scores, 0), 1]), antecedent_scores], 1) # [num_mentions, max_ant + 1]
return antecedent_scores # [num_mentions, max_ant + 1]
def flatten_emb_by_sentence(self, emb, text_len_mask):
num_sentences = tf.shape(emb)[0]
max_sentence_length = tf.shape(emb)[1]
emb_rank = len(emb.get_shape())
if emb_rank == 2:
flattened_emb = tf.reshape(emb, [num_sentences * max_sentence_length])
elif emb_rank == 3:
flattened_emb = tf.reshape(emb, [num_sentences * max_sentence_length, util.shape(emb, 2)])
else:
raise ValueError("Unsupported rank: {}".format(emb_rank))
return tf.boolean_mask(flattened_emb, text_len_mask)
def encode_sentences(self, text_emb, text_len, text_len_mask):
num_sentences = tf.shape(text_emb)[0]
max_sentence_length = tf.shape(text_emb)[1]
# Transpose before and after for efficiency.
inputs = tf.transpose(text_emb, [1, 0, 2]) # [max_sentence_length, num_sentences, emb]
with tf.variable_scope("fw_cell"):
cell_fw = util.CustomLSTMCell(self.config["lstm_size"], num_sentences, self.dropout)
preprocessed_inputs_fw = cell_fw.preprocess_input(inputs)
with tf.variable_scope("bw_cell"):
cell_bw = util.CustomLSTMCell(self.config["lstm_size"], num_sentences, self.dropout)
preprocessed_inputs_bw = cell_bw.preprocess_input(inputs)
preprocessed_inputs_bw = tf.reverse_sequence(preprocessed_inputs_bw,
seq_lengths=text_len,
seq_dim=0,
batch_dim=1)
state_fw = tf.contrib.rnn.LSTMStateTuple(tf.tile(cell_fw.initial_state.c, [num_sentences, 1]), tf.tile(cell_fw.initial_state.h, [num_sentences, 1]))
state_bw = tf.contrib.rnn.LSTMStateTuple(tf.tile(cell_bw.initial_state.c, [num_sentences, 1]), tf.tile(cell_bw.initial_state.h, [num_sentences, 1]))
with tf.variable_scope("lstm"):
with tf.variable_scope("fw_lstm"):
fw_outputs, fw_states = tf.nn.dynamic_rnn(cell=cell_fw,
inputs=preprocessed_inputs_fw,
sequence_length=text_len,
initial_state=state_fw,
time_major=True)
with tf.variable_scope("bw_lstm"):
bw_outputs, bw_states = tf.nn.dynamic_rnn(cell=cell_bw,
inputs=preprocessed_inputs_bw,
sequence_length=text_len,
initial_state=state_bw,
time_major=True)
bw_outputs = tf.reverse_sequence(bw_outputs,
seq_lengths=text_len,
seq_dim=0,
batch_dim=1)
text_outputs = tf.concat([fw_outputs, bw_outputs], 2)
text_outputs = tf.transpose(text_outputs, [1, 0, 2]) # [num_sentences, max_sentence_length, emb]
return self.flatten_emb_by_sentence(text_outputs, text_len_mask)
def evaluate_mentions(self, candidate_starts, candidate_ends, mention_starts, mention_ends, mention_scores, gold_starts, gold_ends, example, evaluators):
text_length = sum(len(s) for s in example["sentences"])
gold_spans = set(zip(gold_starts, gold_ends))
if len(candidate_starts) > 0:
sorted_starts, sorted_ends, _ = zip(*sorted(zip(candidate_starts, candidate_ends, mention_scores), key=operator.itemgetter(2), reverse=True))
else:
sorted_starts = []
sorted_ends = []
for k, evaluator in evaluators.items():
if k == -3:
predicted_spans = set(zip(candidate_starts, candidate_ends)) & gold_spans
else:
if k == -2:
predicted_starts = mention_starts
predicted_ends = mention_ends
elif k == 0:
is_predicted = mention_scores > 0
predicted_starts = candidate_starts[is_predicted]
predicted_ends = candidate_ends[is_predicted]
else:
if k == -1:
num_predictions = len(gold_spans)
else:
num_predictions = (k * text_length) / 100
predicted_starts = sorted_starts[:num_predictions]
predicted_ends = sorted_ends[:num_predictions]
predicted_spans = set(zip(predicted_starts, predicted_ends))
evaluator.update(gold_set=gold_spans, predicted_set=predicted_spans)
def get_predicted_antecedents(self, antecedents, antecedent_scores):
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])
return predicted_antecedents
def get_predicted_clusters(self, mention_starts, mention_ends, predicted_antecedents):
mention_to_predicted = {}
predicted_clusters = []
for i, predicted_index in enumerate(predicted_antecedents):
if predicted_index < 0:
continue
assert i > predicted_index
predicted_antecedent = (int(mention_starts[predicted_index]), int(mention_ends[predicted_index]))
if predicted_antecedent in mention_to_predicted:
predicted_cluster = mention_to_predicted[predicted_antecedent]
else:
predicted_cluster = len(predicted_clusters)
predicted_clusters.append([predicted_antecedent])
mention_to_predicted[predicted_antecedent] = predicted_cluster
mention = (int(mention_starts[i]), int(mention_ends[i]))
predicted_clusters[predicted_cluster].append(mention)
mention_to_predicted[mention] = predicted_cluster
predicted_clusters = [tuple(pc) for pc in predicted_clusters]
mention_to_predicted = { m:predicted_clusters[i] for m,i in mention_to_predicted.items() }
return predicted_clusters, mention_to_predicted
def evaluate_coref(self, mention_starts, mention_ends, predicted_antecedents, gold_clusters, evaluator):
gold_clusters = [tuple(tuple(m) for m in gc) for gc in gold_clusters]
mention_to_gold = {}
for gc in gold_clusters:
for mention in gc:
mention_to_gold[mention] = gc
predicted_clusters, mention_to_predicted = self.get_predicted_clusters(mention_starts, mention_ends, predicted_antecedents)
evaluator.update(predicted_clusters, gold_clusters, mention_to_predicted, mention_to_gold)
return predicted_clusters
def load_eval_data(self):
if self.eval_data is None:
oov_counts = [0 for _ in self.embedding_dicts]
with open(self.config["eval_path"]) as f:
self.eval_data = map(lambda example: (self.tensorize_example(example, is_training=False, oov_counts=oov_counts), example), (json.loads(jsonline) for jsonline in f.readlines()))
num_words = sum(tensorized_example[2].sum() for tensorized_example, _ in self.eval_data)
for emb, c in zip(self.config["embeddings"], oov_counts):
print("OOV rate for {}: {:.2f}%".format(emb["path"], (100.0 * c) / num_words))
print("Loaded {} eval examples.".format(len(self.eval_data)))
def evaluate(self, session, official_stdout=False):
self.load_eval_data()
def _k_to_tag(k):
if k == -3:
return "oracle"
elif k == -2:
return "actual"
elif k == -1:
return "exact"
elif k == 0:
return "threshold"
else:
return "{}%".format(k)
mention_evaluators = { k:util.RetrievalEvaluator() for k in [-3, -2, -1, 0, 10, 15, 20, 25, 30, 40, 50] }
coref_predictions = {}
coref_evaluator = metrics.CorefEvaluator()
for example_num, (tensorized_example, example) in enumerate(self.eval_data):
_, _, _, _, _, _, gold_starts, gold_ends, _ = tensorized_example
feed_dict = {i:t for i,t in zip(self.input_tensors, tensorized_example)}
candidate_starts, candidate_ends, mention_scores, mention_starts, mention_ends, antecedents, antecedent_scores = session.run(self.predictions, feed_dict=feed_dict)
self.evaluate_mentions(candidate_starts, candidate_ends, mention_starts, mention_ends, mention_scores, gold_starts, gold_ends, example, mention_evaluators)
predicted_antecedents = self.get_predicted_antecedents(antecedents, antecedent_scores)
coref_predictions[example["doc_key"]] = self.evaluate_coref(mention_starts, mention_ends, predicted_antecedents, example["clusters"], coref_evaluator)
if example_num % 10 == 0:
print "Evaluated {}/{} examples.".format(example_num + 1, len(self.eval_data))
summary_dict = {}
for k, evaluator in sorted(mention_evaluators.items(), key=operator.itemgetter(0)):
tags = ["{} @ {}".format(t, _k_to_tag(k)) for t in ("R", "P", "F")]
results_to_print = []
for t, v in zip(tags, evaluator.metrics()):
results_to_print.append("{:<10}: {:.2f}".format(t, v))
summary_dict[t] = v
print ", ".join(results_to_print)
conll_results = conll.evaluate_conll(self.config["conll_eval_path"], coref_predictions, official_stdout)
average_f1 = sum(results["f"] for results in conll_results.values()) / len(conll_results)
summary_dict["Average F1 (conll)"] = average_f1
print "Average F1 (conll): {:.2f}%".format(average_f1)
p,r,f = coref_evaluator.get_prf()
summary_dict["Average F1 (py)"] = f
print "Average F1 (py): {:.2f}%".format(f * 100)
summary_dict["Average precision (py)"] = p
print "Average precision (py): {:.2f}%".format(p * 100)
summary_dict["Average recall (py)"] = r
print "Average recall (py): {:.2f}%".format(r * 100)
return util.make_summary(summary_dict), average_f1
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