run_ner.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. #! usr/bin/env python3
  2. # -*- coding:utf-8 -*-
  3. """
  4. Copyright 2018 The Google AI Language Team Authors.
  5. BASED ON Google_BERT.
  6. """
  7. from __future__ import absolute_import
  8. from __future__ import division
  9. from __future__ import print_function
  10. import collections
  11. import os, sys
  12. import pickle
  13. import tensorflow as tf
  14. import numpy as np
  15. sys.path.append("/workspace/bert")
  16. from biobert.conlleval import evaluate, report_notprint
  17. import modeling
  18. import optimization
  19. import tokenization
  20. import tf_metrics
  21. import time
  22. import horovod.tensorflow as hvd
  23. from utils.utils import LogEvalRunHook, LogTrainRunHook
  24. import utils.dllogger_class
  25. from dllogger import Verbosity
  26. flags = tf.flags
  27. FLAGS = flags.FLAGS
  28. flags.DEFINE_string(
  29. "task_name", "NER", "The name of the task to train."
  30. )
  31. flags.DEFINE_string(
  32. "data_dir", None,
  33. "The input datadir.",
  34. )
  35. flags.DEFINE_string(
  36. "output_dir", None,
  37. "The output directory where the model checkpoints will be written."
  38. )
  39. flags.DEFINE_string(
  40. "bert_config_file", None,
  41. "The config json file corresponding to the pre-trained BERT model."
  42. )
  43. flags.DEFINE_string(
  44. "vocab_file", None,
  45. "The vocabulary file that the BERT model was trained on.")
  46. flags.DEFINE_string(
  47. "dllog_path", "/results/bert_dllog.json",
  48. "filename where dllogger writes to")
  49. flags.DEFINE_string(
  50. "init_checkpoint", None,
  51. "Initial checkpoint (usually from a pre-trained BERT model)."
  52. )
  53. flags.DEFINE_bool(
  54. "do_lower_case", False,
  55. "Whether to lower case the input text."
  56. )
  57. flags.DEFINE_integer(
  58. "max_seq_length", 128,
  59. "The maximum total input sequence length after WordPiece tokenization."
  60. )
  61. flags.DEFINE_bool(
  62. "do_train", False,
  63. "Whether to run training."
  64. )
  65. flags.DEFINE_bool(
  66. "do_eval", False,
  67. "Whether to run eval on the dev set.")
  68. flags.DEFINE_bool(
  69. "do_predict", False,
  70. "Whether to run the model in inference mode on the test set.")
  71. flags.DEFINE_integer(
  72. "train_batch_size", 64,
  73. "Total batch size for training.")
  74. flags.DEFINE_integer(
  75. "eval_batch_size", 16,
  76. "Total batch size for eval.")
  77. flags.DEFINE_integer(
  78. "predict_batch_size", 16,
  79. "Total batch size for predict.")
  80. flags.DEFINE_float(
  81. "learning_rate", 5e-6,
  82. "The initial learning rate for Adam.")
  83. flags.DEFINE_float(
  84. "num_train_epochs", 10.0,
  85. "Total number of training epochs to perform.")
  86. flags.DEFINE_float(
  87. "warmup_proportion", 0.1,
  88. "Proportion of training to perform linear learning rate warmup for. "
  89. "E.g., 0.1 = 10% of training.")
  90. flags.DEFINE_integer(
  91. "save_checkpoints_steps", 1000,
  92. "How often to save the model checkpoint.")
  93. flags.DEFINE_integer(
  94. "iterations_per_loop", 1000,
  95. "How many steps to make in each estimator call.")
  96. tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
  97. flags.DEFINE_bool("horovod", False, "Whether to use Horovod for multi-gpu runs")
  98. flags.DEFINE_bool("amp", True, "Whether to enable AMP ops. When false, uses TF32 on A100 and FP32 on V100 GPUS.")
  99. flags.DEFINE_bool("use_xla", True, "Whether to enable XLA JIT compilation.")
  100. class InputExample(object):
  101. """A single training/test example for simple sequence classification."""
  102. def __init__(self, guid, text, label=None):
  103. """Constructs a InputExample.
  104. Args:
  105. guid: Unique id for the example.
  106. text_a: string. The untokenized text of the first sequence. For single
  107. sequence tasks, only this sequence must be specified.
  108. label: (Optional) string. The label of the example. This should be
  109. specified for train and dev examples, but not for test examples.
  110. """
  111. self.guid = guid
  112. self.text = text
  113. self.label = label
  114. class InputFeatures(object):
  115. """A single set of features of data."""
  116. def __init__(self, input_ids, input_mask, segment_ids, label_ids, ):
  117. self.input_ids = input_ids
  118. self.input_mask = input_mask
  119. self.segment_ids = segment_ids
  120. self.label_ids = label_ids
  121. # self.label_mask = label_mask
  122. class DataProcessor(object):
  123. """Base class for data converters for sequence classification data sets."""
  124. def get_train_examples(self, data_dir):
  125. """Gets a collection of `InputExample`s for the train set."""
  126. raise NotImplementedError()
  127. def get_dev_examples(self, data_dir):
  128. """Gets a collection of `InputExample`s for the dev set."""
  129. raise NotImplementedError()
  130. def get_labels(self):
  131. """Gets the list of labels for this data set."""
  132. raise NotImplementedError()
  133. @classmethod
  134. def _read_data(cls, input_file):
  135. """Reads a BIO data."""
  136. with open(input_file, "r") as f:
  137. lines = []
  138. words = []
  139. labels = []
  140. for line in f:
  141. contends = line.strip()
  142. if len(contends) == 0:
  143. assert len(words) == len(labels)
  144. if len(words) > 30:
  145. # split if the sentence is longer than 30
  146. while len(words) > 30:
  147. tmplabel = labels[:30]
  148. for iidx in range(len(tmplabel)):
  149. if tmplabel.pop() == 'O':
  150. break
  151. l = ' '.join(
  152. [label for label in labels[:len(tmplabel) + 1] if len(label) > 0])
  153. w = ' '.join(
  154. [word for word in words[:len(tmplabel) + 1] if len(word) > 0])
  155. lines.append([l, w])
  156. words = words[len(tmplabel) + 1:]
  157. labels = labels[len(tmplabel) + 1:]
  158. if len(words) == 0:
  159. continue
  160. l = ' '.join([label for label in labels if len(label) > 0])
  161. w = ' '.join([word for word in words if len(word) > 0])
  162. lines.append([l, w])
  163. words = []
  164. labels = []
  165. continue
  166. word = line.strip().split()[0]
  167. label = line.strip().split()[-1]
  168. words.append(word)
  169. labels.append(label)
  170. return lines
  171. class BC5CDRProcessor(DataProcessor):
  172. def get_train_examples(self, data_dir):
  173. l1 = self._read_data(os.path.join(data_dir, "train.tsv"))
  174. l2 = self._read_data(os.path.join(data_dir, "devel.tsv"))
  175. return self._create_example(l1 + l2, "train")
  176. def get_dev_examples(self, data_dir, file_name="devel.tsv"):
  177. return self._create_example(
  178. self._read_data(os.path.join(data_dir, file_name)), "dev"
  179. )
  180. def get_test_examples(self, data_dir, file_name="test.tsv"):
  181. return self._create_example(
  182. self._read_data(os.path.join(data_dir, file_name)), "test")
  183. def get_labels(self):
  184. return ["B", "I", "O", "X", "[CLS]", "[SEP]"]
  185. def _create_example(self, lines, set_type):
  186. examples = []
  187. for (i, line) in enumerate(lines):
  188. guid = "%s-%s" % (set_type, i)
  189. text = tokenization.convert_to_unicode(line[1])
  190. label = tokenization.convert_to_unicode(line[0])
  191. examples.append(InputExample(guid=guid, text=text, label=label))
  192. return examples
  193. class CLEFEProcessor(DataProcessor):
  194. def get_train_examples(self, data_dir):
  195. lines1 = self._read_data2(os.path.join(data_dir, "Training.tsv"))
  196. lines2 = self._read_data2(os.path.join(data_dir, "Development.tsv"))
  197. return self._create_example(
  198. lines1 + lines2, "train"
  199. )
  200. def get_dev_examples(self, data_dir, file_name="Development.tsv"):
  201. return self._create_example(
  202. self._read_data2(os.path.join(data_dir, file_name)), "dev"
  203. )
  204. def get_test_examples(self, data_dir, file_name="Test.tsv"):
  205. return self._create_example(
  206. self._read_data2(os.path.join(data_dir, file_name)), "test")
  207. def get_labels(self):
  208. return ["B", "I", "O", "X", "[CLS]", "[SEP]"]
  209. def _create_example(self, lines, set_type):
  210. examples = []
  211. for (i, line) in enumerate(lines):
  212. guid = "%s-%s" % (set_type, i)
  213. text = tokenization.convert_to_unicode(line[1])
  214. label = tokenization.convert_to_unicode(line[0])
  215. examples.append(InputExample(guid=guid, text=text, label=label))
  216. return examples
  217. @classmethod
  218. def _read_data2(cls, input_file):
  219. with tf.io.gfile.Open(input_file, "r") as f:
  220. lines = []
  221. words = []
  222. labels = []
  223. for line in f:
  224. contends = line.strip()
  225. if len(contends) == 0:
  226. assert len(words) == len(labels)
  227. if len(words) == 0:
  228. continue
  229. l = ' '.join([label for label in labels if len(label) > 0])
  230. w = ' '.join([word for word in words if len(word) > 0])
  231. lines.append([l, w])
  232. words = []
  233. labels = []
  234. continue
  235. elif contends.startswith('###'):
  236. continue
  237. word = line.strip().split()[0]
  238. label = line.strip().split()[-1]
  239. words.append(word)
  240. labels.append(label)
  241. return lines
  242. class I2b22012Processor(CLEFEProcessor):
  243. def get_labels(self):
  244. return ['B-CLINICAL_DEPT', 'B-EVIDENTIAL', 'B-OCCURRENCE', 'B-PROBLEM', 'B-TEST', 'B-TREATMENT', 'I-CLINICAL_DEPT', 'I-EVIDENTIAL', 'I-OCCURRENCE', 'I-PROBLEM', 'I-TEST', 'I-TREATMENT', "O", "X", "[CLS]", "[SEP]"]
  245. def write_tokens(tokens, labels, mode):
  246. if mode == "test":
  247. path = os.path.join(FLAGS.output_dir, "token_" + mode + ".txt")
  248. if tf.io.gfile.Exists(path):
  249. wf = tf.io.gfile.Open(path, 'a')
  250. else:
  251. wf = tf.io.gfile.Open(path, 'w')
  252. for token, label in zip(tokens, labels):
  253. if token != "**NULL**":
  254. wf.write(token + ' ' + str(label) + '\n')
  255. wf.close()
  256. def convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer, mode):
  257. label_map = {}
  258. for (i, label) in enumerate(label_list, 1):
  259. label_map[label] = i
  260. label2id_file = os.path.join(FLAGS.output_dir, 'label2id.pkl')
  261. if not os.path.exists(label2id_file):
  262. with open(label2id_file, 'wb') as w:
  263. pickle.dump(label_map, w)
  264. textlist = example.text.split(' ')
  265. labellist = example.label.split(' ')
  266. tokens = []
  267. labels = []
  268. for i, word in enumerate(textlist):
  269. token = tokenizer.tokenize(word)
  270. tokens.extend(token)
  271. label_1 = labellist[i]
  272. for m in range(len(token)):
  273. if m == 0:
  274. labels.append(label_1)
  275. else:
  276. labels.append("X")
  277. # tokens = tokenizer.tokenize(example.text)
  278. if len(tokens) >= max_seq_length - 1:
  279. tokens = tokens[0:(max_seq_length - 2)]
  280. labels = labels[0:(max_seq_length - 2)]
  281. ntokens = []
  282. segment_ids = []
  283. label_ids = []
  284. ntokens.append("[CLS]")
  285. segment_ids.append(0)
  286. # append("O") or append("[CLS]") not sure!
  287. label_ids.append(label_map["[CLS]"])
  288. for i, token in enumerate(tokens):
  289. ntokens.append(token)
  290. segment_ids.append(0)
  291. label_ids.append(label_map[labels[i]])
  292. ntokens.append("[SEP]")
  293. segment_ids.append(0)
  294. # append("O") or append("[SEP]") not sure!
  295. label_ids.append(label_map["[SEP]"])
  296. input_ids = tokenizer.convert_tokens_to_ids(ntokens)
  297. input_mask = [1] * len(input_ids)
  298. # label_mask = [1] * len(input_ids)
  299. while len(input_ids) < max_seq_length:
  300. input_ids.append(0)
  301. input_mask.append(0)
  302. segment_ids.append(0)
  303. # we don't concerned about it!
  304. label_ids.append(0)
  305. ntokens.append("**NULL**")
  306. # label_mask.append(0)
  307. # print(len(input_ids))
  308. assert len(input_ids) == max_seq_length
  309. assert len(input_mask) == max_seq_length
  310. assert len(segment_ids) == max_seq_length
  311. assert len(label_ids) == max_seq_length
  312. # assert len(label_mask) == max_seq_length
  313. if ex_index < 5:
  314. tf.compat.v1.logging.info("*** Example ***")
  315. tf.compat.v1.logging.info("guid: %s" % (example.guid))
  316. tf.compat.v1.logging.info("tokens: %s" % " ".join(
  317. [tokenization.printable_text(x) for x in tokens]))
  318. tf.compat.v1.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
  319. tf.compat.v1.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
  320. tf.compat.v1.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
  321. tf.compat.v1.logging.info("label_ids: %s" % " ".join([str(x) for x in label_ids]))
  322. # tf.compat.v1.logging.info("label_mask: %s" % " ".join([str(x) for x in label_mask]))
  323. feature = InputFeatures(
  324. input_ids=input_ids,
  325. input_mask=input_mask,
  326. segment_ids=segment_ids,
  327. label_ids=label_ids,
  328. # label_mask = label_mask
  329. )
  330. # write_tokens(ntokens, label_ids, mode)
  331. return feature
  332. def filed_based_convert_examples_to_features(
  333. examples, label_list, max_seq_length, tokenizer, output_file, mode=None):
  334. writer = tf.python_io.TFRecordWriter(output_file)
  335. for (ex_index, example) in enumerate(examples):
  336. if ex_index % 5000 == 0:
  337. tf.compat.v1.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
  338. feature = convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer,
  339. mode)
  340. def create_int_feature(values):
  341. f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
  342. return f
  343. features = collections.OrderedDict()
  344. features["input_ids"] = create_int_feature(feature.input_ids)
  345. features["input_mask"] = create_int_feature(feature.input_mask)
  346. features["segment_ids"] = create_int_feature(feature.segment_ids)
  347. features["label_ids"] = create_int_feature(feature.label_ids)
  348. # features["label_mask"] = create_int_feature(feature.label_mask)
  349. tf_example = tf.train.Example(features=tf.train.Features(feature=features))
  350. writer.write(tf_example.SerializeToString())
  351. def file_based_input_fn_builder(input_file, batch_size, seq_length, is_training, drop_remainder, hvd=None):
  352. name_to_features = {
  353. "input_ids": tf.io.FixedLenFeature([seq_length], tf.int64),
  354. "input_mask": tf.io.FixedLenFeature([seq_length], tf.int64),
  355. "segment_ids": tf.io.FixedLenFeature([seq_length], tf.int64),
  356. "label_ids": tf.io.FixedLenFeature([seq_length], tf.int64),
  357. # "label_ids":tf.VarLenFeature(tf.int64),
  358. # "label_mask": tf.io.FixedLenFeature([seq_length], tf.int64),
  359. }
  360. def _decode_record(record, name_to_features):
  361. example = tf.parse_single_example(record, name_to_features)
  362. for name in list(example.keys()):
  363. t = example[name]
  364. if t.dtype == tf.int64:
  365. t = tf.to_int32(t)
  366. example[name] = t
  367. return example
  368. def input_fn(params):
  369. #batch_size = params["batch_size"]
  370. d = tf.data.TFRecordDataset(input_file)
  371. if is_training:
  372. if hvd is not None: d = d.shard(hvd.size(), hvd.rank())
  373. d = d.repeat()
  374. d = d.shuffle(buffer_size=100)
  375. d = d.apply(tf.contrib.data.map_and_batch(
  376. lambda record: _decode_record(record, name_to_features),
  377. batch_size=batch_size,
  378. drop_remainder=drop_remainder
  379. ))
  380. return d
  381. return input_fn
  382. def create_model(bert_config, is_training, input_ids, input_mask,
  383. segment_ids, labels, num_labels, use_one_hot_embeddings):
  384. model = modeling.BertModel(
  385. config=bert_config,
  386. is_training=is_training,
  387. input_ids=input_ids,
  388. input_mask=input_mask,
  389. token_type_ids=segment_ids,
  390. use_one_hot_embeddings=use_one_hot_embeddings
  391. )
  392. output_layer = model.get_sequence_output()
  393. hidden_size = output_layer.shape[-1].value
  394. output_weight = tf.get_variable(
  395. "output_weights", [num_labels, hidden_size],
  396. initializer=tf.truncated_normal_initializer(stddev=0.02)
  397. )
  398. output_bias = tf.get_variable(
  399. "output_bias", [num_labels], initializer=tf.zeros_initializer()
  400. )
  401. with tf.variable_scope("loss"):
  402. if is_training:
  403. output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
  404. output_layer = tf.reshape(output_layer, [-1, hidden_size])
  405. logits = tf.matmul(output_layer, output_weight, transpose_b=True)
  406. logits = tf.nn.bias_add(logits, output_bias)
  407. logits = tf.reshape(logits, [-1, FLAGS.max_seq_length, num_labels])
  408. # mask = tf.cast(input_mask,tf.float32)
  409. # loss = tf.contrib.seq2seq.sequence_loss(logits,labels,mask)
  410. # return (loss, logits, predict)
  411. ##########################################################################
  412. log_probs = tf.nn.log_softmax(logits, axis=-1)
  413. one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
  414. per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
  415. loss = tf.reduce_mean(per_example_loss)
  416. probabilities = tf.nn.softmax(logits, axis=-1)
  417. predict = tf.argmax(probabilities, axis=-1)
  418. return (loss, per_example_loss, logits, predict)
  419. ##########################################################################
  420. def model_fn_builder(bert_config, num_labels, init_checkpoint=None, learning_rate=None,
  421. num_train_steps=None, num_warmup_steps=None,
  422. use_one_hot_embeddings=False, hvd=None, amp=False):
  423. def model_fn(features, labels, mode, params):
  424. tf.compat.v1.logging.info("*** Features ***")
  425. for name in sorted(features.keys()):
  426. tf.compat.v1.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
  427. input_ids = features["input_ids"]
  428. input_mask = features["input_mask"]
  429. segment_ids = features["segment_ids"]
  430. label_ids = features["label_ids"]
  431. # label_mask = features["label_mask"]
  432. is_training = (mode == tf.estimator.ModeKeys.TRAIN)
  433. (total_loss, per_example_loss, logits, predicts) = create_model(
  434. bert_config, is_training, input_ids, input_mask, segment_ids, label_ids,
  435. num_labels, use_one_hot_embeddings)
  436. tvars = tf.trainable_variables()
  437. initialized_variable_names = {}
  438. scaffold_fn = None
  439. if init_checkpoint and (hvd is None or hvd.rank() == 0):
  440. (assignment_map,
  441. initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars,
  442. init_checkpoint)
  443. tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
  444. tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
  445. tf.compat.v1.logging.info("**** Trainable Variables ****")
  446. for var in tvars:
  447. init_string = ""
  448. if var.name in initialized_variable_names:
  449. init_string = ", *INIT_FROM_CKPT*"
  450. tf.compat.v1.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
  451. init_string)
  452. output_spec = None
  453. if mode == tf.estimator.ModeKeys.TRAIN:
  454. train_op = optimization.create_optimizer(
  455. total_loss, learning_rate, num_train_steps, num_warmup_steps, hvd, False, amp)
  456. output_spec = tf.estimator.EstimatorSpec(
  457. mode=mode,
  458. loss=total_loss,
  459. train_op=train_op)
  460. elif mode == tf.estimator.ModeKeys.EVAL:
  461. dummy_op = tf.no_op()
  462. # Need to call mixed precision graph rewrite if fp16 to enable graph rewrite
  463. if amp:
  464. dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite(
  465. optimization.LAMBOptimizer(learning_rate=0.0))
  466. def metric_fn(per_example_loss, label_ids, logits):
  467. # def metric_fn(label_ids, logits):
  468. predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
  469. precision = tf_metrics.precision(label_ids, predictions, num_labels, [1, 2], average="macro")
  470. recall = tf_metrics.recall(label_ids, predictions, num_labels, [1, 2], average="macro")
  471. f = tf_metrics.f1(label_ids, predictions, num_labels, [1, 2], average="macro")
  472. #
  473. return {
  474. "precision": precision,
  475. "recall": recall,
  476. "f1": f,
  477. }
  478. eval_metric_ops = metric_fn(per_example_loss, label_ids, logits)
  479. output_spec = tf.estimator.EstimatorSpec(
  480. mode=mode,
  481. loss=total_loss,
  482. eval_metric_ops=eval_metric_ops)
  483. else:
  484. dummy_op = tf.no_op()
  485. # Need to call mixed precision graph rewrite if fp16 to enable graph rewrite
  486. if amp:
  487. dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite(
  488. optimization.LAMBOptimizer(learning_rate=0.0))
  489. output_spec = tf.estimator.EstimatorSpec(
  490. mode=mode, predictions=predicts)#probabilities)
  491. return output_spec
  492. return model_fn
  493. def result_to_pair(predict_line, pred_ids, id2label, writer, err_writer):
  494. words = str(predict_line.text).split(' ')
  495. labels = str(predict_line.label).split(' ')
  496. if len(words) != len(labels):
  497. tf.compat.v1.logging.error('Text and label not equal')
  498. tf.compat.v1.logging.error(predict_line.text)
  499. tf.compat.v1.logging.error(predict_line.label)
  500. exit(1)
  501. # get from CLS to SEP
  502. pred_labels = []
  503. for id in pred_ids:
  504. if id == 0:
  505. continue
  506. curr_label = id2label[id]
  507. if curr_label == '[CLS]':
  508. continue
  509. elif curr_label == '[SEP]':
  510. break
  511. elif curr_label == 'X':
  512. continue
  513. pred_labels.append(curr_label)
  514. if len(pred_labels) > len(words):
  515. err_writer.write(predict_line.guid + '\n')
  516. err_writer.write(predict_line.text + '\n')
  517. err_writer.write(predict_line.label + '\n')
  518. err_writer.write(' '.join([str(i) for i in pred_ids]) + '\n')
  519. err_writer.write(' '.join([id2label.get(i, '**NULL**') for i in pred_ids]) + '\n\n')
  520. pred_labels = pred_labels[:len(words)]
  521. elif len(pred_labels) < len(words):
  522. err_writer.write(predict_line.guid + '\n')
  523. err_writer.write(predict_line.text + '\n')
  524. err_writer.write(predict_line.label + '\n')
  525. err_writer.write(' '.join([str(i) for i in pred_ids]) + '\n')
  526. err_writer.write(' '.join([id2label.get(i, '**NULL**') for i in pred_ids]) + '\n\n')
  527. pred_labels += ['O'] * (len(words) - len(pred_labels))
  528. for tok, label, pred_label in zip(words, labels, pred_labels):
  529. writer.write(tok + ' ' + label + ' ' + pred_label + '\n')
  530. writer.write('\n')
  531. def main(_):
  532. # causes memory fragmentation for bert leading to OOM
  533. if os.environ.get("TF_XLA_FLAGS", None) is not None:
  534. os.environ["TF_XLA_FLAGS"] += "--tf_xla_enable_lazy_compilation=false"
  535. else:
  536. os.environ["TF_XLA_FLAGS"] = "--tf_xla_enable_lazy_compilation=false"
  537. tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO)
  538. dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path)
  539. if FLAGS.horovod:
  540. hvd.init()
  541. processors = {
  542. "bc5cdr": BC5CDRProcessor,
  543. "clefe": CLEFEProcessor,
  544. 'i2b2': I2b22012Processor
  545. }
  546. if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict:
  547. raise ValueError("At least one of `do_train` or `do_eval` must be True.")
  548. bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
  549. if FLAGS.max_seq_length > bert_config.max_position_embeddings:
  550. raise ValueError(
  551. "Cannot use sequence length %d because the BERT model "
  552. "was only trained up to sequence length %d" %
  553. (FLAGS.max_seq_length, bert_config.max_position_embeddings))
  554. task_name = FLAGS.task_name.lower()
  555. if task_name not in processors:
  556. raise ValueError("Task not found: %s" % (task_name))
  557. tf.io.gfile.makedirs(FLAGS.output_dir)
  558. processor = processors[task_name]()
  559. label_list = processor.get_labels()
  560. tokenizer = tokenization.FullTokenizer(
  561. vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
  562. is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
  563. master_process = True
  564. training_hooks = []
  565. global_batch_size = FLAGS.train_batch_size
  566. hvd_rank = 0
  567. config = tf.compat.v1.ConfigProto()
  568. if FLAGS.horovod:
  569. global_batch_size = FLAGS.train_batch_size * hvd.size()
  570. master_process = (hvd.rank() == 0)
  571. hvd_rank = hvd.rank()
  572. config.gpu_options.visible_device_list = str(hvd.local_rank())
  573. if hvd.size() > 1:
  574. training_hooks.append(hvd.BroadcastGlobalVariablesHook(0))
  575. if FLAGS.use_xla:
  576. config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1
  577. tf.enable_resource_variables()
  578. run_config = tf.estimator.RunConfig(
  579. model_dir=FLAGS.output_dir if master_process else None,
  580. session_config=config,
  581. save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process else None,
  582. keep_checkpoint_max=1)
  583. if master_process:
  584. tf.compat.v1.logging.info("***** Configuaration *****")
  585. for key in FLAGS.__flags.keys():
  586. tf.compat.v1.logging.info(' {}: {}'.format(key, getattr(FLAGS, key)))
  587. tf.compat.v1.logging.info("**************************")
  588. train_examples = None
  589. num_train_steps = None
  590. num_warmup_steps = None
  591. training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank))
  592. if FLAGS.do_train:
  593. train_examples = processor.get_train_examples(FLAGS.data_dir)
  594. num_train_steps = int(
  595. len(train_examples) / global_batch_size * FLAGS.num_train_epochs)
  596. num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)
  597. start_index = 0
  598. end_index = len(train_examples)
  599. tmp_filenames = [os.path.join(FLAGS.output_dir, "train.tf_record")]
  600. if FLAGS.horovod:
  601. tmp_filenames = [os.path.join(FLAGS.output_dir, "train.tf_record{}".format(i)) for i in range(hvd.size())]
  602. num_examples_per_rank = len(train_examples) // hvd.size()
  603. remainder = len(train_examples) % hvd.size()
  604. if hvd.rank() < remainder:
  605. start_index = hvd.rank() * (num_examples_per_rank+1)
  606. end_index = start_index + num_examples_per_rank + 1
  607. else:
  608. start_index = hvd.rank() * num_examples_per_rank + remainder
  609. end_index = start_index + (num_examples_per_rank)
  610. model_fn = model_fn_builder(
  611. bert_config=bert_config,
  612. num_labels=len(label_list) + 1,
  613. init_checkpoint=FLAGS.init_checkpoint,
  614. learning_rate=FLAGS.learning_rate if not FLAGS.horovod else FLAGS.learning_rate * hvd.size(),
  615. num_train_steps=num_train_steps,
  616. num_warmup_steps=num_warmup_steps,
  617. use_one_hot_embeddings=False,
  618. hvd=None if not FLAGS.horovod else hvd,
  619. amp=FLAGS.amp)
  620. estimator = tf.estimator.Estimator(
  621. model_fn=model_fn,
  622. config=run_config)
  623. if FLAGS.do_train:
  624. #train_file = os.path.join(FLAGS.output_dir, "train.tf_record")
  625. #filed_based_convert_examples_to_features(
  626. # train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file)
  627. filed_based_convert_examples_to_features(
  628. train_examples[start_index:end_index], label_list, FLAGS.max_seq_length, tokenizer, tmp_filenames[hvd_rank])
  629. tf.compat.v1.logging.info("***** Running training *****")
  630. tf.compat.v1.logging.info(" Num examples = %d", len(train_examples))
  631. tf.compat.v1.logging.info(" Batch size = %d", FLAGS.train_batch_size)
  632. tf.compat.v1.logging.info(" Num steps = %d", num_train_steps)
  633. train_input_fn = file_based_input_fn_builder(
  634. input_file=tmp_filenames, #train_file,
  635. batch_size=FLAGS.train_batch_size,
  636. seq_length=FLAGS.max_seq_length,
  637. is_training=True,
  638. drop_remainder=True,
  639. hvd=None if not FLAGS.horovod else hvd)
  640. #estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
  641. train_start_time = time.time()
  642. estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=training_hooks)
  643. train_time_elapsed = time.time() - train_start_time
  644. train_time_wo_overhead = training_hooks[-1].total_time
  645. avg_sentences_per_second = num_train_steps * global_batch_size * 1.0 / train_time_elapsed
  646. ss_sentences_per_second = (num_train_steps - training_hooks[-1].skipped) * global_batch_size * 1.0 / train_time_wo_overhead
  647. if master_process:
  648. tf.compat.v1.logging.info("-----------------------------")
  649. tf.compat.v1.logging.info("Total Training Time = %0.2f for Sentences = %d", train_time_elapsed,
  650. num_train_steps * global_batch_size)
  651. tf.compat.v1.logging.info("Total Training Time W/O Overhead = %0.2f for Sentences = %d", train_time_wo_overhead,
  652. (num_train_steps - training_hooks[-1].skipped) * global_batch_size)
  653. tf.compat.v1.logging.info("Throughput Average (sentences/sec) with overhead = %0.2f", avg_sentences_per_second)
  654. tf.compat.v1.logging.info("Throughput Average (sentences/sec) = %0.2f", ss_sentences_per_second)
  655. dllogging.logger.log(step=(), data={"throughput_train": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT)
  656. tf.compat.v1.logging.info("-----------------------------")
  657. if FLAGS.do_eval and master_process:
  658. eval_examples = processor.get_dev_examples(FLAGS.data_dir)
  659. eval_file = os.path.join(FLAGS.output_dir, "eval.tf_record")
  660. filed_based_convert_examples_to_features(
  661. eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file)
  662. tf.compat.v1.logging.info("***** Running evaluation *****")
  663. tf.compat.v1.logging.info(" Num examples = %d", len(eval_examples))
  664. tf.compat.v1.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
  665. eval_steps = None
  666. eval_drop_remainder = False
  667. eval_input_fn = file_based_input_fn_builder(
  668. input_file=eval_file,
  669. batch_size=FLAGS.eval_batch_size,
  670. seq_length=FLAGS.max_seq_length,
  671. is_training=False,
  672. drop_remainder=eval_drop_remainder)
  673. result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)
  674. output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
  675. with tf.io.gfile.Open(output_eval_file, "w") as writer:
  676. tf.compat.v1.logging.info("***** Eval results *****")
  677. for key in sorted(result.keys()):
  678. tf.compat.v1.logging.info(" %s = %s", key, str(result[key]))
  679. dllogging.logger.log(step=(), data={key: float(strresult[key])}, verbosity=Verbosity.DEFAULT)
  680. writer.write("%s = %s\n" % (key, str(result[key])))
  681. if FLAGS.do_predict and master_process:
  682. predict_examples = processor.get_test_examples(FLAGS.data_dir)
  683. predict_file = os.path.join(FLAGS.output_dir, "predict.tf_record")
  684. filed_based_convert_examples_to_features(predict_examples, label_list,
  685. FLAGS.max_seq_length, tokenizer,
  686. predict_file, mode="test")
  687. with tf.io.gfile.Open(os.path.join(FLAGS.output_dir, 'label2id.pkl'), 'rb') as rf:
  688. label2id = pickle.load(rf)
  689. id2label = {value: key for key, value in label2id.items()}
  690. token_path = os.path.join(FLAGS.output_dir, "token_test.txt")
  691. if tf.io.gfile.Exists(token_path):
  692. tf.io.gfile.Remove(token_path)
  693. tf.compat.v1.logging.info("***** Running prediction*****")
  694. tf.compat.v1.logging.info(" Num examples = %d", len(predict_examples))
  695. tf.compat.v1.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
  696. predict_drop_remainder = False
  697. predict_input_fn = file_based_input_fn_builder(
  698. input_file=predict_file,
  699. batch_size=FLAGS.predict_batch_size,
  700. seq_length=FLAGS.max_seq_length,
  701. is_training=False,
  702. drop_remainder=predict_drop_remainder)
  703. eval_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)]
  704. eval_start_time = time.time()
  705. output_predict_file = os.path.join(FLAGS.output_dir, "label_test.txt")
  706. test_labels_file = os.path.join(FLAGS.output_dir, "test_labels.txt")
  707. test_labels_err_file = os.path.join(FLAGS.output_dir, "test_labels_errs.txt")
  708. with tf.io.gfile.Open(output_predict_file, 'w') as writer, \
  709. tf.io.gfile.Open(test_labels_file, 'w') as tl, \
  710. tf.io.gfile.Open(test_labels_err_file, 'w') as tle:
  711. print(id2label)
  712. i=0
  713. for prediction in estimator.predict(input_fn=predict_input_fn, hooks=eval_hooks,
  714. yield_single_examples=True):
  715. output_line = "\n".join(id2label[id] for id in prediction if id != 0) + "\n"
  716. writer.write(output_line)
  717. result_to_pair(predict_examples[i], prediction, id2label, tl, tle)
  718. i = i + 1
  719. eval_time_elapsed = time.time() - eval_start_time
  720. time_list = eval_hooks[-1].time_list
  721. time_list.sort()
  722. # Removing outliers (init/warmup) in throughput computation.
  723. eval_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.99)])
  724. num_sentences = (int(len(time_list) * 0.99)) * FLAGS.predict_batch_size
  725. avg = np.mean(time_list)
  726. cf_50 = max(time_list[:int(len(time_list) * 0.50)])
  727. cf_90 = max(time_list[:int(len(time_list) * 0.90)])
  728. cf_95 = max(time_list[:int(len(time_list) * 0.95)])
  729. cf_99 = max(time_list[:int(len(time_list) * 0.99)])
  730. cf_100 = max(time_list[:int(len(time_list) * 1)])
  731. ss_sentences_per_second = num_sentences * 1.0 / eval_time_wo_overhead
  732. tf.compat.v1.logging.info("-----------------------------")
  733. tf.compat.v1.logging.info("Total Inference Time = %0.2f for Sentences = %d", eval_time_elapsed,
  734. eval_hooks[-1].count * FLAGS.predict_batch_size)
  735. tf.compat.v1.logging.info("Total Inference Time W/O Overhead = %0.2f for Sentences = %d", eval_time_wo_overhead,
  736. num_sentences)
  737. tf.compat.v1.logging.info("Summary Inference Statistics")
  738. tf.compat.v1.logging.info("Batch size = %d", FLAGS.predict_batch_size)
  739. tf.compat.v1.logging.info("Sequence Length = %d", FLAGS.max_seq_length)
  740. tf.compat.v1.logging.info("Precision = %s", "fp16" if FLAGS.amp else "fp32")
  741. tf.compat.v1.logging.info("Latency Confidence Level 50 (ms) = %0.2f", cf_50 * 1000)
  742. tf.compat.v1.logging.info("Latency Confidence Level 90 (ms) = %0.2f", cf_90 * 1000)
  743. tf.compat.v1.logging.info("Latency Confidence Level 95 (ms) = %0.2f", cf_95 * 1000)
  744. tf.compat.v1.logging.info("Latency Confidence Level 99 (ms) = %0.2f", cf_99 * 1000)
  745. tf.compat.v1.logging.info("Latency Confidence Level 100 (ms) = %0.2f", cf_100 * 1000)
  746. tf.compat.v1.logging.info("Latency Average (ms) = %0.2f", avg * 1000)
  747. tf.compat.v1.logging.info("Throughput Average (sentences/sec) = %0.2f", ss_sentences_per_second)
  748. dllogging.logger.log(step=(), data={"throughput_val": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT)
  749. tf.compat.v1.logging.info("-----------------------------")
  750. tf.compat.v1.logging.info('Reading: %s', test_labels_file)
  751. with tf.io.gfile.Open(test_labels_file, "r") as f:
  752. counts = evaluate(f)
  753. eval_result = report_notprint(counts)
  754. print(''.join(eval_result))
  755. with tf.io.gfile.Open(os.path.join(FLAGS.output_dir, 'test_results_conlleval.txt'), 'w') as fd:
  756. fd.write(''.join(eval_result))
  757. if __name__ == "__main__":
  758. flags.mark_flag_as_required("data_dir")
  759. flags.mark_flag_as_required("task_name")
  760. flags.mark_flag_as_required("vocab_file")
  761. flags.mark_flag_as_required("bert_config_file")
  762. flags.mark_flag_as_required("output_dir")
  763. tf.compat.v1.app.run()