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, setup_xla_flags
  24. from utils.gpu_affinity import set_affinity
  25. import utils.dllogger_class
  26. from dllogger import Verbosity
  27. flags = tf.flags
  28. FLAGS = flags.FLAGS
  29. flags.DEFINE_string(
  30. "task_name", "NER", "The name of the task to train."
  31. )
  32. flags.DEFINE_string(
  33. "data_dir", None,
  34. "The input datadir.",
  35. )
  36. flags.DEFINE_string(
  37. "output_dir", None,
  38. "The output directory where the model checkpoints will be written."
  39. )
  40. flags.DEFINE_string(
  41. "bert_config_file", None,
  42. "The config json file corresponding to the pre-trained BERT model."
  43. )
  44. flags.DEFINE_string(
  45. "vocab_file", None,
  46. "The vocabulary file that the BERT model was trained on.")
  47. flags.DEFINE_string(
  48. "dllog_path", "/results/bert_dllog.json",
  49. "filename where dllogger writes to")
  50. flags.DEFINE_string(
  51. "init_checkpoint", None,
  52. "Initial checkpoint (usually from a pre-trained BERT model)."
  53. )
  54. flags.DEFINE_bool(
  55. "do_lower_case", False,
  56. "Whether to lower case the input text."
  57. )
  58. flags.DEFINE_integer(
  59. "max_seq_length", 128,
  60. "The maximum total input sequence length after WordPiece tokenization."
  61. )
  62. flags.DEFINE_bool(
  63. "do_train", False,
  64. "Whether to run training."
  65. )
  66. flags.DEFINE_bool(
  67. "do_eval", False,
  68. "Whether to run eval on the dev set.")
  69. flags.DEFINE_bool(
  70. "do_predict", False,
  71. "Whether to run the model in inference mode on the test set.")
  72. flags.DEFINE_integer(
  73. "train_batch_size", 64,
  74. "Total batch size for training.")
  75. flags.DEFINE_integer(
  76. "eval_batch_size", 16,
  77. "Total batch size for eval.")
  78. flags.DEFINE_integer(
  79. "predict_batch_size", 16,
  80. "Total batch size for predict.")
  81. flags.DEFINE_float(
  82. "learning_rate", 5e-6,
  83. "The initial learning rate for Adam.")
  84. flags.DEFINE_float(
  85. "num_train_epochs", 10.0,
  86. "Total number of training epochs to perform.")
  87. flags.DEFINE_float(
  88. "warmup_proportion", 0.1,
  89. "Proportion of training to perform linear learning rate warmup for. "
  90. "E.g., 0.1 = 10% of training.")
  91. flags.DEFINE_integer(
  92. "save_checkpoints_steps", 1000,
  93. "How often to save the model checkpoint.")
  94. flags.DEFINE_integer(
  95. "iterations_per_loop", 1000,
  96. "How many steps to make in each estimator call.")
  97. tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
  98. flags.DEFINE_bool("horovod", False, "Whether to use Horovod for multi-gpu runs")
  99. flags.DEFINE_bool("amp", True, "Whether to enable AMP ops. When false, uses TF32 on A100 and FP32 on V100 GPUS.")
  100. flags.DEFINE_bool("use_xla", True, "Whether to enable XLA JIT compilation.")
  101. class InputExample(object):
  102. """A single training/test example for simple sequence classification."""
  103. def __init__(self, guid, text, label=None):
  104. """Constructs a InputExample.
  105. Args:
  106. guid: Unique id for the example.
  107. text_a: string. The untokenized text of the first sequence. For single
  108. sequence tasks, only this sequence must be specified.
  109. label: (Optional) string. The label of the example. This should be
  110. specified for train and dev examples, but not for test examples.
  111. """
  112. self.guid = guid
  113. self.text = text
  114. self.label = label
  115. class InputFeatures(object):
  116. """A single set of features of data."""
  117. def __init__(self, input_ids, input_mask, segment_ids, label_ids, ):
  118. self.input_ids = input_ids
  119. self.input_mask = input_mask
  120. self.segment_ids = segment_ids
  121. self.label_ids = label_ids
  122. # self.label_mask = label_mask
  123. class DataProcessor(object):
  124. """Base class for data converters for sequence classification data sets."""
  125. def get_train_examples(self, data_dir):
  126. """Gets a collection of `InputExample`s for the train set."""
  127. raise NotImplementedError()
  128. def get_dev_examples(self, data_dir):
  129. """Gets a collection of `InputExample`s for the dev set."""
  130. raise NotImplementedError()
  131. def get_labels(self):
  132. """Gets the list of labels for this data set."""
  133. raise NotImplementedError()
  134. @classmethod
  135. def _read_data(cls, input_file):
  136. """Reads a BIO data."""
  137. with open(input_file, "r") as f:
  138. lines = []
  139. words = []
  140. labels = []
  141. for line in f:
  142. contends = line.strip()
  143. if len(contends) == 0:
  144. assert len(words) == len(labels)
  145. if len(words) > 30:
  146. # split if the sentence is longer than 30
  147. while len(words) > 30:
  148. tmplabel = labels[:30]
  149. for iidx in range(len(tmplabel)):
  150. if tmplabel.pop() == 'O':
  151. break
  152. l = ' '.join(
  153. [label for label in labels[:len(tmplabel) + 1] if len(label) > 0])
  154. w = ' '.join(
  155. [word for word in words[:len(tmplabel) + 1] if len(word) > 0])
  156. lines.append([l, w])
  157. words = words[len(tmplabel) + 1:]
  158. labels = labels[len(tmplabel) + 1:]
  159. if len(words) == 0:
  160. continue
  161. l = ' '.join([label for label in labels if len(label) > 0])
  162. w = ' '.join([word for word in words if len(word) > 0])
  163. lines.append([l, w])
  164. words = []
  165. labels = []
  166. continue
  167. word = line.strip().split()[0]
  168. label = line.strip().split()[-1]
  169. words.append(word)
  170. labels.append(label)
  171. return lines
  172. class BC5CDRProcessor(DataProcessor):
  173. def get_train_examples(self, data_dir):
  174. l1 = self._read_data(os.path.join(data_dir, "train.tsv"))
  175. l2 = self._read_data(os.path.join(data_dir, "devel.tsv"))
  176. return self._create_example(l1 + l2, "train")
  177. def get_dev_examples(self, data_dir, file_name="devel.tsv"):
  178. return self._create_example(
  179. self._read_data(os.path.join(data_dir, file_name)), "dev"
  180. )
  181. def get_test_examples(self, data_dir, file_name="test.tsv"):
  182. return self._create_example(
  183. self._read_data(os.path.join(data_dir, file_name)), "test")
  184. def get_labels(self):
  185. return ["B", "I", "O", "X", "[CLS]", "[SEP]"]
  186. def _create_example(self, lines, set_type):
  187. examples = []
  188. for (i, line) in enumerate(lines):
  189. guid = "%s-%s" % (set_type, i)
  190. text = tokenization.convert_to_unicode(line[1])
  191. label = tokenization.convert_to_unicode(line[0])
  192. examples.append(InputExample(guid=guid, text=text, label=label))
  193. return examples
  194. class CLEFEProcessor(DataProcessor):
  195. def get_train_examples(self, data_dir):
  196. lines1 = self._read_data2(os.path.join(data_dir, "Training.tsv"))
  197. lines2 = self._read_data2(os.path.join(data_dir, "Development.tsv"))
  198. return self._create_example(
  199. lines1 + lines2, "train"
  200. )
  201. def get_dev_examples(self, data_dir, file_name="Development.tsv"):
  202. return self._create_example(
  203. self._read_data2(os.path.join(data_dir, file_name)), "dev"
  204. )
  205. def get_test_examples(self, data_dir, file_name="Test.tsv"):
  206. return self._create_example(
  207. self._read_data2(os.path.join(data_dir, file_name)), "test")
  208. def get_labels(self):
  209. return ["B", "I", "O", "X", "[CLS]", "[SEP]"]
  210. def _create_example(self, lines, set_type):
  211. examples = []
  212. for (i, line) in enumerate(lines):
  213. guid = "%s-%s" % (set_type, i)
  214. text = tokenization.convert_to_unicode(line[1])
  215. label = tokenization.convert_to_unicode(line[0])
  216. examples.append(InputExample(guid=guid, text=text, label=label))
  217. return examples
  218. @classmethod
  219. def _read_data2(cls, input_file):
  220. with tf.io.gfile.GFile(input_file, "r") as f:
  221. lines = []
  222. words = []
  223. labels = []
  224. for line in f:
  225. contends = line.strip()
  226. if len(contends) == 0:
  227. assert len(words) == len(labels)
  228. if len(words) == 0:
  229. continue
  230. l = ' '.join([label for label in labels if len(label) > 0])
  231. w = ' '.join([word for word in words if len(word) > 0])
  232. lines.append([l, w])
  233. words = []
  234. labels = []
  235. continue
  236. elif contends.startswith('###'):
  237. continue
  238. word = line.strip().split()[0]
  239. label = line.strip().split()[-1]
  240. words.append(word)
  241. labels.append(label)
  242. return lines
  243. class I2b22012Processor(CLEFEProcessor):
  244. def get_labels(self):
  245. 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]"]
  246. def write_tokens(tokens, labels, mode):
  247. if mode == "test":
  248. path = os.path.join(FLAGS.output_dir, "token_" + mode + ".txt")
  249. if tf.io.gfile.exists(path):
  250. wf = tf.io.gfile.GFile(path, 'a')
  251. else:
  252. wf = tf.io.gfile.GFile(path, 'w')
  253. for token, label in zip(tokens, labels):
  254. if token != "**NULL**":
  255. wf.write(token + ' ' + str(label) + '\n')
  256. wf.close()
  257. def convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer, mode):
  258. label_map = {}
  259. for (i, label) in enumerate(label_list, 1):
  260. label_map[label] = i
  261. label2id_file = os.path.join(FLAGS.output_dir, 'label2id.pkl')
  262. if not os.path.exists(label2id_file):
  263. with open(label2id_file, 'wb') as w:
  264. pickle.dump(label_map, w)
  265. textlist = example.text.split(' ')
  266. labellist = example.label.split(' ')
  267. tokens = []
  268. labels = []
  269. for i, word in enumerate(textlist):
  270. token = tokenizer.tokenize(word)
  271. tokens.extend(token)
  272. label_1 = labellist[i]
  273. for m in range(len(token)):
  274. if m == 0:
  275. labels.append(label_1)
  276. else:
  277. labels.append("X")
  278. # tokens = tokenizer.tokenize(example.text)
  279. if len(tokens) >= max_seq_length - 1:
  280. tokens = tokens[0:(max_seq_length - 2)]
  281. labels = labels[0:(max_seq_length - 2)]
  282. ntokens = []
  283. segment_ids = []
  284. label_ids = []
  285. ntokens.append("[CLS]")
  286. segment_ids.append(0)
  287. # append("O") or append("[CLS]") not sure!
  288. label_ids.append(label_map["[CLS]"])
  289. for i, token in enumerate(tokens):
  290. ntokens.append(token)
  291. segment_ids.append(0)
  292. label_ids.append(label_map[labels[i]])
  293. ntokens.append("[SEP]")
  294. segment_ids.append(0)
  295. # append("O") or append("[SEP]") not sure!
  296. label_ids.append(label_map["[SEP]"])
  297. input_ids = tokenizer.convert_tokens_to_ids(ntokens)
  298. input_mask = [1] * len(input_ids)
  299. # label_mask = [1] * len(input_ids)
  300. while len(input_ids) < max_seq_length:
  301. input_ids.append(0)
  302. input_mask.append(0)
  303. segment_ids.append(0)
  304. # we don't concerned about it!
  305. label_ids.append(0)
  306. ntokens.append("**NULL**")
  307. # label_mask.append(0)
  308. # print(len(input_ids))
  309. assert len(input_ids) == max_seq_length
  310. assert len(input_mask) == max_seq_length
  311. assert len(segment_ids) == max_seq_length
  312. assert len(label_ids) == max_seq_length
  313. # assert len(label_mask) == max_seq_length
  314. if ex_index < 5:
  315. tf.compat.v1.logging.info("*** Example ***")
  316. tf.compat.v1.logging.info("guid: %s" % (example.guid))
  317. tf.compat.v1.logging.info("tokens: %s" % " ".join(
  318. [tokenization.printable_text(x) for x in tokens]))
  319. tf.compat.v1.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
  320. tf.compat.v1.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
  321. tf.compat.v1.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
  322. tf.compat.v1.logging.info("label_ids: %s" % " ".join([str(x) for x in label_ids]))
  323. # tf.compat.v1.logging.info("label_mask: %s" % " ".join([str(x) for x in label_mask]))
  324. feature = InputFeatures(
  325. input_ids=input_ids,
  326. input_mask=input_mask,
  327. segment_ids=segment_ids,
  328. label_ids=label_ids,
  329. # label_mask = label_mask
  330. )
  331. # write_tokens(ntokens, label_ids, mode)
  332. return feature
  333. def filed_based_convert_examples_to_features(
  334. examples, label_list, max_seq_length, tokenizer, output_file, mode=None):
  335. writer = tf.python_io.TFRecordWriter(output_file)
  336. for (ex_index, example) in enumerate(examples):
  337. if ex_index % 5000 == 0:
  338. tf.compat.v1.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
  339. feature = convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer,
  340. mode)
  341. def create_int_feature(values):
  342. f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
  343. return f
  344. features = collections.OrderedDict()
  345. features["input_ids"] = create_int_feature(feature.input_ids)
  346. features["input_mask"] = create_int_feature(feature.input_mask)
  347. features["segment_ids"] = create_int_feature(feature.segment_ids)
  348. features["label_ids"] = create_int_feature(feature.label_ids)
  349. # features["label_mask"] = create_int_feature(feature.label_mask)
  350. tf_example = tf.train.Example(features=tf.train.Features(feature=features))
  351. writer.write(tf_example.SerializeToString())
  352. def file_based_input_fn_builder(input_file, batch_size, seq_length, is_training, drop_remainder, hvd=None):
  353. name_to_features = {
  354. "input_ids": tf.io.FixedLenFeature([seq_length], tf.int64),
  355. "input_mask": tf.io.FixedLenFeature([seq_length], tf.int64),
  356. "segment_ids": tf.io.FixedLenFeature([seq_length], tf.int64),
  357. "label_ids": tf.io.FixedLenFeature([seq_length], tf.int64),
  358. # "label_ids":tf.VarLenFeature(tf.int64),
  359. # "label_mask": tf.io.FixedLenFeature([seq_length], tf.int64),
  360. }
  361. def _decode_record(record, name_to_features):
  362. example = tf.parse_single_example(record, name_to_features)
  363. for name in list(example.keys()):
  364. t = example[name]
  365. if t.dtype == tf.int64:
  366. t = tf.to_int32(t)
  367. example[name] = t
  368. return example
  369. def input_fn(params):
  370. #batch_size = params["batch_size"]
  371. d = tf.data.TFRecordDataset(input_file)
  372. if is_training:
  373. if hvd is not None: d = d.shard(hvd.size(), hvd.rank())
  374. d = d.repeat()
  375. d = d.shuffle(buffer_size=100)
  376. d = d.apply(tf.contrib.data.map_and_batch(
  377. lambda record: _decode_record(record, name_to_features),
  378. batch_size=batch_size,
  379. drop_remainder=drop_remainder
  380. ))
  381. return d
  382. return input_fn
  383. def create_model(bert_config, is_training, input_ids, input_mask,
  384. segment_ids, labels, num_labels, use_one_hot_embeddings):
  385. model = modeling.BertModel(
  386. config=bert_config,
  387. is_training=is_training,
  388. input_ids=input_ids,
  389. input_mask=input_mask,
  390. token_type_ids=segment_ids,
  391. use_one_hot_embeddings=use_one_hot_embeddings
  392. )
  393. output_layer = model.get_sequence_output()
  394. hidden_size = output_layer.shape[-1].value
  395. output_weight = tf.get_variable(
  396. "output_weights", [num_labels, hidden_size],
  397. initializer=tf.truncated_normal_initializer(stddev=0.02)
  398. )
  399. output_bias = tf.get_variable(
  400. "output_bias", [num_labels], initializer=tf.zeros_initializer()
  401. )
  402. with tf.variable_scope("loss"):
  403. if is_training:
  404. output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
  405. output_layer = tf.reshape(output_layer, [-1, hidden_size])
  406. logits = tf.matmul(output_layer, output_weight, transpose_b=True)
  407. logits = tf.nn.bias_add(logits, output_bias)
  408. logits = tf.reshape(logits, [-1, FLAGS.max_seq_length, num_labels])
  409. # mask = tf.cast(input_mask,tf.float32)
  410. # loss = tf.contrib.seq2seq.sequence_loss(logits,labels,mask)
  411. # return (loss, logits, predict)
  412. ##########################################################################
  413. log_probs = tf.nn.log_softmax(logits, axis=-1)
  414. one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
  415. per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
  416. loss = tf.reduce_mean(per_example_loss)
  417. probabilities = tf.nn.softmax(logits, axis=-1)
  418. predict = tf.argmax(probabilities, axis=-1)
  419. return (loss, per_example_loss, logits, predict)
  420. ##########################################################################
  421. def model_fn_builder(bert_config, num_labels, init_checkpoint=None, learning_rate=None,
  422. num_train_steps=None, num_warmup_steps=None,
  423. use_one_hot_embeddings=False, hvd=None, amp=False):
  424. def model_fn(features, labels, mode, params):
  425. tf.compat.v1.logging.info("*** Features ***")
  426. for name in sorted(features.keys()):
  427. tf.compat.v1.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
  428. input_ids = features["input_ids"]
  429. input_mask = features["input_mask"]
  430. segment_ids = features["segment_ids"]
  431. label_ids = features["label_ids"]
  432. # label_mask = features["label_mask"]
  433. is_training = (mode == tf.estimator.ModeKeys.TRAIN)
  434. (total_loss, per_example_loss, logits, predicts) = create_model(
  435. bert_config, is_training, input_ids, input_mask, segment_ids, label_ids,
  436. num_labels, use_one_hot_embeddings)
  437. tvars = tf.trainable_variables()
  438. initialized_variable_names = {}
  439. scaffold_fn = None
  440. if init_checkpoint and (hvd is None or hvd.rank() == 0):
  441. (assignment_map,
  442. initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars,
  443. init_checkpoint)
  444. tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
  445. tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
  446. tf.compat.v1.logging.info("**** Trainable Variables ****")
  447. for var in tvars:
  448. init_string = ""
  449. if var.name in initialized_variable_names:
  450. init_string = ", *INIT_FROM_CKPT*"
  451. tf.compat.v1.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
  452. init_string)
  453. output_spec = None
  454. if mode == tf.estimator.ModeKeys.TRAIN:
  455. train_op = optimization.create_optimizer(
  456. total_loss, learning_rate, num_train_steps, num_warmup_steps, hvd, False, amp)
  457. output_spec = tf.estimator.EstimatorSpec(
  458. mode=mode,
  459. loss=total_loss,
  460. train_op=train_op)
  461. elif mode == tf.estimator.ModeKeys.EVAL:
  462. dummy_op = tf.no_op()
  463. # Need to call mixed precision graph rewrite if fp16 to enable graph rewrite
  464. if amp:
  465. loss_scaler = tf.train.experimental.FixedLossScale(1)
  466. dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite(
  467. optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler)
  468. def metric_fn(per_example_loss, label_ids, logits):
  469. # def metric_fn(label_ids, logits):
  470. predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
  471. precision = tf_metrics.precision(label_ids, predictions, num_labels, [1, 2], average="macro")
  472. recall = tf_metrics.recall(label_ids, predictions, num_labels, [1, 2], average="macro")
  473. f = tf_metrics.f1(label_ids, predictions, num_labels, [1, 2], average="macro")
  474. #
  475. return {
  476. "precision": precision,
  477. "recall": recall,
  478. "f1": f,
  479. }
  480. eval_metric_ops = metric_fn(per_example_loss, label_ids, logits)
  481. output_spec = tf.estimator.EstimatorSpec(
  482. mode=mode,
  483. loss=total_loss,
  484. eval_metric_ops=eval_metric_ops)
  485. else:
  486. dummy_op = tf.no_op()
  487. # Need to call mixed precision graph rewrite if fp16 to enable graph rewrite
  488. if amp:
  489. dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite(
  490. optimization.LAMBOptimizer(learning_rate=0.0))
  491. output_spec = tf.estimator.EstimatorSpec(
  492. mode=mode, predictions=predicts)#probabilities)
  493. return output_spec
  494. return model_fn
  495. def result_to_pair(predict_line, pred_ids, id2label, writer, err_writer):
  496. words = str(predict_line.text).split(' ')
  497. labels = str(predict_line.label).split(' ')
  498. if len(words) != len(labels):
  499. tf.compat.v1.logging.error('Text and label not equal')
  500. tf.compat.v1.logging.error(predict_line.text)
  501. tf.compat.v1.logging.error(predict_line.label)
  502. exit(1)
  503. # get from CLS to SEP
  504. pred_labels = []
  505. for id in pred_ids:
  506. if id == 0:
  507. continue
  508. curr_label = id2label[id]
  509. if curr_label == '[CLS]':
  510. continue
  511. elif curr_label == '[SEP]':
  512. break
  513. elif curr_label == 'X':
  514. continue
  515. pred_labels.append(curr_label)
  516. if len(pred_labels) > len(words):
  517. err_writer.write(predict_line.guid + '\n')
  518. err_writer.write(predict_line.text + '\n')
  519. err_writer.write(predict_line.label + '\n')
  520. err_writer.write(' '.join([str(i) for i in pred_ids]) + '\n')
  521. err_writer.write(' '.join([id2label.get(i, '**NULL**') for i in pred_ids]) + '\n\n')
  522. pred_labels = pred_labels[:len(words)]
  523. elif len(pred_labels) < len(words):
  524. err_writer.write(predict_line.guid + '\n')
  525. err_writer.write(predict_line.text + '\n')
  526. err_writer.write(predict_line.label + '\n')
  527. err_writer.write(' '.join([str(i) for i in pred_ids]) + '\n')
  528. err_writer.write(' '.join([id2label.get(i, '**NULL**') for i in pred_ids]) + '\n\n')
  529. pred_labels += ['O'] * (len(words) - len(pred_labels))
  530. for tok, label, pred_label in zip(words, labels, pred_labels):
  531. writer.write(tok + ' ' + label + ' ' + pred_label + '\n')
  532. writer.write('\n')
  533. def main(_):
  534. setup_xla_flags()
  535. tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO)
  536. dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path)
  537. if FLAGS.horovod:
  538. hvd.init()
  539. processors = {
  540. "bc5cdr": BC5CDRProcessor,
  541. "clefe": CLEFEProcessor,
  542. 'i2b2': I2b22012Processor
  543. }
  544. if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict:
  545. raise ValueError("At least one of `do_train` or `do_eval` must be True.")
  546. bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
  547. if FLAGS.max_seq_length > bert_config.max_position_embeddings:
  548. raise ValueError(
  549. "Cannot use sequence length %d because the BERT model "
  550. "was only trained up to sequence length %d" %
  551. (FLAGS.max_seq_length, bert_config.max_position_embeddings))
  552. task_name = FLAGS.task_name.lower()
  553. if task_name not in processors:
  554. raise ValueError("Task not found: %s" % (task_name))
  555. tf.io.gfile.makedirs(FLAGS.output_dir)
  556. processor = processors[task_name]()
  557. label_list = processor.get_labels()
  558. tokenizer = tokenization.FullTokenizer(
  559. vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
  560. is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
  561. master_process = True
  562. training_hooks = []
  563. global_batch_size = FLAGS.train_batch_size
  564. hvd_rank = 0
  565. config = tf.compat.v1.ConfigProto()
  566. if FLAGS.horovod:
  567. global_batch_size = FLAGS.train_batch_size * hvd.size()
  568. master_process = (hvd.rank() == 0)
  569. hvd_rank = hvd.rank()
  570. config.gpu_options.visible_device_list = str(hvd.local_rank())
  571. set_affinity(hvd.local_rank())
  572. if hvd.size() > 1:
  573. training_hooks.append(hvd.BroadcastGlobalVariablesHook(0))
  574. if FLAGS.use_xla:
  575. config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1
  576. if FLAGS.amp:
  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.GFile(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(str(result[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.GFile(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.GFile(output_predict_file, 'w') as writer, \
  709. tf.io.gfile.GFile(test_labels_file, 'w') as tl, \
  710. tf.io.gfile.GFile(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.GFile(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.GFile(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()