├── .ipynb_checkpoints
└── main-v2-checkpoint.ipynb
├── LICENSE
├── README.md
├── __init__.py
├── bleu.py
├── data
├── src-train.txt
├── src-val.txt
├── tgt-train.txt
└── tgt-val.txt
├── images
├── learning_rate.png
├── multi_head_attention.png
├── scaled_attention.png
└── transformer.png
├── main-v2.ipynb
├── modules_v2.py
├── old_version
├── __init__.py
├── data_loader.py
├── eval.py
├── make_dic.py
├── modules.py
├── params.py
├── requirements.txt
└── train.py
├── params.py
├── requirements.txt
├── tf1.12.0-eager
├── __init__.py
├── bleu.py
├── main.ipynb
├── modules.py
├── params.py
├── requirements.txt
└── utils.py
└── utils_v2.py
/.ipynb_checkpoints/main-v2-checkpoint.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "metadata": {},
7 | "outputs": [],
8 | "source": [
9 | "from __future__ import absolute_import, division, print_function, unicode_literals\n",
10 | "\n",
11 | "import tensorflow as tf\n",
12 | "\n",
13 | "import time\n",
14 | "import datetime\n",
15 | "import os\n",
16 | "from tqdm import tqdm\n",
17 | "import numpy as np\n",
18 | "import matplotlib.pyplot as plt\n",
19 | "plt.rcParams['font.sans-serif']=['SimHei'] # 用来正常显示中文标签\n",
20 | "plt.rcParams['axes.unicode_minus']=False\n",
21 | "\n",
22 | "os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0, 1, 2, 3\" # 添加可用的gpu\n",
23 | "physical_devices = tf.config.experimental.list_physical_devices('GPU')\n",
24 | "for device in physical_devices:\n",
25 | " tf.config.experimental.set_memory_growth(device, True)\n",
26 | "\n",
27 | "from params import Params as pm\n",
28 | "from utils_v2 import en2idx, idx2en, de2idx, idx2de, dump2record, build_dataset, LRSchedule, masking, create_masks, plot_attention_weights\n",
29 | "from bleu import bleu_metrics"
30 | ]
31 | },
32 | {
33 | "cell_type": "code",
34 | "execution_count": null,
35 | "metadata": {},
36 | "outputs": [],
37 | "source": [
38 | "tf.__version__"
39 | ]
40 | },
41 | {
42 | "cell_type": "markdown",
43 | "metadata": {},
44 | "source": [
45 | "---"
46 | ]
47 | },
48 | {
49 | "cell_type": "code",
50 | "execution_count": null,
51 | "metadata": {},
52 | "outputs": [],
53 | "source": [
54 | "strategy = tf.distribute.MirroredStrategy()\n",
55 | "\n",
56 | "print('Number of device: {}'.format(strategy.num_replicas_in_sync))"
57 | ]
58 | },
59 | {
60 | "cell_type": "code",
61 | "execution_count": null,
62 | "metadata": {},
63 | "outputs": [],
64 | "source": [
65 | "def get_data(corpus_file):\n",
66 | " return open(corpus_file, 'r', encoding='utf-8').read().splitlines()"
67 | ]
68 | },
69 | {
70 | "cell_type": "code",
71 | "execution_count": null,
72 | "metadata": {},
73 | "outputs": [],
74 | "source": [
75 | "src_train, src_val = get_data(pm.src_train), get_data(pm.src_test)\n",
76 | "tgt_train, tgt_val = get_data(pm.tgt_train), get_data(pm.tgt_test)"
77 | ]
78 | },
79 | {
80 | "cell_type": "code",
81 | "execution_count": null,
82 | "metadata": {},
83 | "outputs": [],
84 | "source": [
85 | "dump2record(pm.train_record, src_train, tgt_train)\n",
86 | "dump2record(pm.test_record, src_val, tgt_val)"
87 | ]
88 | },
89 | {
90 | "cell_type": "markdown",
91 | "metadata": {},
92 | "source": [
93 | "---"
94 | ]
95 | },
96 | {
97 | "cell_type": "code",
98 | "execution_count": null,
99 | "metadata": {},
100 | "outputs": [],
101 | "source": [
102 | "from modules_v2 import positional_encoding, scaled_dot_product_attention, multihead_attention, pointwise_feedforward, EncoderBlock, DecoderBlock, Encoder, Decoder, Transformer"
103 | ]
104 | },
105 | {
106 | "cell_type": "markdown",
107 | "metadata": {},
108 | "source": [
109 | "# Positional encoding\n",
110 | "$$\\Large{PE_{(pos, 2i)} = sin(pos / 10000^{2i / d_{model}})} $$\n",
111 | "$$\\Large{PE_{(pos, 2i+1)} = cos(pos / 10000^{2i / d_{model}})} $$"
112 | ]
113 | },
114 | {
115 | "cell_type": "code",
116 | "execution_count": null,
117 | "metadata": {},
118 | "outputs": [],
119 | "source": [
120 | "pos_encoding = positional_encoding(50, 512, True)\n",
121 | "print(pos_encoding.shape)"
122 | ]
123 | },
124 | {
125 | "cell_type": "markdown",
126 | "metadata": {},
127 | "source": [
128 | "# Masking"
129 | ]
130 | },
131 | {
132 | "cell_type": "code",
133 | "execution_count": null,
134 | "metadata": {},
135 | "outputs": [],
136 | "source": [
137 | "x = tf.constant([[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]])\n",
138 | "masking(x, task='padding')"
139 | ]
140 | },
141 | {
142 | "cell_type": "code",
143 | "execution_count": null,
144 | "metadata": {},
145 | "outputs": [],
146 | "source": [
147 | "masking(x, task='look_ahead')"
148 | ]
149 | },
150 | {
151 | "cell_type": "markdown",
152 | "metadata": {},
153 | "source": [
154 | "# Scaled dot product attention"
155 | ]
156 | },
157 | {
158 | "cell_type": "markdown",
159 | "metadata": {},
160 | "source": [
161 | "\n",
162 | "$$\\Large{Attention(Q, K, V) = softmax_k(\\frac{QK^T}{\\sqrt{d_k}}) V} $$"
163 | ]
164 | },
165 | {
166 | "cell_type": "code",
167 | "execution_count": null,
168 | "metadata": {},
169 | "outputs": [],
170 | "source": [
171 | "def print_out(q, k, v):\n",
172 | " temp_out, temp_attn = scaled_dot_product_attention(q, k, v, None)\n",
173 | " print ('Attention weights are:')\n",
174 | " print (temp_attn)\n",
175 | " print ('Output is:')\n",
176 | " print (temp_out)"
177 | ]
178 | },
179 | {
180 | "cell_type": "code",
181 | "execution_count": null,
182 | "metadata": {},
183 | "outputs": [],
184 | "source": [
185 | "np.set_printoptions(suppress=True)\n",
186 | "\n",
187 | "temp_k = tf.constant([[10,0,0],\n",
188 | " [0,10,0],\n",
189 | " [0,0,10],\n",
190 | " [0,0,10]], dtype=tf.float32)\n",
191 | "\n",
192 | "temp_v = tf.constant([[ 1,0],\n",
193 | " [ 10,0],\n",
194 | " [ 100,5],\n",
195 | " [1000,6]], dtype=tf.float32)\n",
196 | "\n",
197 | "temp_q = tf.constant([[0, 10, 0]], dtype=tf.float32)\n",
198 | "print_out(temp_q, temp_k, temp_v)"
199 | ]
200 | },
201 | {
202 | "cell_type": "code",
203 | "execution_count": null,
204 | "metadata": {},
205 | "outputs": [],
206 | "source": [
207 | "temp_q = tf.constant([[0, 0, 10]], dtype=tf.float32)\n",
208 | "print_out(temp_q, temp_k, temp_v)"
209 | ]
210 | },
211 | {
212 | "cell_type": "code",
213 | "execution_count": null,
214 | "metadata": {},
215 | "outputs": [],
216 | "source": [
217 | "temp_q = tf.constant([[0, 0, 10], [0, 10, 0], [10, 10, 0]], dtype=tf.float32)\n",
218 | "print_out(temp_q, temp_k, temp_v)"
219 | ]
220 | },
221 | {
222 | "cell_type": "markdown",
223 | "metadata": {},
224 | "source": [
225 | "# Multi-head attention"
226 | ]
227 | },
228 | {
229 | "cell_type": "markdown",
230 | "metadata": {},
231 | "source": [
232 | ""
233 | ]
234 | },
235 | {
236 | "cell_type": "markdown",
237 | "metadata": {},
238 | "source": [
239 | "- **Tips: Dimention-level split**"
240 | ]
241 | },
242 | {
243 | "cell_type": "code",
244 | "execution_count": null,
245 | "metadata": {},
246 | "outputs": [],
247 | "source": [
248 | "temp_mha = multihead_attention(d_model=512, num_heads=8)\n",
249 | "y = tf.random.uniform((1, 50, 512))\n",
250 | "out, attn = temp_mha(y, k=y, q=y, mask=None)\n",
251 | "out.shape, attn.shape"
252 | ]
253 | },
254 | {
255 | "cell_type": "markdown",
256 | "metadata": {},
257 | "source": [
258 | "# Pointwise feed forward network"
259 | ]
260 | },
261 | {
262 | "cell_type": "code",
263 | "execution_count": null,
264 | "metadata": {},
265 | "outputs": [],
266 | "source": [
267 | "sample_ffn = pointwise_feedforward(512, 2048)\n",
268 | "sample_ffn(tf.random.uniform((64, 50, 512))).shape"
269 | ]
270 | },
271 | {
272 | "cell_type": "markdown",
273 | "metadata": {},
274 | "source": [
275 | "# Whole model (Encoder & Decoder)\n",
276 | ""
277 | ]
278 | },
279 | {
280 | "cell_type": "markdown",
281 | "metadata": {},
282 | "source": [
283 | "## Encoder"
284 | ]
285 | },
286 | {
287 | "cell_type": "code",
288 | "execution_count": null,
289 | "metadata": {},
290 | "outputs": [],
291 | "source": [
292 | "sample_encoder_layer = EncoderBlock(512, 8, 2048)\n",
293 | "sample_encoder_layer_output, _ = sample_encoder_layer(tf.random.uniform((64, 43, 512)), False, None)\n",
294 | "sample_encoder_layer_output.shape"
295 | ]
296 | },
297 | {
298 | "cell_type": "markdown",
299 | "metadata": {},
300 | "source": [
301 | "## Decoder"
302 | ]
303 | },
304 | {
305 | "cell_type": "code",
306 | "execution_count": null,
307 | "metadata": {},
308 | "outputs": [],
309 | "source": [
310 | "sample_decoder_layer = DecoderBlock(512, 8, 2048)\n",
311 | "\n",
312 | "sample_decoder_layer_output, _, _ = sample_decoder_layer(\n",
313 | " tf.random.uniform((64, 50, 512)), sample_encoder_layer_output, \n",
314 | " False, None, None)\n",
315 | "\n",
316 | "sample_decoder_layer_output.shape"
317 | ]
318 | },
319 | {
320 | "cell_type": "markdown",
321 | "metadata": {},
322 | "source": [
323 | "## Packed Encoder & Decoder"
324 | ]
325 | },
326 | {
327 | "cell_type": "code",
328 | "execution_count": null,
329 | "metadata": {},
330 | "outputs": [],
331 | "source": [
332 | "sample_encoder = Encoder(num_blocks=2, d_model=512, num_heads=8, dff=2048, input_vocab_size=8500, plot_pos_embedding=False)\n",
333 | "attn_dict = {}\n",
334 | "sample_encoder_output, attn_dict = sample_encoder(tf.random.uniform((64, 62)), training=False, padding_mask=None, attn_dict=attn_dict)\n",
335 | "sample_encoder_output.shape"
336 | ]
337 | },
338 | {
339 | "cell_type": "code",
340 | "execution_count": null,
341 | "metadata": {},
342 | "outputs": [],
343 | "source": [
344 | "sample_decoder = Decoder(num_blocks=2, d_model=512, num_heads=8, dff=2048, target_vocab_size=8000, plot_pos_embedding=False)\n",
345 | "output, attn_dict = sample_decoder(tf.random.uniform((64, 26)), \n",
346 | " enc_output=sample_encoder_output, \n",
347 | " training=False, look_ahead_mask=None, \n",
348 | " padding_mask=None, attn_dict=attn_dict)\n",
349 | "output.shape, attn_dict['decoder_layer2_block'].shape"
350 | ]
351 | },
352 | {
353 | "cell_type": "markdown",
354 | "metadata": {},
355 | "source": [
356 | "# Transformer"
357 | ]
358 | },
359 | {
360 | "cell_type": "code",
361 | "execution_count": null,
362 | "metadata": {},
363 | "outputs": [],
364 | "source": [
365 | "sample_transformer = Transformer(num_blocks=2, d_model=512, num_heads=8, dff=2048, input_vocab_size=8500, target_vocab_size=8000, plot_pos_embedding=False)\n",
366 | "\n",
367 | "temp_input = tf.random.uniform((64, 62))\n",
368 | "temp_target = tf.random.uniform((64, 26))\n",
369 | "\n",
370 | "fn_out, _ = sample_transformer(temp_input, \n",
371 | " temp_target, \n",
372 | " training=False, \n",
373 | " enc_padding_mask=None, \n",
374 | " look_ahead_mask=None,\n",
375 | " dec_padding_mask=None)\n",
376 | "\n",
377 | "fn_out.shape"
378 | ]
379 | },
380 | {
381 | "cell_type": "markdown",
382 | "metadata": {},
383 | "source": [
384 | "# Training"
385 | ]
386 | },
387 | {
388 | "cell_type": "code",
389 | "execution_count": null,
390 | "metadata": {},
391 | "outputs": [],
392 | "source": [
393 | "num_layers = pm.num_block\n",
394 | "d_model = pm.d_model\n",
395 | "dff = pm.dff\n",
396 | "num_heads = pm.num_heads\n",
397 | "\n",
398 | "input_vocab_size = len(en2idx)\n",
399 | "target_vocab_size = len(de2idx)\n",
400 | "dropout_rate = pm.dropout_rate\n",
401 | "\n",
402 | "EPOCHS = pm.num_epochs"
403 | ]
404 | },
405 | {
406 | "cell_type": "markdown",
407 | "metadata": {},
408 | "source": [
409 | "- Learning rate schedule\n",
410 | "$$\\Large{lrate = d_{model}^{-0.5} * min(step{\\_}num^{-0.5}, step{\\_}num * warmup{\\_}steps^{-1.5})}$$"
411 | ]
412 | },
413 | {
414 | "cell_type": "code",
415 | "execution_count": null,
416 | "metadata": {},
417 | "outputs": [],
418 | "source": [
419 | "temp_learning_rate_schedule = LRSchedule(d_model)\n",
420 | "\n",
421 | "plt.figure(figsize=(12, 8))\n",
422 | "plt.plot(temp_learning_rate_schedule(tf.range(40000, dtype=tf.float32)))\n",
423 | "plt.ylabel(\"Learning Rate\")\n",
424 | "plt.xlabel(\"Train Step\")"
425 | ]
426 | },
427 | {
428 | "cell_type": "markdown",
429 | "metadata": {},
430 | "source": [
431 | "---"
432 | ]
433 | },
434 | {
435 | "cell_type": "code",
436 | "execution_count": null,
437 | "metadata": {},
438 | "outputs": [],
439 | "source": [
440 | "with strategy.scope():\n",
441 | " # 1、dataset\n",
442 | " ## train_dataset = build_dataset(mode='array', batch_size=pm.batch_size * strategy.num_replicas_in_sync, cache_name='train_cache.tf-data', corpus=[src_train, tgt_train], is_training=True)\n",
443 | " ## val_dataset = build_dataset(mode='array', batch_size=pm.batch_size * strategy.num_replicas_in_sync, cache_name='val_cache.tf-data', corpus=[src_val, tgt_val], is_training=True)\n",
444 | " \n",
445 | " train_dataset = build_dataset(mode='file', batch_size=pm.batch_size * strategy.num_replicas_in_sync, cache_name='train_cache.tf-data', filename=pm.train_record, is_training=True)\n",
446 | " train_dist_dataset = strategy.experimental_distribute_dataset(train_dataset)\n",
447 | " \n",
448 | " # 2、loss function\n",
449 | " loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)\n",
450 | "\n",
451 | " def loss_function(real, pred):\n",
452 | " mask = tf.math.logical_not(tf.math.equal(real, 0))\n",
453 | " loss_ = loss_object(real, pred)\n",
454 | "\n",
455 | " mask = tf.cast(mask, dtype=loss_.dtype)\n",
456 | " loss_ *= mask\n",
457 | "\n",
458 | " return tf.reduce_mean(loss_), mask\n",
459 | " \n",
460 | " # 3、metrics to track loss and accuracy\n",
461 | " train_loss = tf.keras.metrics.Mean(name='train_loss')\n",
462 | " train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')\n",
463 | " \n",
464 | " # 4、model config\n",
465 | " transformer = Transformer(num_layers, d_model, num_heads, dff, input_vocab_size, target_vocab_size, pm.plot_pos_embedding, dropout_rate)\n",
466 | " \n",
467 | " learning_rate = LRSchedule(d_model)\n",
468 | " optimizer = tf.keras.optimizers.Adam(learning_rate, beta_1=pm.beta_1, beta_2=pm.beta_2, epsilon=pm.epsilon)\n",
469 | " \n",
470 | " checkpoint_path = pm.ckpt_path\n",
471 | "\n",
472 | " ckpt = tf.train.Checkpoint(transformer=transformer, optimizer=optimizer)\n",
473 | " ckpt_manager = tf.train.CheckpointManager(ckpt, checkpoint_path, max_to_keep=5)\n",
474 | "\n",
475 | " if ckpt_manager.latest_checkpoint:\n",
476 | " ckpt.restore(ckpt_manager.latest_checkpoint)\n",
477 | " print ('Latest checkpoint restored!!')\n",
478 | " \n",
479 | " current_time = datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n",
480 | " log_dir = pm.logdir + '/gradient_tape/' + current_time\n",
481 | " summary_writer = tf.summary.create_file_writer(log_dir)\n",
482 | " \n",
483 | " # 5、train step\n",
484 | " def train_step(inp, tar):\n",
485 | " tar_inp = tar[:, :-1]\n",
486 | " tar_real = tar[:, 1:]\n",
487 | "\n",
488 | " enc_padding_mask, combined_mask, dec_padding_mask = create_masks(inp, tar_inp)\n",
489 | "\n",
490 | " with tf.GradientTape() as tape:\n",
491 | " predictions, _ = transformer(inp, \n",
492 | " tar_inp, \n",
493 | " True, \n",
494 | " enc_padding_mask, \n",
495 | " combined_mask, \n",
496 | " dec_padding_mask)\n",
497 | "\n",
498 | " loss, istarget = loss_function(tar_real, predictions)\n",
499 | "\n",
500 | " gradients = tape.gradient(loss, transformer.trainable_variables) \n",
501 | " optimizer.apply_gradients(zip(gradients, transformer.trainable_variables))\n",
502 | "\n",
503 | " train_accuracy(tar_real, predictions, sample_weight=istarget)\n",
504 | " \n",
505 | " return loss\n",
506 | " \n",
507 | " @tf.function\n",
508 | " def distributed_train_step(inp, tar):\n",
509 | " per_replica_losses = strategy.experimental_run_v2(train_step, \n",
510 | " args=(inp, tar, ))\n",
511 | " return strategy.reduce(tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None)\n",
512 | " \n",
513 | " # 6、for loop\n",
514 | " total_steps = 0\n",
515 | " for epoch in range(EPOCHS):\n",
516 | " start = time.time()\n",
517 | "\n",
518 | " train_loss.reset_states()\n",
519 | " train_accuracy.reset_states()\n",
520 | " \n",
521 | " total_loss = 0.0\n",
522 | " num_batches = 0\n",
523 | " for (batch, (inp, tar)) in enumerate(train_dataset):\n",
524 | " total_loss += distributed_train_step(inp, tar)\n",
525 | " num_batches += 1\n",
526 | " total_steps += 1\n",
527 | "\n",
528 | " if batch % 500 == 0:\n",
529 | " with summary_writer.as_default():\n",
530 | " tf.summary.scalar('loss', total_loss / num_batches, step=total_steps)\n",
531 | " tf.summary.scalar('accuracy', train_accuracy.result() * 100, step=total_steps)\n",
532 | " \n",
533 | " print ('Epoch {} Batch {} Loss {:.4f} Accuracy {:.4f}'.format(\n",
534 | " epoch + 1, batch, total_loss / num_batches, train_accuracy.result() * 100))\n",
535 | " \n",
536 | " train_loss(total_loss / num_batches)\n",
537 | "\n",
538 | " if (epoch + 1) % 5 == 0:\n",
539 | " ckpt_save_path = ckpt_manager.save()\n",
540 | " print ('Saving checkpoint for epoch {} at {}'.format(epoch + 1, ckpt_save_path))\n",
541 | "\n",
542 | " print ('Epoch {} Loss {:.4f} Accuracy {:.4f}'.format(epoch + 1, train_loss.result(), train_accuracy.result() * 100))\n",
543 | " print ('Time taken for 1 epoch: {} secs\\n'.format(time.time() - start))"
544 | ]
545 | },
546 | {
547 | "cell_type": "markdown",
548 | "metadata": {},
549 | "source": [
550 | "---"
551 | ]
552 | },
553 | {
554 | "cell_type": "code",
555 | "execution_count": null,
556 | "metadata": {},
557 | "outputs": [],
558 | "source": [
559 | "val_dataset = build_dataset(mode='file', batch_size=pm.batch_size * strategy.num_replicas_in_sync, cache_name='val_cache.tf-data', filename=pm.test_record, is_training=True)"
560 | ]
561 | },
562 | {
563 | "cell_type": "code",
564 | "execution_count": null,
565 | "metadata": {},
566 | "outputs": [],
567 | "source": [
568 | "def evaluate(inp_sentence):\n",
569 | " encoder_input = inp_sentence\n",
570 | " \n",
571 | " decoder_input = [2]\n",
572 | " output = tf.expand_dims(decoder_input, 0)\n",
573 | " output = tf.tile(output, [tf.shape(encoder_input)[0], 1])\n",
574 | "\n",
575 | " for i in range(pm.maxlen):\n",
576 | " enc_padding_mask, combined_mask, dec_padding_mask = create_masks(encoder_input, output)\n",
577 | "\n",
578 | " predictions, attention_weights = transformer(encoder_input, \n",
579 | " output,\n",
580 | " False,\n",
581 | " enc_padding_mask,\n",
582 | " combined_mask,\n",
583 | " dec_padding_mask)\n",
584 | "\n",
585 | " predictions = predictions[: ,-1:, :]\n",
586 | " predicted_id = tf.cast(tf.argmax(predictions, axis=-1), tf.int32)\n",
587 | "\n",
588 | " output = tf.concat([output, predicted_id], axis=-1)\n",
589 | "\n",
590 | " return output, attention_weights"
591 | ]
592 | },
593 | {
594 | "cell_type": "code",
595 | "execution_count": null,
596 | "metadata": {},
597 | "outputs": [],
598 | "source": [
599 | "def cut_by_end(samples):\n",
600 | " output_list = np.zeros(tf.shape(samples))\n",
601 | " for i, sample in enumerate(samples):\n",
602 | " dtype = sample.dtype\n",
603 | " idx = tf.where(tf.equal(sample, 3))\n",
604 | " \n",
605 | " flag = tf.where(tf.equal(tf.size(idx), 0), 1, 0)\n",
606 | " if flag:\n",
607 | " output_list[i] = sample\n",
608 | " else:\n",
609 | " indices = tf.cast(idx[0, 0], dtype)\n",
610 | " output_list[i] = tf.concat([sample[:indices], tf.zeros(tf.shape(sample)[0] - indices, dtype=dtype)], axis=0)\n",
611 | "\n",
612 | " return tf.cast(output_list, dtype)"
613 | ]
614 | },
615 | {
616 | "cell_type": "code",
617 | "execution_count": null,
618 | "metadata": {},
619 | "outputs": [],
620 | "source": [
621 | "eval_log = os.path.join(pm.eval_log_path, '{}_eval.tsv'.format(pm.project_name))\n",
622 | "if not os.path.exists(pm.eval_log_path):\n",
623 | " os.makedirs(pm.eval_log_path)\n",
624 | "eval_file = open(eval_log, 'w', encoding='utf-8')\n",
625 | "\n",
626 | "start = time.time()\n",
627 | "count, scores = 0, 0\n",
628 | "for (batch, (inp, tar)) in enumerate(val_dataset):\n",
629 | " prediction, attention_weights = evaluate(inp)\n",
630 | " prediction = cut_by_end(prediction)\n",
631 | " \n",
632 | " preds, tars = [], []\n",
633 | " for source, real_tar, pred in zip(inp, tar, prediction):\n",
634 | " s = \" \".join([idx2en.get(i, 1) for i in source.numpy() if i < len(idx2en) and i not in [0, 2, 3]])\n",
635 | " t = \"\".join([idx2de.get(i, 1) for i in real_tar.numpy() if i < len(idx2de) and i not in [0, 2, 3]])\n",
636 | " p = \"\".join([idx2de.get(i, 1) for i in pred.numpy() if i < len(idx2de) and i not in [0, 2, 3]])\n",
637 | " \n",
638 | " preds.append(p)\n",
639 | " tars.append([t])\n",
640 | " \n",
641 | " eval_file.write('-Source : {}\\n-Target : {}\\n-Pred : {}\\n\\n'.format(s, t, p))\n",
642 | " eval_file.flush()\n",
643 | " \n",
644 | " scores += bleu_metrics(tars, preds, False, 3, True)\n",
645 | " count += 1\n",
646 | "\n",
647 | "eval_file.write('-BLEU Score : {:.4f}'.format(scores / count))\n",
648 | "eval_file.close()\n",
649 | "\n",
650 | "print(\"MSG : Done for evalutation ... Totolly {:.2f} sec.\".format(time.time() - start))"
651 | ]
652 | },
653 | {
654 | "cell_type": "code",
655 | "execution_count": null,
656 | "metadata": {},
657 | "outputs": [],
658 | "source": [
659 | "def predict(inp_sentence):\n",
660 | " start_token = [2]\n",
661 | " end_token = [3]\n",
662 | "\n",
663 | " inp_sentence = start_token + [en2idx.get(word, 1) for word in inp_sentence.split()] + end_token\n",
664 | " encoder_input = tf.expand_dims(inp_sentence, 0)\n",
665 | " \n",
666 | " decoder_input = [2]\n",
667 | " output = tf.expand_dims(decoder_input, 0)\n",
668 | "\n",
669 | " for i in range(pm.maxlen):\n",
670 | " enc_padding_mask, combined_mask, dec_padding_mask = create_masks(encoder_input, output)\n",
671 | "\n",
672 | " predictions, attention_weights = transformer(encoder_input, \n",
673 | " output,\n",
674 | " False,\n",
675 | " enc_padding_mask,\n",
676 | " combined_mask,\n",
677 | " dec_padding_mask)\n",
678 | "\n",
679 | " predictions = predictions[: ,-1:, :]\n",
680 | " predicted_id = tf.cast(tf.argmax(predictions, axis=-1), tf.int32)\n",
681 | "\n",
682 | " if tf.equal(predicted_id, 3):\n",
683 | " return tf.squeeze(output, axis=0), attention_weights\n",
684 | "\n",
685 | " output = tf.concat([output, predicted_id], axis=-1)\n",
686 | "\n",
687 | " return tf.squeeze(output, axis=0), attention_weights"
688 | ]
689 | },
690 | {
691 | "cell_type": "code",
692 | "execution_count": null,
693 | "metadata": {},
694 | "outputs": [],
695 | "source": [
696 | "def translate(sentence, plot=''):\n",
697 | " result, attention_weights = predict(sentence)\n",
698 | " \n",
699 | " predicted_sentence = [idx2de.get(i, 1) for i in result.numpy() if i < len(idx2de) and i not in [0, 2, 3]]\n",
700 | "\n",
701 | " print('Input: {}'.format(sentence))\n",
702 | " print('Predicted translation: {}'.format(\" \".join(predicted_sentence)))\n",
703 | "\n",
704 | " if plot:\n",
705 | " plot_attention_weights(attention_weights, sentence, result, plot)"
706 | ]
707 | },
708 | {
709 | "cell_type": "code",
710 | "execution_count": null,
711 | "metadata": {},
712 | "outputs": [],
713 | "source": [
714 | "translate(\"明 天 就 要 上 班 了\", plot='decoder_layer4_block')\n",
715 | "print(\"Real translation: 還好我沒工作QQ\")"
716 | ]
717 | },
718 | {
719 | "cell_type": "code",
720 | "execution_count": null,
721 | "metadata": {},
722 | "outputs": [],
723 | "source": []
724 | }
725 | ],
726 | "metadata": {
727 | "kernelspec": {
728 | "display_name": "Python 3",
729 | "language": "python",
730 | "name": "python3"
731 | },
732 | "language_info": {
733 | "codemirror_mode": {
734 | "name": "ipython",
735 | "version": 3
736 | },
737 | "file_extension": ".py",
738 | "mimetype": "text/x-python",
739 | "name": "python",
740 | "nbconvert_exporter": "python",
741 | "pygments_lexer": "ipython3",
742 | "version": "3.7.1"
743 | }
744 | },
745 | "nbformat": 4,
746 | "nbformat_minor": 2
747 | }
748 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | An Implementation of Attention is all you need with Chinese Corpus
2 | ===
3 | The code is an implementation of Paper [Attention is all you need](https://arxiv.org/abs/1706.03762) working for dialogue generation tasks like: **Chatbot**、 **Text Generation** and so on.
4 | **Thanks to every friends who have raised issues and helped solve them. Your contribution is very important for the improvement of this project. Due to the limited support of the 'static graph mode' in coding, we decided to move the features to 2.0.0-beta1 version. However if you worry about the problems from docker building and service creation with version issues, we still keep an old version of the code written by eager mode using tensorflow 1.12.x version to refer.**
5 |
6 | # Documents
7 | ```
8 | |-- root/
9 | |-- data/
10 | |-- src-train.csv
11 | |-- src-val.csv
12 | |-- tgt-train.csv
13 | `-- tgt-val.csv
14 | |-- old_version/
15 | |-- data_loader.py
16 | |-- eval.py
17 | |-- make_dic.py
18 | |-- modules.py
19 | |-- params.py
20 | |-- requirements.txt
21 | `-- train.py
22 | |-- tf1.12.0-eager/
23 | |-- bleu.py
24 | |-- main.ipynb
25 | |-- modules.py
26 | |-- params.py
27 | |-- requirements.txt
28 | `-- utils.py
29 | |-- images/
30 | |-- bleu.py
31 | |-- main-v2.ipynb
32 | |-- modules-v2.py
33 | |-- params.py
34 | |-- requirements.txt
35 | `-- utils-v2.py
36 | ```
37 |
38 | # Requirements
39 | - Numpy >= 1.13.1
40 | - Tensorflow-gpu == 1.12.0
41 | - **Tensorflow-gpu == 2.0.0-beta1**
42 | - cudatoolkit >= 10.0
43 | - cudnn >= 7.4
44 | - nvidia cuda driver version >= 410.x
45 | - tqdm
46 | - nltk
47 | - jupyter notebook
48 |
49 | # Construction
50 | As we all know the Translation System can be used in implementing conversational model just by replacing the paris of two different sentences to questions and answers. After all, the basic conversation model named "Sequence-to-Sequence" is develped from translation system. Therefore, why we not to improve the efficiency of conversation model in generating dialogues?
51 |
52 |
53 |

54 |
55 |
56 | With the development of [BERT-based models](https://arxiv.org/abs/1810.04805), more and more nlp tasks are refreshed constantly. However, the language model is not contained in BERT's open source tasks. There is no doubt that on this way we still have a long way to go.
57 |
58 | ## Model Advantages
59 | A transformer model handles variable-sized input using stacks of self-attention layers instead of RNNs or CNNs. This general architecture has a number of advantages and special ticks. Now let's take them out:
60 |
61 | - It make no assumptions about the temporal/spatial relationships across the data.(However this was proved to be not sure from AutoML)
62 | - Layer outputs can be calculated in parallel, instead of a series like an RNN.(Faster training)
63 | - Distant items can affect each other's output without passing through many RNN-steps, or CNN layers.(Lower cost)
64 | - It can learn long-range dependencies, which is a challenge of dialogue system.
65 |
66 | ## Implementation details
67 | **In the newest version of our code**, we complete the details described in paper.
68 |
69 | ### Data Generation
70 | - Use tfrecord to unified data storage format.
71 | - Use dataset to load the processed chinese token datasets.
72 |
73 | ### Positional Encoding
74 | - Since the model doesn't contain any memory mechanism, positional encoding is added to give it some information about the relative position of the words in the sentence by representing a token into a d-dimensional space where tokens with similar meaning will be closer to each other.
75 |
76 |
77 |
} = sin(pos / 10000^{2i / d_{model}})})
78 |
79 |
80 |
81 |
} = cos(pos / 10000^{2i / d_{model}})})
82 |
83 |
84 | ### Mask
85 | - We create two different type of mask during training. One is for the padding masking, the other is for the decoder look_ahead masking to keep the following tokens invisible when generating the previous ones.
86 |
87 | ### Scaled dot product attention
88 | - The attention function used by the transformer takes three inputs: Q,K,V. The equation used to calculate the attention weights, which is scaled by a factor of square root of the depth is:
89 |
90 |
91 |
 = softmax_k(\frac{QK^T}{\sqrt{d_k}}) V})
92 |
93 |
94 |
95 |

96 |
97 |
98 | ### Multi-head attention
99 | - Multi-head attention consists of four parts: **Linear layers**、**Multi-head attention**、**Concatenation of heads** and **Final linear layers**.
100 |
101 |
102 |

103 |
104 |
105 | ### Pointwise Feedforward Network
106 | - Pointwise feedforward network consists of two fully-connected layers with ReLU activation in between.
107 |
108 | ### Learning Rate Schedule
109 | - Use the adam optimizer with a custom learning rate scheduler according to the formula like:
110 |
111 |
112 |
})
113 |
114 |
115 |
116 |

117 |
118 |
119 |
120 | ## Model Downsides
121 | However, such a strong architecture still have some downsides:
122 | - For a time-series, the output for a time-step is calculated from the entire history of only the inputs and current hidden-state(Just like the different between CRF & HMM). So that it may be less efficient.
123 | - As the first part above said, if the input does have a temporal/spatial relationship, like text generation task, the model may be lost in the context.
124 |
125 | # Usage
126 | - old_version
127 | - STEP 1. Download dialogue corpus with format like sample datasets and extract them to `data/` folder.
128 | - STEP 2. Adjust hyper parameters in `params.py` if you want.
129 | - STEP 3. Run `make_dic.py` to generate vocabulary files to a new folder named `dictionary`.
130 | - STEP 4. Run `train.py` to build the model. Checkpoint will be stored in `checkpoint` folder while the tensorflow event files can be found in `logdir`.
131 | - STEP 5. Run `eval.py` to evaluate the result with testing data. Result will be stored in `Results` folder.
132 | - new_version(2.0 & 1.12.x with eager mode)
133 | - follow the .ipynb to run train & eval & demo
134 | - if you use `GPU` to speed up training processing, please set up your device in the code.(It support multi-workers training)
135 |
136 | # Results
137 | - demo
138 | ```
139 | - Source: 肥 宅 初 夜 可 以 賣 多 少 `
140 | - Ground Truth: 肥 宅 還 是 去 打 手 槍 吧
141 | - Predict: 肥 宅 還 是 去 打 手 槍 吧
142 |
143 | - Source: 兇 的 女 生 484 都 很 胸
144 | - Ground Truth: 我 看 都 是 醜 的 比 較 凶
145 | - Predict: 我 看 都 是 醜 的 比 較
146 |
147 | - Source: 留 髮 不 留 頭
148 | - Ground Truth: 還 好 我 早 就 禿 頭 了
149 | - Predict: 還 好 我 早 就 禿 頭 了
150 |
151 | - Source: 當 人 好 痛 苦 R 的 八 卦
152 | - Ground Truth: 去 中 國 就 不 用 當 人 了
153 | - Predict: 去 中 國 就 不 會 有 了 -
154 |
155 | - Source: 有 沒 有 今 天 捷 運 的 八 卦
156 | - Ground Truth: 有 - 真 的 有 多
157 | - Predict: 有 - 真 的 有 多
158 |
159 | - Source: 2016 帶 走 了 什 麼 `
160 | - Ground Truth: HellKitty 麥 當 勞 歡 樂 送 開 門 -
161 | - Predict: 麥 當 勞 歡 樂 送 開 門 -
162 |
163 | - Source: 有 沒 有 多 益 很 賺 的 八 卦
164 | - Ground Truth: 比 大 型 包 裹 貴
165 | - Predict: 比 大 型 包 貴
166 |
167 | - Source: 邊 緣 人 收 到 地 震 警 報 了
168 | - Ground Truth: 都 跑 到 窗 邊 了 才 來
169 | - Predict: 都 跑 到 邊 了 才 來
170 |
171 | - Source: 車 震
172 | - Ground Truth: 沒 被 刪 版 主 是 有 眼 睛 der
173 | - Predict: 沒 被 刪 版 主 是 有 眼 睛 der
174 |
175 | - Source: 在 家 跌 倒 的 八 卦 `
176 | - Ground Truth: 傷 到 腦 袋 - 可 憐
177 | - Predict: 傷 到 腦 袋 - 可 憐
178 |
179 | - Source: 大 家 很 討 厭 核 核 嗎 `
180 | - Ground Truth: 核 核 欠 幹 阿
181 | - Predict: 核 核 欠 幹 阿
182 |
183 | - Source: 館 長 跟 黎 明 打 誰 贏 -
184 | - Ground Truth: 我 愛 黎 明 - 我 愛 黎 明 -
185 | - Predict: 我 愛 明 - 我 愛 明 -
186 |
187 | - Source: 嘻 嘻 打 打
188 | - Ground Truth: 媽 的 智 障 姆 咪 滾 喇 幹
189 | - Predict: 媽 的 智 障 姆 咪 滾 喇 幹
190 |
191 | - Source: 經 典 電 影 台 詞
192 | - Ground Truth: 超 時 空 要 愛 裡 滿 滿 的 梗
193 | - Predict: 超 時 空 要 愛 裡 滿 滿 滿 的
194 |
195 | - Source: 2B 守 得 住 街 亭 嗎 `
196 | - Ground Truth: 被 病 毒 滅 亡 真 的 會 -
197 | - Predict: 守 得 住
198 | ```
199 |
200 | # Comparison
201 |
202 | ## Implement feedforward through fully connected.
203 |
204 | - Training Accuracy
205 |
206 |
207 |

208 |
209 |
210 | - Training Loss
211 |
212 |
213 |

214 |
215 |
216 | ## Implement feedforward through convolution in only one dimention.
217 |
218 | - Training Accuracy
219 |
220 |
221 |

222 |
223 |
224 | - Training Loss
225 |
226 |
227 |

228 |
229 |
230 | # Tips
231 | If you try to use **AutoGraph** to speed up your training process, please make sure the datasets is padded to a fixed length. Because of the graph rebuilding operation will be activated during training, which may affect the performance. Our code only ensures the performance of version 2.0, and the lower ones can try to refer it.
232 |
233 | # Reference
234 |
235 | Thanks for [Transformer](https://github.com/Kyubyong/transformer) and [Tensorflow](https://www.tensorflow.org)
236 |
--------------------------------------------------------------------------------
/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EternalFeather/Transformer-in-generating-dialogue/fc781a61ee8cfcd0966571f34809ec7308476590/__init__.py
--------------------------------------------------------------------------------
/bleu.py:
--------------------------------------------------------------------------------
1 | # Copyright 2017 Google Inc. All Rights Reserved.
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | # ==============================================================================
15 |
16 | """Python implementation of BLEU and smooth-BLEU.
17 | This module provides a Python implementation of BLEU and smooth-BLEU.
18 | Smooth BLEU is computed following the method outlined in the paper:
19 | Chin-Yew Lin, Franz Josef Och. ORANGE: a method for evaluating automatic
20 | evaluation metrics for machine translation. COLING 2004.
21 | """
22 |
23 | import collections
24 | import math
25 |
26 |
27 | def _get_ngrams(segment, max_order):
28 | """Extracts all n-grams upto a given maximum order from an input segment.
29 | Args:
30 | segment: text segment from which n-grams will be extracted.
31 | max_order: maximum length in tokens of the n-grams returned by this
32 | methods.
33 | Returns:
34 | The Counter containing all n-grams upto max_order in segment
35 | with a count of how many times each n-gram occurred.
36 | """
37 | ngram_counts = collections.Counter()
38 | for order in range(1, max_order + 1):
39 | for i in range(0, len(segment) - order + 1):
40 | ngram = tuple(segment[i:i+order])
41 | ngram_counts[ngram] += 1
42 | return ngram_counts
43 |
44 |
45 | def compute_bleu(reference_corpus, translation_corpus, max_order=4,
46 | smooth=False, order_weights=True):
47 | """Computes BLEU score of translated segments against one or more references.
48 | Args:
49 | reference_corpus: list of lists of references for each translation. Each
50 | reference should be tokenized into a list of tokens.
51 | translation_corpus: list of translations to score. Each translation
52 | should be tokenized into a list of tokens.
53 | max_order: Maximum n-gram order to use when computing BLEU score.
54 | smooth: Whether or not to apply Lin et al. 2004 smoothing.
55 |
56 | order_weights: Use different weights to control accuracy. The longer, the more important.
57 | Default to True.
58 |
59 | Returns:
60 | 3-Tuple with the BLEU score, n-gram precisions, geometric mean of n-gram
61 | precisions and brevity penalty.
62 | """
63 | matches_by_order = [0] * max_order
64 | possible_matches_by_order = [0] * max_order
65 | reference_length = 0
66 | translation_length = 0
67 |
68 | empty_error_flag = False
69 |
70 | for (references, translation) in zip(reference_corpus,
71 | translation_corpus):
72 | if len(references) == 0 or len(translation) == 0:
73 | empty_error_flag = True
74 | break
75 |
76 | reference_length += min(len(r) for r in references)
77 | translation_length += len(translation)
78 |
79 | merged_ref_ngram_counts = collections.Counter()
80 | for reference in references:
81 | merged_ref_ngram_counts |= _get_ngrams(reference, max_order)
82 | translation_ngram_counts = _get_ngrams(translation, max_order)
83 | overlap = translation_ngram_counts & merged_ref_ngram_counts
84 |
85 | for ngram in overlap:
86 | matches_by_order[len(ngram)-1] += overlap[ngram]
87 | for order in range(1, max_order+1):
88 | possible_matches = len(translation) - order + 1
89 | if possible_matches > 0:
90 | possible_matches_by_order[order-1] += possible_matches
91 |
92 | if empty_error_flag:
93 | return 0.0, None, None, None, None, None
94 |
95 | precisions = [0] * max_order
96 | for i in range(0, max_order):
97 | if smooth:
98 | precisions[i] = ((matches_by_order[i] + 1.) /
99 | (possible_matches_by_order[i] + 1.))
100 | else:
101 | if possible_matches_by_order[i] > 0:
102 | precisions[i] = (float(matches_by_order[i]) /
103 | possible_matches_by_order[i])
104 | else:
105 | precisions[i] = 0.0
106 |
107 | if max(precisions) > 0:
108 | if order_weights:
109 | p_log_sum = sum((1. / (i + 1)) * math.log(p) for i, p in enumerate(reversed(precisions)) if p > 0)
110 | else:
111 | p_log_sum = sum((1. / max_order) * math.log(p) for p in precisions if p > 0)
112 | geo_mean = math.exp(p_log_sum)
113 | else:
114 | geo_mean = 0
115 |
116 | ratio = float(translation_length) / reference_length
117 |
118 | if ratio > 1.0:
119 | bp = 1.
120 | else:
121 | bp = math.exp(1 - 1. / ratio)
122 |
123 | bleu = geo_mean * bp
124 |
125 | return bleu, precisions, bp, ratio, translation_length, reference_length
126 |
127 |
128 | def bleu_metrics(per_segment_references, translations, smooth=False, max_order=3, order_weights=True):
129 | """Compute BLEU scores"""
130 | # bleu_score, precisions, bp, ratio, translation_length, reference_length
131 | bleu_score, _, _, _, _, _ = compute_bleu(
132 | per_segment_references, translations, max_order, smooth, order_weights)
133 |
134 | return 100 * bleu_score
135 |
136 |
--------------------------------------------------------------------------------
/data/src-val.txt:
--------------------------------------------------------------------------------
1 | 不 要 再 操 弄 一 休 和 尚 了
2 | 明 天 有 放 假 嗎 -
3 | 4NonBlondes
4 | 如 何 幫 貓 貓 減 肥 `
5 | 雞 腿 能 換 駕 照 那 雞 翅 `
6 | 台 灣 十 大 國 際 品 牌
7 | 最 近 有 哪 本 書 好 看 `
8 | 這 樣 稱 得 上 反 串 嗎 -
9 | 馬 子 是 M 屬 性 怎 麼 辦 -
10 | 要 如 何 才 能 把 餅 掰 開 `
11 | 哪 裡 買 的 到 陰 陽 奶
12 | FB484 壞 掉
13 | 有 狠 生 氣 燒 肉 的 卦 嗎 `
14 | 那 女 孩 對 我 微 笑 -
15 | 關 於 身 心 障 礙 特 考 三 等
16 | 明 天 就 要 上 班 了
17 | 館 長 怎 麼 在 PTT 紅 的
18 | 今 天 晚 上 會 治 安 紅 燈 嗎
19 | 馬 雅 人 有 沒 有 改 革 者 `
20 | 誰 知 道 這 是 什 麼 餅 乾 -
21 | 貓 咪 會 這 樣 走 路 嗎 OAO
22 | 發 廢 文 嗆 金 正 恩 -
23 | 妹 妹 拿 槍 指 著 我
24 | 有 沒 有 MAJAJA 的 掛 -
25 | 想 開 間 按 摩 店
26 | 波 波 圍 棋 會 下 圍 棋 嗎
27 | 登 入 1000 次 算 學 長 嗎 -
28 | 貓 會 裝 死 嗎 `
29 | 兔 兔 蜜 外 套 的 原 料
30 | 幫 黑 人 拔 罐
31 | 草 莓 百 分 百 重 新 選 邊 站
32 | 惱 羞 拍 影 片 回 嗆 酸 民 `
33 | 屁 股 下 巴
34 | 閣 下 是 開 戰 的 起 手 式 嗎
35 | 睡 不 著
36 | 有 炸 鍋 貼 這 種 料 理 嗎 -
37 | 魔 人 是 如 何 養 成 的 `
38 | 幾 歲 第 一 次 搭 ` -
39 | 讓 我 們 互 到 一 聲 晚 安
40 | 有 沒 有 通 靈 的 八 卦 -
41 | 濟 顛 是 不 是 工 具 人 `
42 | 什 麼 叫 做 勇 敢 去 愛
43 | 學 姐 一 直 在 聽 magnet
44 | 登 入 滿 1000 次 會 出 現 什 麼
45 | 三 監 之 亂
46 | 一 直 看 公 車 的 卦 `
47 | 大 學 畢 業 潮 有 多 潮
48 | 世 界 末 日 -
49 | 天 氣 很 熱 怎 麼 辦
50 | 該 閃 左 邊 還 右 邊 `
51 | 嫖 了 不 給 錢 算 誘 姦 嗎 `
52 | 今 天 的 勇 士 讓 人 舒 服 -
53 | 中 華 XX 隊
54 | 宵 夜 戒 斷 症 候 群
55 | 有 沒 有 theXXX 的 八 卦
56 | 慈 濟 今 天 什 麼 活 動 `
57 | 童 軍 是 在 幹 嘛 的 -
58 | 個 體 經 濟 中 文 聖 經 是 誰
59 | 如 何 加 強 國 民 駕 駛 素 質
60 | 冰 島 CrashedDC3Plane
61 | 是 有 多 潮 `
62 | 臉 書 社 團
63 | she 當 初 怎 麼 紅 的 -
64 | 低 能 卡 怎 麼 這 摸 低 能
65 | 有 沒 有 疊 字 的 八 卦 `
66 | 海 淪 清 洮 的 八 卦
67 | 米 其 林 餐 廳 有 沒 有 魚 翅
68 | 姐 姐 是 不 是 睡 糊 塗 了 `
69 | 683T 拍 成 電 影 要 怎 麼 演
70 | 有 沒 有 歐 森 的 八 卦
71 | babalabalabalabala 給 你 好 心 情
72 | yee 建 聯 行 情 還 好 嗎 `
73 | 姓 侯 能 取 什 麼 名 字 -
74 | 桐 谷 和 人 巴 哈 -
75 | 伴 隨 我 這 樣 好 嗎
76 | 有 沒 有 基 地 台 名 稱 的 卦
77 | 為 什 麼 NBA 樂 透 一 面 倒 -
78 | 板 主 要 開 賭 盤 嗎 `
79 | 鄉 民 想 當 正 男 還 是 正 恩
80 | 怎 摸 拒 絕 國 中 森 -
81 | 八 卦 板 隨 時 都 有 人 噓 `
82 | ThuMay414 - 53 - 292017
83 | 只 有 一 人 的 電 影 廳
84 | 有 沒 有 sodapoppin 的 八 掛
85 | 南 加 州 學 院 科 系
86 | 肥 宅 早 餐 都 吃 了 什 麼
87 | a000000000 被 水 桶 obov 會 復 出 嗎 -
88 | 肥 宅 是 帥 哥 難 為
89 | 全 部 人 都 死 了 -
90 | 單 身 的 力 量 `
91 | 得 憂 鬱 症 了 怎 麼 辦 -
92 | 睡 前 喝 惹 很 多 牛 奶
93 | 要 怎 麼 證 明 圓 環 之 理 -
94 | 半 導 體
95 | 大 家 多 久 一 次 見 到 朋 友
96 | 有 妹 妹 是 什 麼 感 覺 `
97 | 剛 和 正 妹 看 完 電 影 -
98 | 生 氣 給 魔 鬼 留 地 步
99 | Python 和 R - 哪 個 屌 `
100 | 犬 太 大 怎 麼 辦
101 | 我 突 然 發 現
102 | 希 望 撿 到 筆 記 本
103 | 有 沒 有 中 夭 崩 潰 的 八 卦
104 | 準 時 下 班 的 工 作 多 嗎 `
105 | 哪 個 工 藤 新 一 比 較 像 `
106 | 氧 化 還 原 反 應 -
107 | 把 可 樂 當 水 喝 會 怎 樣 -
108 | 法 國 是 不 是 太 自 由 了
109 | 有 沒 有 宣 儀 的 八 卦
110 | 如 果 做 一 份 這 種 工 作 -
111 | 該 唸 企 鵝 還 是 企 鵝 -
112 | 妹 妹 說 看 小 說 會 濕 掉
113 | 我 飄 香 北 方 -
114 | 正 修 的 掛
115 | 在 中 橫 上 想 ` 怎 麼 辦 `
116 | 剛 剛 去 提 款 被 電 到 -
117 | pttfor 手 機 的 API 有 後 門 -
118 | 八 卦 下 一 個 戰 的 族 群 -
119 | 好 希 望 能 被 XXXXGAY 肛
120 | 有 陳 園 淳 的 八 卦 嗎
121 | 希 望 能 交 到 女 朋 友
122 | XXXXGAY 和 X 是 什 麼 關 係 `
123 | 希 望 我 的 狗 不 再 尿 床
124 | 睡 夢 中 驚 醒
125 | 取 手 治 算 是 工 具 人 嗎 `
126 | - ` - ` - 奶 子 的 八 卦
127 | 色 盲 可 以 分 辨 紅 綠 燈 嗎
128 | 有 沒 有 電 療 的 掛 `
129 | 有 沒 有 王 洛 九 的 八 卦 -
130 | ptt 是 不 是 過 譽 了
131 | 赤 井 秀 一 怎 麼 那 麼 帥 `
132 | 你 室 友 沒 有 被 ` -
133 | 手 機 電 池 容 量
134 | 喉 糖 界 的 霸 主 的 掛
135 | SHE 新 歌 抄 襲 五 佰 -
136 | 不 穿 內 褲 內 衣 會 被 告 嗎
137 | 有 沒 有 新 物 種 的 八 卦
138 | 發 哥 只 收 電 機 資 工 -
139 | 有 沒 有 小 紅 帽 的 八 卦 -
140 | 有 沒 有 神 經 病 的 八 卦
141 | 有 沒 有 反 三 寶 的 八 卦
142 | 如 何 安 慰 失 戀 的 室 友
143 | 胡 瓜 兒
144 | 有 沒 有 DJOkawari 的 八 卦
145 | 狗 淡 水 新 民 街 狗 走 失 -
146 | 有 沒 有 五 雷 印 的 八 卦
147 | 現 在 誰 開 演 唱 會 會 去 看
148 | 被 男 生 倒 追 怎 麼 辦 `
149 | 香 港 大 欖 郊 公 園 八 卦
150 | 一 休 一 例 被 蓋 掉 嗎 -
151 | 有 沒 有 大 熱 天 的 八 卦 `
152 | 跑 酷 遊 戲 越 跑 越 快 -
153 | 有 沒 有 伯 奇 的 八 卦 `
154 | 偶 勒 哇 趟 抖 露
155 | 有 沒 有 吳 祥 輝 的 八 卦 `
156 | 有 沒 有 seve 舞 步 的 八 卦 -
157 | 大 家 的 卍 解 是 什 麼 `
158 | 有 沒 有 MAJU 公 司 的 八 卦 -
159 | 有 人 喝 過 馬 奶 酒 嗎 -
160 | 有 沒 有 返 校 日 的 八 卦
161 | 有 沒 有 練 懿 樂 的 八 卦
162 | 一 直 畫 圖 是 在 畫 三 小 `
163 | 悲 傷 的 心 情 QQ
164 | 弟 弟 不 給 舔
165 | 有 沒 有 ROC 的 八 卦
166 | 要 怎 麼 跟 鬼 交 朋 友 `
167 | 有 誰 能 打 奧 運 網 球 -
168 | 七 夕 可 以 幹 嘛
169 | 王 八 蛋 是 什 麼 樣 的 蛋 -
170 | 到 底 道 統 是 什 麼 `
171 | PTT 御 三 家 `
172 | 幾 歲 結 婚 的 八 卦
173 | 老 師 怪 怪 的 怎 麼 辦 -
174 | PokemonGO 是 肥 宅 出 頭 天 的 遊 戲
175 | 有 沒 有 樂 宜 的 八 卦 -
176 | 國 語 是 不 是 過 譽 了
177 | 把 外 勞 妹 妹 要 注 意 什 麼
178 | 請 問 輔 大 Kobe
179 | 有 沒 有 女 追 男 的 八 卦 -
180 | 又 長 又 硬 的 懶 覺
181 | cp 值 最 高 的 咖 啡
182 | 邪 魔 ` -
183 | 跟 身 體 一 樣 長 的 屎
184 | 盒 盒 跟 女 森 ` 下 午 茶
185 | ` 的 團 長 ` 孫 - 志
186 | 神 奇 海 螺 有 多 神 奇 -
187 | 有 人 用 伍 佰 的 ID 嗎
188 | 國 慶 爺 在 幹 嘛
189 | 早 餐 店 該 選 哪 一 家 `
190 | 用 花 生 造 個 詞
191 | 為 什 麼 公 雞 早 上 會 叫 `
192 | 有 沒 有 口 噛 ` 酒 的 八 卦
193 | 香 香 的 胖 子 有 多 慘
194 | 為 什 麼 會 被 肥 宅 敷 衍 -
195 | 螞 蟻 是 會 突 然 暴 斃 的 嗎
196 | 被 劈 腿 了 要 嗆 什 麼 話 `
197 | 陳 建 州 為 什 麼 不 告 網 友
198 | 被 說 像 貓 ` 該 開 心 嗎 `
199 | 夢 子 算 不 算 母 豬 `
200 | 是 你 你 會 選 擇 -
201 | 被 刺 激 到 了 - 怎 麼 辦 `
202 | 我 可 以 抱 你 嗎
203 | 任 天 堂 在 搞 什 麼 飛 機 -
204 | 決 戰 一 分 鐘
205 | 清 蘭 槌 子 上 的 紅 漬
206 | 明 年 會 有 什 麼 秀 `
207 | 蛇 蛇 可 愛 但 蛇 蛇 不 說
208 | 有 沒 有 愛 愛 的 八 卦
209 | 有 李 欣 欣 的 八 卦 嗎 `
210 | 有 沒 有 HTLV 的 八 卦
211 | 還 有 什 麼 捨 不 得 能 幹 嘛
212 | 歐 陽 鋒 想 收 妹 妹 為 徒
213 | 蟑 螂 什 麼 時 候 黑 掉 了
214 | 姓 柯 的 能 取 什 麼 名 字 `
215 | 肥 宅 可 剪 豪 力 頭 嗎 -
216 | 先 有 雞 先 有 蛋 -
217 | 最 可 愛 的 狗
218 | 以 後 義 體 化 可 以 結 婚 嗎
219 | 在 哪 裡 工 作 最 潮 -
220 | 有 沒 有 重 新 定 義 大 平 台
221 | 考 上 清 大 很 難 `
222 | 當 PTT 板 主 有 什 麼 好 處 -
223 | 吃 到 飽 要 多 少 錢 才 合 理
224 | 有 沒 有 烘 焙 機 的 八 卦 -
225 | 我 不 要 緊 的
226 | 為 什 麼 撞 到 牆 壁 會 痛
227 | 反 甲 卻 挺 T 是 為 什 麼 `
228 | 每 天 一 定 做 的 事 -
229 | 聽 縮 鄉 民 人 都 很 好
230 | 被 叫 床 聲 吵 醒 能 幹 嘛
231 | 姆 咪 被 偷 了 怎 麼 辦
232 | 清 華 大 學
233 | 有 氧 飲 料 喝 了 會 怎 樣
234 | 冬 天 如 何 克 制 食 慾 -
235 | 肥 宅 外 遇 的 八 卦
236 | uber 現 在 是 不 是 不 能 用 了
237 | 有 菜 蟲 的 八 卦 嗎 `
238 | 肥 宅 很 會 轉 珠 有 加 分 嗎
239 | 為 何 剛 力 彩 芽 常 被 酸 `
240 | 有 沒 有 AlisonBrie 的 八 卦 -
241 | 給 我 一 個 理 由 忘 記
242 | 愛 的 故 事 有 很 多
243 |
--------------------------------------------------------------------------------
/data/tgt-val.txt:
--------------------------------------------------------------------------------
1 | 幕 府 大 將 軍
2 | 學 生 乖 乖 去 上 課 ` 懂 `
3 | BASS 手 是 女 的 - 我 不 信
4 | 橘 貓 天 生 肥 宅 無 解
5 | 打 翻 了 齁 笑 你
6 | 台 積 電 是 外 資 啊 -
7 | 有 從 市 場 賺 到 2000 了 嗎
8 | 歐 嗨 喲 不 是 這 樣 用 的 吧
9 | 彩 虹 小 馬 ` -
10 | 一 代 宗 師 嗎
11 | 陰 陽 爛 屁 股
12 | 應 該 都 沒 有 注 意 到 吧
13 | 就 還 好 吃 粗 飽 還 可 以
14 | 往 後 看 好 嗎
15 | 有 國 考 板 身 障 板
16 | 還 好 我 沒 工 作 QQ
17 | 館 長 就 是 說 真 話 的 人
18 | 宣 佈 為 國 定 殺 戮 日
19 | 先 猜 你 釣 不 到
20 | 裡 面 有 蠶 寶 寶
21 | 臉 書 有 影 片
22 | 有 種 去 官 網 嗆
23 | 尻 尻 時 別 看 著 GG
24 | 國 中 的 東 西 了 -
25 | 叫 某 某 女 中 會 超 多 人
26 | 不 只 波 波 比 鵰 也 會
27 | 沒 人 認 識 高 義 嗎 `
28 | 正 在 CD 中 貓 有 九 條 命
29 | 前 三 張 外 套 都 一 樣 吧
30 | 蓋 三 小 喇 幹
31 | 癡 女 梢 奇 蹟 逆 轉
32 | 你 被 搶 上 來 討 拍 拍 嗎
33 | 韓 國 子 瑜 `
34 | 閣 下 筆 者
35 | 該 ` 早 餐 惹
36 | 早 餐 店 會 有 炸 水 餃 這 道
37 | 在 蛋 裡 吸 賽 亞 人 的 氣
38 | 還 在 媽 媽 肚 子 裡 的 時 候
39 | 我 想 念 動 哥 QQ
40 | 現 在 通 通 隔 開
41 | 佛 不 會 跟 凡 人 計 較 這 些
42 | 你 的 電 量 說 明 一 切
43 | 和 他 一 起 玩 啊 - 3
44 | 真 的 有 道 理 耶 發 錢
45 | 幹 是 真 貨 -
46 | 在 等 307 阿 斯 娜
47 | 高 潮 了 啊 啊 - 啊 啊 啊 `
48 | 歌 詞 文 出 動
49 | 開 27 加 電 扇 阿
50 | 到 左 邊 助 跑 往 右 邊 跳
51 | 去 問 豹 子 頭
52 | 總 冠 軍 賽 再 叫 我
53 | 中 國 台 北 一 定 強
54 | 真 的 幹 他 媽 的 戒 不 掉
55 | 快 去 吃 THE 便 當
56 | 乾 我 屁 事 去 選 賓 士 啦 滾
57 | 打 發 時 間 用 的
58 | 鼻 地 經 濟 學
59 | 直 接 抓 進 去 關 就 好 了
60 | 冰 鳥 墜 機 在 ` 第 三 星 球
61 | XDDDDDDDDDDDD
62 | 石 皮 處 礻 土
63 | 捧 中 國 人 LP
64 | 你 這 篇 文 章 還 給 嗆 低 卡
65 | 疊 字 就 是 可 愛
66 | 好 你 可 以 滾 了
67 | 我 請 你 吃 虱 目 魚 刺
68 | 佛 說 八 大 人 學 經
69 | 拍 國 軍 公 墓 阿
70 | 歐 森 姐 妹 我 的
71 | 吧 啦 吧 啦 紅 吧 啦 吧 啦 紅
72 | Yi 定 很 好
73 | 侯 子 在 動 物 園
74 | 西 瓜 榴 槤 雞
75 | 你 沒 有 女 友
76 | 我 有 網 路 你 沒 有 `
77 | 姆 迷 嘴 上 說 不 要
78 | 眼 睛 有 父 女 眼
79 | 想 當 正 男 幹 妮 妮
80 | 想 騙 人 家 尿 尿 ` 地 方 `
81 | 剛 好 想 `
82 | 台 北 人 養 全 台 灣 人
83 | 你 的 後 面 都 是 人
84 | 我 只 知 道 SODA 是 巨 乳 DJ
85 | 勝 文 哪 是 笑 噴
86 | 機 器 人 問 卦
87 | 哈 哈 哈 哈 哈 哈
88 | 你 的 語 表 -
89 | 有 時 候 死 人 比 活 人 好 用
90 | 138 哪 裡 啊
91 | 好 想 瘋 狂 做 艾
92 | 你 明 天 開 始 改 喝 馬 奶
93 | 一 個 女 的 在 中 間
94 | 快 去 睡 覺 - 別 想 太 多 了
95 | 我 現 在 在 聽 粗 音 唱 歌
96 | 沒 有 很 好 醒 醒
97 | 錢 準 備 好 了 就 去 吧
98 | 因 為 要 CD
99 | R 時 代 已 經 過 去 了
100 | 三 小 XDD
101 | 廢 到 笑 XD
102 | 雷 姆 是 誰 `
103 | 太 陽 花 崩 潰 -
104 | - 1 面 時 的 時 候 記 得 問
105 | 小 哀 不 夠 傲 嬌
106 | 你 化 學 式 先 寫 出 來 啊 `
107 | 會 變 更 肥 的 肥 宅
108 | 沒 競 爭 力 的 國 家
109 | 現 在 很 少 發 fb 了 QQ
110 | 發 錢 啊 - 馬 的 這 麼 多 字
111 | 去 看 教 育 部 的 資 料 啊
112 | 幹 嘛 開 兩 個 帳 號 聊 天
113 | 哪 首 糞 歌 自 己 報
114 | 超 多 學 店 不 意 外
115 | 衛 生 紙 吞 下 去 不 會 喔
116 | 開 始 尻 阿 還 用 問
117 | 覺 青 ` 把 手 機 丟 掉
118 | 沒 網 路 的 南 部 人
119 | 還 穿 什 麼 內 褲
120 | 邱 創 換 外 孫 女
121 | 幽 默 的 工 具 人
122 | 插 四 下 就 會 射
123 | 差 點 害 到 正 妹 96
124 | 睡 夢 中 被 敲 醒
125 | 愛 情 白 皮 書
126 | 一 個 奶 子 - 各 自 表 述 `
127 | 聽 說 有 色 盲 專 用 的 眼 鏡
128 | 為 啥 要 殺 高 梨 王
129 | 八 卦 是 你 竟 然 會 看 康 熙
130 | 慢 走 不 送 囉
131 | 只 要 做 好 自 己 本 分 就 好
132 | 腦 袋 沒 壞 吧 `
133 | 改 裝 電 瓶 啊
134 | 龍 角 散 喉 糖 有 點 貴 就 是
135 | ` 點 都 不 想 - 騙 點
136 | 你 長 那 樣 都 沒 事 了
137 | XDDDDDD
138 | 都 至 少 大 葉 資 工 好 嗎
139 | 佩 雯 小 紅 帽
140 | 公 三 小 哪 部 直 接 講
141 | 肥 宅 也 是 三 寶
142 | 好 棒 喔 加 油 喔
143 | 開 封 有 個 包 莖 天
144 | 一 個 不 練 腳 的 人 很 愛 聽
145 | 好 可 愛 會 咬 人 嗎
146 | 季 離 欸 進 力 量 欸 大 喔 `
147 | 張 學 友 張 學 友 我 們 愛 你
148 | 肚 毛 有 點 多
149 | 請 香 港 人 來 說 明 -
150 | 總 統 旅 遊 團 也 被 蓋 掉 了
151 | 因 為 柱 算 不 如 朱 算
152 | hiyo 衝 天 跑
153 | 機 機 應 應 就 是 伯 奇
154 | 不 知 道 在 嗨 什 麼 -
155 | 國 家 系 列 書 寫 得 很 動 人
156 | 西 洋 台 客 舞
157 | 看 到 超 ` 拳 婦 白 冰 冰
158 | 官 網 是 國 小 生 做 的 嗎
159 | 這 篇 沒 馬 奶 圖 我 自 `
160 | 全 裸 登 校 日
161 | 幹 他 很 帥 -
162 | 想 紅 的 肥 宅 吧
163 | 沒 關 過 所 以 不 知 道
164 | 你 是 不 是 有 屌 - 錢
165 | 沒 人 理 你 欸
166 | 你 根 本 沒 種 認 識 啦 -
167 | 叫 那 群 喊 賠 錢 的 去 打 啊
168 | 去 抓 特 有 怪 四 腳 獸
169 | 忘 八 端
170 | 中 華 民 國 道 統 懂 -
171 | 肥 宅 ` 魯 蛇 ` 魯 肥 宅
172 | 肥 宅 此 生 窩 無 望 結 婚
173 | 這 片 好 老 了 喔
174 | 肥 宅 連 寶 可 夢 都 想 沾 光
175 | 冷 凍 小 丑 女 友
176 | 你 是 文 組 嗎
177 | 幹 轟 三 小 喇 幹
178 | 輔 大 情 慾 流 動
179 | 找 人 回 收 -
180 | 你 是 不 是 想 釣 懶 叫 王
181 | 他 去 了 免 費 續 杯 的 咖 啡
182 | 幹 那 是 特 蘭 克 斯 的 招 吧
183 | 倒 影 都 出 油 惹
184 | 藥 吃 了 嗎 `
185 | 這 還 不 桶 又 廢 又 難 笑
186 | 梗 老 到 不 行 滾 喇 幹
187 | 他 老 婆 好 像 是 台 大 的
188 | 人 妻 好 ` 油
189 | 先 看 看 老 闆 娘
190 | 電 腦 選 的 花 生
191 | 我 人 超 好 我 告 訴 你 -
192 | 咪 茲 哈 會 說 你 變 態
193 | 嗆 三 小 窩 揪 香 香 `
194 | 妳 等 級 比 他 高 啊
195 | 肥 宅 味 道 太 噁 心 被 臭 死
196 | 台 灣 這 種 賤 妹 太 多 了
197 | 說 人 裝 熟 實 在 不 好 告
198 | 貓 咪 `
199 | 有 毛 又 摳 B 感 覺 有 夠 A
200 | 林 北 不 喝 酒 滾
201 | 在 床 上 教 訓 室 友
202 | 終 於 抓 到 人 了
203 | 跟 nokia 一 樣 - 再 等 等
204 | 廣 告 3 分 鐘 決 戰 一 分 鐘
205 | 明 明 就 花 生 醬
206 | 無 存 在 感 板 主 QQ
207 | 有 點 創 意 好 麻
208 | 比 較 溫 馨 阿
209 | 加 我 群 組 QQ
210 | LTHV ` NTNV
211 | 安 寧 病 房 啊
212 | 你 哪 國 來 的 啦
213 | 蟑 螂 脫 皮 後 就 變 白 的 囉
214 | 車 車 19 號 柯 斯 塔
215 | 明 明 是 腕 力
216 | 雞 懶 覺 好 `
217 | 最 大 隻 的 狗 三 翻 西 施 狗
218 | 素 子 給 你 七 轉 福 音 給 我
219 | 美 國 啊 當 然 -
220 | 大 奶 平 臺 你 都 不 懂 `
221 | 變 成 肥 宅 的 後 宮 惹 開 勳
222 | 桶 人 很 舒 壓 約 泡 很 爽
223 | 本 魯 小 確 幸
224 | 就 這 點 資 歷 也 敢 說 多 年
225 | 邱 X 表 示 -
226 | 因 為 人 被 殺 就 會 死
227 | 剛 好 被 你 朋 友 聞 到
228 | 幹 菜 英 文
229 | 我 又 不 是 好 人
230 | 開 a 片 回 擊 啊 還 用 說
231 | 姆 咪 騎 士 團 參 上
232 | 先 吃 一 下 麥 當 勞
233 | 會 有 吉 戰 力
234 | 吃 飽 開 始 克 制 4 小 時 阿
235 | 我 家 老 婆 們 不 會 吵 架 的
236 | 真 的 耶 - 新 竹 沒 有 半 台
237 | 揪 竟 什 麼 坎 佔 才 不 菜
238 | 有 啊 - 加 工 具 人 分
239 | 人 太 正 也 會 燒 菜
240 | MadMen 裡 面 我 最 愛 她
241 | 那 麼 愛 我 的 你 `
242 | 而 任 性 的 風
243 |
--------------------------------------------------------------------------------
/images/learning_rate.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EternalFeather/Transformer-in-generating-dialogue/fc781a61ee8cfcd0966571f34809ec7308476590/images/learning_rate.png
--------------------------------------------------------------------------------
/images/multi_head_attention.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EternalFeather/Transformer-in-generating-dialogue/fc781a61ee8cfcd0966571f34809ec7308476590/images/multi_head_attention.png
--------------------------------------------------------------------------------
/images/scaled_attention.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EternalFeather/Transformer-in-generating-dialogue/fc781a61ee8cfcd0966571f34809ec7308476590/images/scaled_attention.png
--------------------------------------------------------------------------------
/images/transformer.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EternalFeather/Transformer-in-generating-dialogue/fc781a61ee8cfcd0966571f34809ec7308476590/images/transformer.png
--------------------------------------------------------------------------------
/main-v2.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "metadata": {},
7 | "outputs": [],
8 | "source": [
9 | "from __future__ import absolute_import, division, print_function, unicode_literals\n",
10 | "\n",
11 | "import tensorflow as tf\n",
12 | "\n",
13 | "import time\n",
14 | "import datetime\n",
15 | "import os\n",
16 | "from tqdm import tqdm\n",
17 | "import numpy as np\n",
18 | "import matplotlib.pyplot as plt\n",
19 | "plt.rcParams['font.sans-serif']=['SimHei'] # 用来正常显示中文标签\n",
20 | "plt.rcParams['axes.unicode_minus']=False\n",
21 | "\n",
22 | "os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0, 1, 2, 3\" # 添加可用的gpu\n",
23 | "physical_devices = tf.config.experimental.list_physical_devices('GPU')\n",
24 | "for device in physical_devices:\n",
25 | " tf.config.experimental.set_memory_growth(device, True)\n",
26 | "\n",
27 | "from params import Params as pm\n",
28 | "from utils_v2 import en2idx, idx2en, de2idx, idx2de, dump2record, build_dataset, LRSchedule, masking, create_masks, plot_attention_weights\n",
29 | "from bleu import bleu_metrics"
30 | ]
31 | },
32 | {
33 | "cell_type": "code",
34 | "execution_count": null,
35 | "metadata": {},
36 | "outputs": [],
37 | "source": [
38 | "tf.__version__"
39 | ]
40 | },
41 | {
42 | "cell_type": "markdown",
43 | "metadata": {},
44 | "source": [
45 | "---"
46 | ]
47 | },
48 | {
49 | "cell_type": "code",
50 | "execution_count": null,
51 | "metadata": {},
52 | "outputs": [],
53 | "source": [
54 | "strategy = tf.distribute.MirroredStrategy()\n",
55 | "\n",
56 | "print('Number of device: {}'.format(strategy.num_replicas_in_sync))"
57 | ]
58 | },
59 | {
60 | "cell_type": "code",
61 | "execution_count": null,
62 | "metadata": {},
63 | "outputs": [],
64 | "source": [
65 | "def get_data(corpus_file):\n",
66 | " return open(corpus_file, 'r', encoding='utf-8').read().splitlines()"
67 | ]
68 | },
69 | {
70 | "cell_type": "code",
71 | "execution_count": null,
72 | "metadata": {},
73 | "outputs": [],
74 | "source": [
75 | "src_train, src_val = get_data(pm.src_train), get_data(pm.src_test)\n",
76 | "tgt_train, tgt_val = get_data(pm.tgt_train), get_data(pm.tgt_test)"
77 | ]
78 | },
79 | {
80 | "cell_type": "code",
81 | "execution_count": null,
82 | "metadata": {},
83 | "outputs": [],
84 | "source": [
85 | "dump2record(pm.train_record, src_train, tgt_train)\n",
86 | "dump2record(pm.test_record, src_val, tgt_val)"
87 | ]
88 | },
89 | {
90 | "cell_type": "markdown",
91 | "metadata": {},
92 | "source": [
93 | "---"
94 | ]
95 | },
96 | {
97 | "cell_type": "code",
98 | "execution_count": null,
99 | "metadata": {},
100 | "outputs": [],
101 | "source": [
102 | "from modules_v2 import positional_encoding, scaled_dot_product_attention, multihead_attention, pointwise_feedforward, EncoderBlock, DecoderBlock, Encoder, Decoder, Transformer"
103 | ]
104 | },
105 | {
106 | "cell_type": "markdown",
107 | "metadata": {},
108 | "source": [
109 | "# Positional encoding\n",
110 | "$$\\Large{PE_{(pos, 2i)} = sin(pos / 10000^{2i / d_{model}})} $$\n",
111 | "$$\\Large{PE_{(pos, 2i+1)} = cos(pos / 10000^{2i / d_{model}})} $$"
112 | ]
113 | },
114 | {
115 | "cell_type": "code",
116 | "execution_count": null,
117 | "metadata": {},
118 | "outputs": [],
119 | "source": [
120 | "pos_encoding = positional_encoding(50, 512, True)\n",
121 | "print(pos_encoding.shape)"
122 | ]
123 | },
124 | {
125 | "cell_type": "markdown",
126 | "metadata": {},
127 | "source": [
128 | "# Masking"
129 | ]
130 | },
131 | {
132 | "cell_type": "code",
133 | "execution_count": null,
134 | "metadata": {},
135 | "outputs": [],
136 | "source": [
137 | "x = tf.constant([[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]])\n",
138 | "masking(x, task='padding')"
139 | ]
140 | },
141 | {
142 | "cell_type": "code",
143 | "execution_count": null,
144 | "metadata": {},
145 | "outputs": [],
146 | "source": [
147 | "masking(x, task='look_ahead')"
148 | ]
149 | },
150 | {
151 | "cell_type": "markdown",
152 | "metadata": {},
153 | "source": [
154 | "# Scaled dot product attention"
155 | ]
156 | },
157 | {
158 | "cell_type": "markdown",
159 | "metadata": {},
160 | "source": [
161 | "\n",
162 | "$$\\Large{Attention(Q, K, V) = softmax_k(\\frac{QK^T}{\\sqrt{d_k}}) V} $$"
163 | ]
164 | },
165 | {
166 | "cell_type": "code",
167 | "execution_count": null,
168 | "metadata": {},
169 | "outputs": [],
170 | "source": [
171 | "def print_out(q, k, v):\n",
172 | " temp_out, temp_attn = scaled_dot_product_attention(q, k, v, None)\n",
173 | " print ('Attention weights are:')\n",
174 | " print (temp_attn)\n",
175 | " print ('Output is:')\n",
176 | " print (temp_out)"
177 | ]
178 | },
179 | {
180 | "cell_type": "code",
181 | "execution_count": null,
182 | "metadata": {},
183 | "outputs": [],
184 | "source": [
185 | "np.set_printoptions(suppress=True)\n",
186 | "\n",
187 | "temp_k = tf.constant([[10,0,0],\n",
188 | " [0,10,0],\n",
189 | " [0,0,10],\n",
190 | " [0,0,10]], dtype=tf.float32)\n",
191 | "\n",
192 | "temp_v = tf.constant([[ 1,0],\n",
193 | " [ 10,0],\n",
194 | " [ 100,5],\n",
195 | " [1000,6]], dtype=tf.float32)\n",
196 | "\n",
197 | "temp_q = tf.constant([[0, 10, 0]], dtype=tf.float32)\n",
198 | "print_out(temp_q, temp_k, temp_v)"
199 | ]
200 | },
201 | {
202 | "cell_type": "code",
203 | "execution_count": null,
204 | "metadata": {},
205 | "outputs": [],
206 | "source": [
207 | "temp_q = tf.constant([[0, 0, 10]], dtype=tf.float32)\n",
208 | "print_out(temp_q, temp_k, temp_v)"
209 | ]
210 | },
211 | {
212 | "cell_type": "code",
213 | "execution_count": null,
214 | "metadata": {},
215 | "outputs": [],
216 | "source": [
217 | "temp_q = tf.constant([[0, 0, 10], [0, 10, 0], [10, 10, 0]], dtype=tf.float32)\n",
218 | "print_out(temp_q, temp_k, temp_v)"
219 | ]
220 | },
221 | {
222 | "cell_type": "markdown",
223 | "metadata": {},
224 | "source": [
225 | "# Multi-head attention"
226 | ]
227 | },
228 | {
229 | "cell_type": "markdown",
230 | "metadata": {},
231 | "source": [
232 | ""
233 | ]
234 | },
235 | {
236 | "cell_type": "markdown",
237 | "metadata": {},
238 | "source": [
239 | "- **Tips: Dimention-level split**"
240 | ]
241 | },
242 | {
243 | "cell_type": "code",
244 | "execution_count": null,
245 | "metadata": {},
246 | "outputs": [],
247 | "source": [
248 | "temp_mha = multihead_attention(d_model=512, num_heads=8)\n",
249 | "y = tf.random.uniform((1, 50, 512))\n",
250 | "out, attn = temp_mha(y, k=y, q=y, mask=None)\n",
251 | "out.shape, attn.shape"
252 | ]
253 | },
254 | {
255 | "cell_type": "markdown",
256 | "metadata": {},
257 | "source": [
258 | "# Pointwise feed forward network"
259 | ]
260 | },
261 | {
262 | "cell_type": "code",
263 | "execution_count": null,
264 | "metadata": {},
265 | "outputs": [],
266 | "source": [
267 | "sample_ffn = pointwise_feedforward(512, 2048)\n",
268 | "sample_ffn(tf.random.uniform((64, 50, 512))).shape"
269 | ]
270 | },
271 | {
272 | "cell_type": "markdown",
273 | "metadata": {},
274 | "source": [
275 | "# Whole model (Encoder & Decoder)\n",
276 | ""
277 | ]
278 | },
279 | {
280 | "cell_type": "markdown",
281 | "metadata": {},
282 | "source": [
283 | "## Encoder"
284 | ]
285 | },
286 | {
287 | "cell_type": "code",
288 | "execution_count": null,
289 | "metadata": {},
290 | "outputs": [],
291 | "source": [
292 | "sample_encoder_layer = EncoderBlock(512, 8, 2048)\n",
293 | "sample_encoder_layer_output, _ = sample_encoder_layer(tf.random.uniform((64, 43, 512)), False, None)\n",
294 | "sample_encoder_layer_output.shape"
295 | ]
296 | },
297 | {
298 | "cell_type": "markdown",
299 | "metadata": {},
300 | "source": [
301 | "## Decoder"
302 | ]
303 | },
304 | {
305 | "cell_type": "code",
306 | "execution_count": null,
307 | "metadata": {},
308 | "outputs": [],
309 | "source": [
310 | "sample_decoder_layer = DecoderBlock(512, 8, 2048)\n",
311 | "\n",
312 | "sample_decoder_layer_output, _, _ = sample_decoder_layer(\n",
313 | " tf.random.uniform((64, 50, 512)), sample_encoder_layer_output, \n",
314 | " False, None, None)\n",
315 | "\n",
316 | "sample_decoder_layer_output.shape"
317 | ]
318 | },
319 | {
320 | "cell_type": "markdown",
321 | "metadata": {},
322 | "source": [
323 | "## Packed Encoder & Decoder"
324 | ]
325 | },
326 | {
327 | "cell_type": "code",
328 | "execution_count": null,
329 | "metadata": {},
330 | "outputs": [],
331 | "source": [
332 | "sample_encoder = Encoder(num_blocks=2, d_model=512, num_heads=8, dff=2048, input_vocab_size=8500, plot_pos_embedding=False)\n",
333 | "attn_dict = {}\n",
334 | "sample_encoder_output, attn_dict = sample_encoder(tf.random.uniform((64, 62)), training=False, padding_mask=None, attn_dict=attn_dict)\n",
335 | "sample_encoder_output.shape"
336 | ]
337 | },
338 | {
339 | "cell_type": "code",
340 | "execution_count": null,
341 | "metadata": {},
342 | "outputs": [],
343 | "source": [
344 | "sample_decoder = Decoder(num_blocks=2, d_model=512, num_heads=8, dff=2048, target_vocab_size=8000, plot_pos_embedding=False)\n",
345 | "output, attn_dict = sample_decoder(tf.random.uniform((64, 26)), \n",
346 | " enc_output=sample_encoder_output, \n",
347 | " training=False, look_ahead_mask=None, \n",
348 | " padding_mask=None, attn_dict=attn_dict)\n",
349 | "output.shape, attn_dict['decoder_layer2_block'].shape"
350 | ]
351 | },
352 | {
353 | "cell_type": "markdown",
354 | "metadata": {},
355 | "source": [
356 | "# Transformer"
357 | ]
358 | },
359 | {
360 | "cell_type": "code",
361 | "execution_count": null,
362 | "metadata": {},
363 | "outputs": [],
364 | "source": [
365 | "sample_transformer = Transformer(num_blocks=2, d_model=512, num_heads=8, dff=2048, input_vocab_size=8500, target_vocab_size=8000, plot_pos_embedding=False)\n",
366 | "\n",
367 | "temp_input = tf.random.uniform((64, 62))\n",
368 | "temp_target = tf.random.uniform((64, 26))\n",
369 | "\n",
370 | "fn_out, _ = sample_transformer(temp_input, \n",
371 | " temp_target, \n",
372 | " training=False, \n",
373 | " enc_padding_mask=None, \n",
374 | " look_ahead_mask=None,\n",
375 | " dec_padding_mask=None)\n",
376 | "\n",
377 | "fn_out.shape"
378 | ]
379 | },
380 | {
381 | "cell_type": "markdown",
382 | "metadata": {},
383 | "source": [
384 | "# Training"
385 | ]
386 | },
387 | {
388 | "cell_type": "code",
389 | "execution_count": null,
390 | "metadata": {},
391 | "outputs": [],
392 | "source": [
393 | "num_layers = pm.num_block\n",
394 | "d_model = pm.d_model\n",
395 | "dff = pm.dff\n",
396 | "num_heads = pm.num_heads\n",
397 | "\n",
398 | "input_vocab_size = len(en2idx)\n",
399 | "target_vocab_size = len(de2idx)\n",
400 | "dropout_rate = pm.dropout_rate\n",
401 | "\n",
402 | "EPOCHS = pm.num_epochs"
403 | ]
404 | },
405 | {
406 | "cell_type": "markdown",
407 | "metadata": {},
408 | "source": [
409 | "- Learning rate schedule\n",
410 | "$$\\Large{lrate = d_{model}^{-0.5} * min(step{\\_}num^{-0.5}, step{\\_}num * warmup{\\_}steps^{-1.5})}$$"
411 | ]
412 | },
413 | {
414 | "cell_type": "code",
415 | "execution_count": null,
416 | "metadata": {},
417 | "outputs": [],
418 | "source": [
419 | "temp_learning_rate_schedule = LRSchedule(d_model)\n",
420 | "\n",
421 | "plt.figure(figsize=(12, 8))\n",
422 | "plt.plot(temp_learning_rate_schedule(tf.range(40000, dtype=tf.float32)))\n",
423 | "plt.ylabel(\"Learning Rate\")\n",
424 | "plt.xlabel(\"Train Step\")"
425 | ]
426 | },
427 | {
428 | "cell_type": "markdown",
429 | "metadata": {},
430 | "source": [
431 | "---"
432 | ]
433 | },
434 | {
435 | "cell_type": "code",
436 | "execution_count": null,
437 | "metadata": {},
438 | "outputs": [],
439 | "source": [
440 | "with strategy.scope():\n",
441 | " # 1、dataset\n",
442 | " ## train_dataset = build_dataset(mode='array', batch_size=pm.batch_size * strategy.num_replicas_in_sync, cache_name='train_cache.tf-data', corpus=[src_train, tgt_train], is_training=True)\n",
443 | " ## val_dataset = build_dataset(mode='array', batch_size=pm.batch_size * strategy.num_replicas_in_sync, cache_name='val_cache.tf-data', corpus=[src_val, tgt_val], is_training=True)\n",
444 | " \n",
445 | " train_dataset = build_dataset(mode='file', batch_size=pm.batch_size * strategy.num_replicas_in_sync, cache_name='train_cache.tf-data', filename=pm.train_record, is_training=True)\n",
446 | " train_dist_dataset = strategy.experimental_distribute_dataset(train_dataset)\n",
447 | " \n",
448 | " # 2、loss function\n",
449 | " loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)\n",
450 | "\n",
451 | " def loss_function(real, pred):\n",
452 | " mask = tf.math.logical_not(tf.math.equal(real, 0))\n",
453 | " loss_ = loss_object(real, pred)\n",
454 | "\n",
455 | " mask = tf.cast(mask, dtype=loss_.dtype)\n",
456 | " loss_ *= mask\n",
457 | "\n",
458 | " return tf.reduce_mean(loss_), mask\n",
459 | " \n",
460 | " # 3、metrics to track loss and accuracy\n",
461 | " train_loss = tf.keras.metrics.Mean(name='train_loss')\n",
462 | " train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')\n",
463 | " \n",
464 | " # 4、model config\n",
465 | " transformer = Transformer(num_layers, d_model, num_heads, dff, input_vocab_size, target_vocab_size, pm.plot_pos_embedding, dropout_rate)\n",
466 | " \n",
467 | " learning_rate = LRSchedule(d_model)\n",
468 | " optimizer = tf.keras.optimizers.Adam(learning_rate, beta_1=pm.beta_1, beta_2=pm.beta_2, epsilon=pm.epsilon)\n",
469 | " \n",
470 | " checkpoint_path = pm.ckpt_path\n",
471 | "\n",
472 | " ckpt = tf.train.Checkpoint(transformer=transformer, optimizer=optimizer)\n",
473 | " ckpt_manager = tf.train.CheckpointManager(ckpt, checkpoint_path, max_to_keep=5)\n",
474 | "\n",
475 | " if ckpt_manager.latest_checkpoint:\n",
476 | " ckpt.restore(ckpt_manager.latest_checkpoint)\n",
477 | " print ('Latest checkpoint restored!!')\n",
478 | " \n",
479 | " current_time = datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n",
480 | " log_dir = pm.logdir + '/gradient_tape/' + current_time\n",
481 | " summary_writer = tf.summary.create_file_writer(log_dir)\n",
482 | " \n",
483 | " # 5、train step\n",
484 | " def train_step(inp, tar):\n",
485 | " tar_inp = tar[:, :-1]\n",
486 | " tar_real = tar[:, 1:]\n",
487 | "\n",
488 | " enc_padding_mask, combined_mask, dec_padding_mask = create_masks(inp, tar_inp)\n",
489 | "\n",
490 | " with tf.GradientTape() as tape:\n",
491 | " predictions, _ = transformer(inp, \n",
492 | " tar_inp, \n",
493 | " True, \n",
494 | " enc_padding_mask, \n",
495 | " combined_mask, \n",
496 | " dec_padding_mask)\n",
497 | "\n",
498 | " loss, istarget = loss_function(tar_real, predictions)\n",
499 | "\n",
500 | " gradients = tape.gradient(loss, transformer.trainable_variables) \n",
501 | " optimizer.apply_gradients(zip(gradients, transformer.trainable_variables))\n",
502 | "\n",
503 | " train_accuracy(tar_real, predictions, sample_weight=istarget)\n",
504 | " \n",
505 | " return loss\n",
506 | " \n",
507 | " @tf.function\n",
508 | " def distributed_train_step(inp, tar):\n",
509 | " per_replica_losses = strategy.experimental_run_v2(train_step, \n",
510 | " args=(inp, tar, ))\n",
511 | " return strategy.reduce(tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None)\n",
512 | " \n",
513 | " # 6、for loop\n",
514 | " total_steps = 0\n",
515 | " for epoch in range(EPOCHS):\n",
516 | " start = time.time()\n",
517 | "\n",
518 | " train_loss.reset_states()\n",
519 | " train_accuracy.reset_states()\n",
520 | " \n",
521 | " total_loss = 0.0\n",
522 | " num_batches = 0\n",
523 | " for (batch, (inp, tar)) in enumerate(train_dataset):\n",
524 | " total_loss += distributed_train_step(inp, tar)\n",
525 | " num_batches += 1\n",
526 | " total_steps += 1\n",
527 | "\n",
528 | " if batch % 500 == 0:\n",
529 | " with summary_writer.as_default():\n",
530 | " tf.summary.scalar('loss', total_loss / num_batches, step=total_steps)\n",
531 | " tf.summary.scalar('accuracy', train_accuracy.result() * 100, step=total_steps)\n",
532 | " \n",
533 | " print ('Epoch {} Batch {} Loss {:.4f} Accuracy {:.4f}'.format(\n",
534 | " epoch + 1, batch, total_loss / num_batches, train_accuracy.result() * 100))\n",
535 | " \n",
536 | " train_loss(total_loss / num_batches)\n",
537 | "\n",
538 | " if (epoch + 1) % 5 == 0:\n",
539 | " ckpt_save_path = ckpt_manager.save()\n",
540 | " print ('Saving checkpoint for epoch {} at {}'.format(epoch + 1, ckpt_save_path))\n",
541 | "\n",
542 | " print ('Epoch {} Loss {:.4f} Accuracy {:.4f}'.format(epoch + 1, train_loss.result(), train_accuracy.result() * 100))\n",
543 | " print ('Time taken for 1 epoch: {} secs\\n'.format(time.time() - start))"
544 | ]
545 | },
546 | {
547 | "cell_type": "markdown",
548 | "metadata": {},
549 | "source": [
550 | "---"
551 | ]
552 | },
553 | {
554 | "cell_type": "code",
555 | "execution_count": null,
556 | "metadata": {},
557 | "outputs": [],
558 | "source": [
559 | "val_dataset = build_dataset(mode='file', batch_size=pm.batch_size * strategy.num_replicas_in_sync, cache_name='val_cache.tf-data', filename=pm.test_record, is_training=True)"
560 | ]
561 | },
562 | {
563 | "cell_type": "code",
564 | "execution_count": null,
565 | "metadata": {},
566 | "outputs": [],
567 | "source": [
568 | "def evaluate(inp_sentence):\n",
569 | " encoder_input = inp_sentence\n",
570 | " \n",
571 | " decoder_input = [2]\n",
572 | " output = tf.expand_dims(decoder_input, 0)\n",
573 | " output = tf.tile(output, [tf.shape(encoder_input)[0], 1])\n",
574 | "\n",
575 | " for i in range(pm.maxlen):\n",
576 | " enc_padding_mask, combined_mask, dec_padding_mask = create_masks(encoder_input, output)\n",
577 | "\n",
578 | " predictions, attention_weights = transformer(encoder_input, \n",
579 | " output,\n",
580 | " False,\n",
581 | " enc_padding_mask,\n",
582 | " combined_mask,\n",
583 | " dec_padding_mask)\n",
584 | "\n",
585 | " predictions = predictions[: ,-1:, :]\n",
586 | " predicted_id = tf.cast(tf.argmax(predictions, axis=-1), tf.int32)\n",
587 | "\n",
588 | " output = tf.concat([output, predicted_id], axis=-1)\n",
589 | "\n",
590 | " return output, attention_weights"
591 | ]
592 | },
593 | {
594 | "cell_type": "code",
595 | "execution_count": null,
596 | "metadata": {},
597 | "outputs": [],
598 | "source": [
599 | "def cut_by_end(samples):\n",
600 | " output_list = np.zeros(tf.shape(samples))\n",
601 | " for i, sample in enumerate(samples):\n",
602 | " dtype = sample.dtype\n",
603 | " idx = tf.where(tf.equal(sample, 3))\n",
604 | " \n",
605 | " flag = tf.where(tf.equal(tf.size(idx), 0), 1, 0)\n",
606 | " if flag:\n",
607 | " output_list[i] = sample\n",
608 | " else:\n",
609 | " indices = tf.cast(idx[0, 0], dtype)\n",
610 | " output_list[i] = tf.concat([sample[:indices], tf.zeros(tf.shape(sample)[0] - indices, dtype=dtype)], axis=0)\n",
611 | "\n",
612 | " return tf.cast(output_list, dtype)"
613 | ]
614 | },
615 | {
616 | "cell_type": "code",
617 | "execution_count": null,
618 | "metadata": {},
619 | "outputs": [],
620 | "source": [
621 | "eval_log = os.path.join(pm.eval_log_path, '{}_eval.tsv'.format(pm.project_name))\n",
622 | "if not os.path.exists(pm.eval_log_path):\n",
623 | " os.makedirs(pm.eval_log_path)\n",
624 | "eval_file = open(eval_log, 'w', encoding='utf-8')\n",
625 | "\n",
626 | "start = time.time()\n",
627 | "count, scores = 0, 0\n",
628 | "for (batch, (inp, tar)) in enumerate(val_dataset):\n",
629 | " prediction, attention_weights = evaluate(inp)\n",
630 | " prediction = cut_by_end(prediction)\n",
631 | " \n",
632 | " preds, tars = [], []\n",
633 | " for source, real_tar, pred in zip(inp, tar, prediction):\n",
634 | " s = \" \".join([idx2en.get(i, 1) for i in source.numpy() if i < len(idx2en) and i not in [0, 2, 3]])\n",
635 | " t = \"\".join([idx2de.get(i, 1) for i in real_tar.numpy() if i < len(idx2de) and i not in [0, 2, 3]])\n",
636 | " p = \"\".join([idx2de.get(i, 1) for i in pred.numpy() if i < len(idx2de) and i not in [0, 2, 3]])\n",
637 | " \n",
638 | " preds.append(p)\n",
639 | " tars.append([t])\n",
640 | " \n",
641 | " eval_file.write('-Source : {}\\n-Target : {}\\n-Pred : {}\\n\\n'.format(s, t, p))\n",
642 | " eval_file.flush()\n",
643 | " \n",
644 | " scores += bleu_metrics(tars, preds, False, 3, True)\n",
645 | " count += 1\n",
646 | "\n",
647 | "eval_file.write('-BLEU Score : {:.4f}'.format(scores / count))\n",
648 | "eval_file.close()\n",
649 | "\n",
650 | "print(\"MSG : Done for evalutation ... Totolly {:.2f} sec.\".format(time.time() - start))"
651 | ]
652 | },
653 | {
654 | "cell_type": "code",
655 | "execution_count": null,
656 | "metadata": {},
657 | "outputs": [],
658 | "source": [
659 | "def predict(inp_sentence):\n",
660 | " start_token = [2]\n",
661 | " end_token = [3]\n",
662 | "\n",
663 | " inp_sentence = start_token + [en2idx.get(word, 1) for word in inp_sentence.split()] + end_token\n",
664 | " encoder_input = tf.expand_dims(inp_sentence, 0)\n",
665 | " \n",
666 | " decoder_input = [2]\n",
667 | " output = tf.expand_dims(decoder_input, 0)\n",
668 | "\n",
669 | " for i in range(pm.maxlen):\n",
670 | " enc_padding_mask, combined_mask, dec_padding_mask = create_masks(encoder_input, output)\n",
671 | "\n",
672 | " predictions, attention_weights = transformer(encoder_input, \n",
673 | " output,\n",
674 | " False,\n",
675 | " enc_padding_mask,\n",
676 | " combined_mask,\n",
677 | " dec_padding_mask)\n",
678 | "\n",
679 | " predictions = predictions[: ,-1:, :]\n",
680 | " predicted_id = tf.cast(tf.argmax(predictions, axis=-1), tf.int32)\n",
681 | "\n",
682 | " if tf.equal(predicted_id, 3):\n",
683 | " return tf.squeeze(output, axis=0), attention_weights\n",
684 | "\n",
685 | " output = tf.concat([output, predicted_id], axis=-1)\n",
686 | "\n",
687 | " return tf.squeeze(output, axis=0), attention_weights"
688 | ]
689 | },
690 | {
691 | "cell_type": "code",
692 | "execution_count": null,
693 | "metadata": {},
694 | "outputs": [],
695 | "source": [
696 | "def translate(sentence, plot=''):\n",
697 | " result, attention_weights = predict(sentence)\n",
698 | " \n",
699 | " predicted_sentence = [idx2de.get(i, 1) for i in result.numpy() if i < len(idx2de) and i not in [0, 2, 3]]\n",
700 | "\n",
701 | " print('Input: {}'.format(sentence))\n",
702 | " print('Predicted translation: {}'.format(\" \".join(predicted_sentence)))\n",
703 | "\n",
704 | " if plot:\n",
705 | " plot_attention_weights(attention_weights, sentence, result, plot)"
706 | ]
707 | },
708 | {
709 | "cell_type": "code",
710 | "execution_count": null,
711 | "metadata": {},
712 | "outputs": [],
713 | "source": [
714 | "translate(\"明 天 就 要 上 班 了\", plot='decoder_layer4_block')\n",
715 | "print(\"Real translation: 還好我沒工作QQ\")"
716 | ]
717 | },
718 | {
719 | "cell_type": "code",
720 | "execution_count": null,
721 | "metadata": {},
722 | "outputs": [],
723 | "source": []
724 | }
725 | ],
726 | "metadata": {
727 | "kernelspec": {
728 | "display_name": "Python 3",
729 | "language": "python",
730 | "name": "python3"
731 | },
732 | "language_info": {
733 | "codemirror_mode": {
734 | "name": "ipython",
735 | "version": 3
736 | },
737 | "file_extension": ".py",
738 | "mimetype": "text/x-python",
739 | "name": "python",
740 | "nbconvert_exporter": "python",
741 | "pygments_lexer": "ipython3",
742 | "version": "3.7.1"
743 | }
744 | },
745 | "nbformat": 4,
746 | "nbformat_minor": 2
747 | }
748 |
--------------------------------------------------------------------------------
/modules_v2.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import print_function
3 | import tensorflow as tf
4 | import numpy as np
5 | import matplotlib.pyplot as plt
6 |
7 |
8 | def positional_encoding(seq_len, num_units, visualization=False):
9 | """
10 | Positional_Encoding for a given tensor.
11 |
12 | Args:
13 | :param inputs: [Tensor], A tensor contains the ids to be search from the lookup table, shape = [batch_size, seq_len]
14 | :param num_units: [Int], Hidden size of embedding
15 | :param visualization: [Boolean], If True, it will plot the graph of position encoding
16 | :return: [Tensor] A tensor with shape [1, seq_len, num_units]
17 | """
18 | def __get_angles(pos, i, d_model):
19 | angle_rates = 1 / np.power(10000, (2 * (i // 2)) / np.float32(d_model))
20 | return pos * angle_rates
21 |
22 | angle_rads = __get_angles(np.arange(seq_len)[:, np.newaxis],
23 | np.arange(num_units)[np.newaxis, :],
24 | num_units)
25 |
26 | sine = np.sin(angle_rads[:, 0::2])
27 | cosine = np.cos(angle_rads[:, 1::2])
28 |
29 | pos_encoding = np.concatenate([sine, cosine], axis=-1)
30 | pos_encoding = pos_encoding[np.newaxis, ...]
31 |
32 | if visualization:
33 | plt.figure(figsize=(12, 8))
34 | plt.pcolormesh(pos_encoding[0], cmap='RdBu')
35 | plt.xlabel('Depth')
36 | plt.xlim((0, num_units))
37 | plt.ylabel('Position')
38 | plt.colorbar()
39 | plt.show()
40 |
41 | return tf.cast(pos_encoding, tf.float32)
42 |
43 |
44 | def scaled_dot_product_attention(q, k, v, mask=None):
45 | """
46 | Calculate the attention weights.
47 |
48 | Args:
49 | :param q: [Tensor], query with shape [..., seq_len_q, d_model]
50 | :param k: [Tensor], key with shape [..., seq_len_k, d_model]
51 | :param v: [Tensor], value with shape [..., seq_len_v, d_model]
52 | :param mask: [Tensor], Float tensor with shape [..., seq_len_q, seq_len_k], default to None
53 | :return: [Tensor], output, attention_weights
54 | """
55 | matmul_qk = tf.matmul(q, k, transpose_b=True)
56 |
57 | dk = tf.cast(tf.shape(k)[-1], tf.float32)
58 | scaled_attention_logits = matmul_qk / tf.math.sqrt(dk)
59 |
60 | # Heuristic mask implementation that add an infinitesimal number so that its effect can be ignored
61 | if mask is not None:
62 | scaled_attention_logits += (mask * -1e9)
63 |
64 | attention_weights = tf.nn.softmax(scaled_attention_logits, axis=-1)
65 | output = tf.matmul(attention_weights, v)
66 |
67 | return output, attention_weights
68 |
69 |
70 | class multihead_attention(tf.keras.layers.Layer):
71 | def __init__(self, d_model, num_heads):
72 | super(multihead_attention, self).__init__()
73 | self.num_heads = num_heads
74 | self.d_model = d_model
75 |
76 | assert d_model % self.num_heads == 0
77 | self.depth = d_model // num_heads
78 |
79 | self.wq = tf.keras.layers.Dense(d_model)
80 | self.wk = tf.keras.layers.Dense(d_model)
81 | self.wv = tf.keras.layers.Dense(d_model)
82 |
83 | self.dense = tf.keras.layers.Dense(d_model)
84 |
85 | def split_heads(self, x, batch_size):
86 | """
87 | Split the last dimension into (num_heads, depth).
88 | Transpose the result such that the shape is (batch_size, num_heads, seq_len, depth).
89 | """
90 |
91 | x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth))
92 | return tf.transpose(x, perm=[0, 2, 1, 3])
93 |
94 | def call(self, v, k, q, mask):
95 | batch_size = tf.shape(q)[0]
96 |
97 | q = self.wq(q)
98 | k = self.wk(k)
99 | v = self.wv(v)
100 |
101 | q = self.split_heads(q, batch_size)
102 | k = self.split_heads(k, batch_size)
103 | v = self.split_heads(v, batch_size)
104 |
105 | scaled_attention, attention_weights = scaled_dot_product_attention(q, k, v, mask)
106 | scaled_attention = tf.transpose(scaled_attention, perm=[0, 2, 1, 3])
107 | concat_attention = tf.reshape(scaled_attention, (batch_size, -1, self.d_model))
108 | output = self.dense(concat_attention)
109 |
110 | return output, attention_weights
111 |
112 |
113 | class pointwise_feedforward(tf.keras.layers.Layer):
114 | def __init__(self, d_model, dff):
115 | super(pointwise_feedforward, self).__init__()
116 | self.d_model = d_model
117 | self.dff = dff
118 |
119 | self.dense_layer_1 = tf.keras.layers.Dense(dff, activation='relu')
120 | self.dense_layer_2 = tf.keras.layers.Dense(d_model)
121 |
122 | def call(self, x):
123 | output = self.dense_layer_1(x)
124 | output = self.dense_layer_2(output)
125 |
126 | return output
127 |
128 |
129 | class EncoderBlock(tf.keras.layers.Layer):
130 | def __init__(self, d_model, num_heads, dff, rate=0.1):
131 | super(EncoderBlock, self).__init__()
132 | self.multi_attn = multihead_attention(d_model, num_heads)
133 | self.ffn = pointwise_feedforward(d_model, dff)
134 |
135 | self.layer_norm_1 = tf.keras.layers.LayerNormalization(epsilon=1e-6)
136 | self.layer_norm_2 = tf.keras.layers.LayerNormalization(epsilon=1e-6)
137 |
138 | self.dropout_1 = tf.keras.layers.Dropout(rate)
139 | self.dropout_2 = tf.keras.layers.Dropout(rate)
140 |
141 | def call(self, x, training, padding_mask):
142 | attn_output, attn_weight = self.multi_attn(x, x, x, padding_mask)
143 | attn_output = self.dropout_1(attn_output, training=training)
144 | output_1 = self.layer_norm_1(x + attn_output)
145 |
146 | ffn_output = self.ffn(output_1)
147 | ffn_output = self.dropout_2(ffn_output, training=training)
148 | output_2 = self.layer_norm_2(output_1 + ffn_output)
149 |
150 | return output_2, attn_weight
151 |
152 |
153 | class DecoderBlock(tf.keras.layers.Layer):
154 | def __init__(self, d_model, num_heads, dff, rate=0.1):
155 | super(DecoderBlock, self).__init__()
156 | self.multi_attn_1 = multihead_attention(d_model, num_heads)
157 | self.multi_attn_2 = multihead_attention(d_model, num_heads)
158 |
159 | self.ffn = pointwise_feedforward(d_model, dff)
160 |
161 | self.layer_norm_1 = tf.keras.layers.LayerNormalization(epsilon=1e-6)
162 | self.layer_norm_2 = tf.keras.layers.LayerNormalization(epsilon=1e-6)
163 | self.layer_norm_3 = tf.keras.layers.LayerNormalization(epsilon=1e-6)
164 |
165 | self.dropout_1 = tf.keras.layers.Dropout(rate)
166 | self.dropout_2 = tf.keras.layers.Dropout(rate)
167 | self.dropout_3 = tf.keras.layers.Dropout(rate)
168 |
169 | def call(self, x, enc_output, training, look_ahead_mask, padding_mask):
170 | attn_output_1, attn_weight_1 = self.multi_attn_1(x, x, x, look_ahead_mask)
171 | attn_output_1 = self.dropout_1(attn_output_1, training=training)
172 | output_1 = self.layer_norm_1(x + attn_output_1)
173 |
174 | attn_output_2, attn_weight_2 = self.multi_attn_2(enc_output, enc_output, output_1, padding_mask)
175 | attn_output_2 = self.dropout_2(attn_output_2, training=training)
176 | output_2 = self.layer_norm_2(output_1 + attn_output_2)
177 |
178 | ffn_output = self.ffn(output_2)
179 | ffn_output = self.dropout_3(ffn_output, training=training)
180 | output_3 = self.layer_norm_3(output_2 + ffn_output)
181 |
182 | return output_3, attn_weight_1, attn_weight_2
183 |
184 |
185 | class Encoder(tf.keras.layers.Layer):
186 | def __init__(self, num_blocks, d_model, num_heads, dff, input_vocab_size, plot_pos_embedding, rate=0.1):
187 | super(Encoder, self).__init__()
188 | self.d_model = d_model
189 | self.num_blocks = num_blocks
190 | self.plot_pos_embedding = plot_pos_embedding
191 |
192 | self.embedding = tf.keras.layers.Embedding(input_vocab_size, d_model)
193 | self.pos_embedding = positional_encoding(input_vocab_size, d_model, plot_pos_embedding)
194 |
195 | self.enc_blocks = [EncoderBlock(d_model, num_heads, dff, rate) for _ in range(num_blocks)]
196 | self.dropout = tf.keras.layers.Dropout(rate)
197 |
198 | def call(self, x, training, padding_mask, attn_dict):
199 | seq_len = tf.shape(x)[1]
200 |
201 | x = self.embedding(x)
202 | x *= tf.math.sqrt(tf.cast(self.d_model, tf.float32))
203 | x += self.pos_embedding[:, :seq_len, :]
204 |
205 | x = self.dropout(x, training=training)
206 |
207 | for i in range(self.num_blocks):
208 | x, attn_weight = self.enc_blocks[i](x, training, padding_mask)
209 | attn_dict['encoder_layer{}_block'.format(i + 1)] = attn_weight
210 |
211 | return x, attn_dict
212 |
213 |
214 | class Decoder(tf.keras.layers.Layer):
215 | def __init__(self, num_blocks, d_model, num_heads, dff, target_vocab_size, plot_pos_embedding, rate=0.1):
216 | super(Decoder, self).__init__()
217 | self.d_model = d_model
218 | self.num_blocks = num_blocks
219 | self.plot_pos_embedding = plot_pos_embedding
220 |
221 | self.embedding = tf.keras.layers.Embedding(target_vocab_size, d_model)
222 | self.pos_embedding = positional_encoding(target_vocab_size, d_model, plot_pos_embedding)
223 |
224 | self.dec_blocks = [DecoderBlock(d_model, num_heads, dff, rate) for _ in range(num_blocks)]
225 | self.dropout = tf.keras.layers.Dropout(rate)
226 |
227 | def call(self, x, enc_output, training, look_ahead_mask, padding_mask, attn_dict):
228 | seq_len = tf.shape(x)[1]
229 |
230 | x = self.embedding(x)
231 | x *= tf.math.sqrt(tf.cast(self.d_model, tf.float32))
232 | x += self.pos_embedding[:, :seq_len, :]
233 |
234 | x = self.dropout(x, training=training)
235 |
236 | for i in range(self.num_blocks):
237 | x, attn_weight_1, attn_weight_2 = self.dec_blocks[i](x, enc_output, training, look_ahead_mask, padding_mask)
238 | attn_dict['decoder_layer{}_block'.format(i + 1)] = attn_weight_1
239 | attn_dict['decoder_layer{}_cross'.format(i + 1)] = attn_weight_2
240 |
241 | return x, attn_dict
242 |
243 |
244 | class Transformer(tf.keras.Model):
245 | def __init__(self, num_blocks, d_model, num_heads, dff, input_vocab_size, target_vocab_size, plot_pos_embedding, rate=0.1):
246 | super(Transformer, self).__init__()
247 |
248 | self.encoder = Encoder(num_blocks, d_model, num_heads, dff, input_vocab_size, plot_pos_embedding, rate)
249 | self.decoder = Decoder(num_blocks, d_model, num_heads, dff, target_vocab_size, plot_pos_embedding, rate)
250 | self.final_layer = tf.keras.layers.Dense(target_vocab_size)
251 |
252 | def call(self, inp, tar, training, enc_padding_mask, look_ahead_mask, dec_padding_mask):
253 | attn_dict = {}
254 |
255 | enc_output, attn_dict = self.encoder(inp, training, enc_padding_mask, attn_dict)
256 | dec_output, attn_dict = self.decoder(tar, enc_output, training, look_ahead_mask, dec_padding_mask, attn_dict)
257 | final_output = self.final_layer(dec_output)
258 |
259 | return final_output, attn_dict
260 |
--------------------------------------------------------------------------------
/old_version/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EternalFeather/Transformer-in-generating-dialogue/fc781a61ee8cfcd0966571f34809ec7308476590/old_version/__init__.py
--------------------------------------------------------------------------------
/old_version/data_loader.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import print_function
3 | from params import Params as pm
4 | import codecs
5 | import sys
6 | import numpy as np
7 | import tensorflow as tf
8 |
9 |
10 | def load_vocab(vocab):
11 | '''
12 | Load word token from encoding dictionary
13 |
14 | Args:
15 | vocab: [String], vocabulary files
16 | '''
17 | vocab = [line.split()[0] for line in codecs.open('dictionary/{}'.format(vocab), 'r', 'utf-8').read().splitlines() if int(line.split()[1]) >= pm.word_limit_size]
18 | word2idx_dic = {word: idx for idx, word in enumerate(vocab)}
19 | idx2word_dic = {idx: word for idx, word in enumerate(vocab)}
20 | return word2idx_dic, idx2word_dic
21 |
22 |
23 | def generate_dataset(source_sents, target_sents):
24 | '''
25 | Parse source sentences and target sentences from corpus with some formats
26 |
27 | Parse word token of each sentences
28 |
29 | Args:
30 | source_sents: [List], encoding sentences from src-train file
31 | target_sents: [List], decoding sentences from tgt-train file
32 |
33 | Padding for word token sentence list
34 | '''
35 | en2idx, idx2en = load_vocab('en.vocab.tsv')
36 | de2idx, idx2de = load_vocab('de.vocab.tsv')
37 |
38 | in_list, out_list, Sources, Targets = [], [], [], []
39 | for source_sent, target_sent in zip(source_sents, target_sents):
40 | # 1 means
41 | inpt = [en2idx.get(word, 1) for word in (source_sent + u" ").split()]
42 | outpt = [de2idx.get(word, 1) for word in (target_sent + u" ").split()]
43 | if max(len(inpt), len(outpt)) <= pm.maxlen:
44 | # sentence token list
45 | in_list.append(np.array(inpt))
46 | out_list.append(np.array(outpt))
47 | # sentence list
48 | Sources.append(source_sent)
49 | Targets.append(target_sent)
50 |
51 | X = np.zeros([len(in_list), pm.maxlen], np.int32)
52 | Y = np.zeros([len(out_list), pm.maxlen], np.int32)
53 | for i, (x, y) in enumerate(zip(in_list, out_list)):
54 | X[i] = np.lib.pad(x, (0, pm.maxlen - len(x)), 'constant', constant_values = (0, 0))
55 | Y[i] = np.lib.pad(y, (0, pm.maxlen - len(y)), 'constant', constant_values = (0, 0))
56 |
57 | return X, Y, Sources, Targets
58 |
59 |
60 | def load_data(l_data):
61 | '''
62 | Read train-data from input datasets
63 |
64 | Args:
65 | l_data: [String], the file name of datasets which used to generate tokens
66 | '''
67 | if l_data == 'train':
68 | en_sents = [line for line in codecs.open(pm.src_train, 'r', 'utf-8').read().split('\n') if line]
69 | de_sents = [line for line in codecs.open(pm.tgt_train, 'r', 'utf-8').read().split('\n') if line]
70 | if len(en_sents) == len(de_sents):
71 | inpt, outpt, Sources, Targets = generate_dataset(en_sents, de_sents)
72 | else:
73 | print("MSG : Source length is different from Target length.")
74 | sys.exit(0)
75 | return inpt, outpt
76 | elif l_data == 'test':
77 | en_sents = [line for line in codecs.open(pm.src_test, 'r', 'utf-8').read().split('\n') if line]
78 | de_sents = [line for line in codecs.open(pm.tgt_test, 'r', 'utf-8').read().split('\n') if line]
79 | if len(en_sents) == len(de_sents):
80 | inpt, outpt, Sources, Targets = generate_dataset(en_sents, de_sents)
81 | else:
82 | print("MSG : Source length is different from Target length.")
83 | sys.exit(0)
84 | return inpt, Sources, Targets
85 | else:
86 | print("MSG : Error when load data.")
87 | sys.exit(0)
88 |
89 |
90 | def get_batch_data():
91 | '''
92 | A batch dataset generator
93 | '''
94 | inpt, outpt = load_data("train")
95 |
96 | batch_num = len(inpt) // pm.batch_size
97 |
98 | inpt = tf.convert_to_tensor(inpt, tf.int32)
99 | outpt = tf.convert_to_tensor(outpt, tf.int32)
100 |
101 | # parsing data into queue used for pipeline operations as a generator.
102 | input_queues = tf.train.slice_input_producer([inpt, outpt])
103 |
104 | # multi-thread processing using batch
105 | x, y = tf.train.shuffle_batch(input_queues,
106 | num_threads = 8,
107 | batch_size = pm.batch_size,
108 | capacity = pm.batch_size * 64,
109 | min_after_dequeue = pm.batch_size * 32,
110 | allow_smaller_final_batch = False)
111 |
112 | return x, y, batch_num
113 |
114 |
115 |
116 |
--------------------------------------------------------------------------------
/old_version/eval.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import print_function
3 | import codecs
4 | import os
5 | from train import Graph
6 | from params import Params as pm
7 | from data_loader import load_data, load_vocab
8 | import tensorflow as tf
9 | import numpy as np
10 | from nltk.translate.bleu_score import corpus_bleu
11 |
12 |
13 | def eval():
14 | g = Graph(is_training = False)
15 | print("MSG : Graph loaded!")
16 |
17 | X, Sources, Targets = load_data('test')
18 | en2idx, idx2en = load_vocab('en.vocab.tsv')
19 | de2idx, idx2de = load_vocab('de.vocab.tsv')
20 |
21 | with g.graph.as_default():
22 | sv = tf.train.Supervisor()
23 | with sv.managed_session(config = tf.ConfigProto(allow_soft_placement = True)) as sess:
24 | # load pre-train model
25 | sv.saver.restore(sess, tf.train.latest_checkpoint(pm.checkpoint))
26 | print("MSG : Restore Model!")
27 |
28 | mname = open(pm.checkpoint + '/checkpoint', 'r').read().split('"')[1]
29 |
30 | if not os.path.exists('Results'):
31 | os.mkdir('Results')
32 | with codecs.open("Results/" + mname, 'w', 'utf-8') as f:
33 | list_of_refs, predict = [], []
34 | # Get a batch
35 | for i in range(len(X) // pm.batch_size):
36 | x = X[i * pm.batch_size: (i + 1) * pm.batch_size]
37 | sources = Sources[i * pm.batch_size: (i + 1) * pm.batch_size]
38 | targets = Targets[i * pm.batch_size: (i + 1) * pm.batch_size]
39 |
40 | # Autoregressive inference
41 | preds = np.zeros((pm.batch_size, pm.maxlen), dtype = np.int32)
42 | for j in range(pm.maxlen):
43 | _preds = sess.run(g.preds, feed_dict = {g.inpt: x, g.outpt: preds})
44 | preds[:, j] = _preds[:, j]
45 |
46 | for source, target, pred in zip(sources, targets, preds):
47 | got = " ".join(idx2de[idx] for idx in pred).split("")[0].strip()
48 | f.write("- Source: {}\n".format(source))
49 | f.write("- Ground Truth: {}\n".format(target))
50 | f.write("- Predict: {}\n\n".format(got))
51 | f.flush()
52 |
53 | # Bleu Score
54 | ref = target.split()
55 | prediction = got.split()
56 | if len(ref) > pm.word_limit_lower and len(prediction) > pm.word_limit_lower:
57 | list_of_refs.append([ref])
58 | predict.append(prediction)
59 |
60 | score = corpus_bleu(list_of_refs, predict)
61 | f.write("Bleu Score = " + str(100 * score))
62 |
63 |
64 | if __name__ == '__main__':
65 | eval()
66 | print("MSG : Done!")
67 |
--------------------------------------------------------------------------------
/old_version/make_dic.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import print_function
3 | from params import Params as pm
4 | import codecs
5 | import os
6 | from collections import Counter
7 |
8 |
9 | def make_dic(path, fname):
10 | '''
11 | Constructs vocabulary as a dictionary
12 |
13 | Args:
14 | path: [String], Input file path
15 | fname: [String], Output file name
16 |
17 | Build vocabulary line by line to dictionary/ path
18 | '''
19 | text = codecs.open(path, 'r', 'utf-8').read()
20 | words = text.split()
21 | wordCount = Counter(words)
22 | if not os.path.exists('dictionary'):
23 | os.mkdir('dictionary')
24 | with codecs.open('dictionary/{}'.format(fname), 'w', 'utf-8') as f:
25 | f.write("{}\t1000000000\n{}\t1000000000\n{}\t1000000000\n{}\t1000000000\n".format("","","",""))
26 | for word, count in wordCount.most_common(len(wordCount)):
27 | f.write(u"{}\t{}\n".format(word, count))
28 |
29 |
30 | if __name__ == '__main__':
31 | make_dic(pm.src_train, "en.vocab.tsv")
32 | make_dic(pm.tgt_train, "de.vocab.tsv")
33 | print("MSG : Constructing Dictionary Finished!")
34 |
35 |
--------------------------------------------------------------------------------
/old_version/modules.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import print_function
3 | import tensorflow as tf
4 | import numpy as np
5 | import math
6 |
7 |
8 | def normalize(inputs,
9 | epsilon = 1e-8,
10 | scope = "ln",
11 | reuse = None):
12 | '''
13 | Implement layer normalization
14 |
15 | Args:
16 | inputs: [Tensor], A tensor with two or more dimensions, where the first one is "batch_size"
17 | epsilon: [Float], A small number for preventing ZeroDivision Error
18 | scope: [String], Optional scope for "variable_scope"
19 | reuse: [Boolean], If to reuse the weights of a previous layer by the same name
20 |
21 | Returns:
22 | A tensor with the same shape and data type as "inputs"
23 | '''
24 | with tf.variable_scope(scope, reuse = reuse):
25 | inputs_shape = inputs.get_shape()
26 | params_shape = inputs_shape[-1 :]
27 |
28 | mean, variance = tf.nn.moments(inputs, [-1], keep_dims = True)
29 | beta = tf.Variable(tf.zeros(params_shape))
30 | gamma = tf.Variable(tf.ones(params_shape))
31 | normalized = (inputs - mean) / ((variance + epsilon) ** (.5))
32 | outputs = gamma * normalized + beta
33 |
34 | return outputs
35 |
36 |
37 | def positional_encoding(inputs,
38 | vocab_size,
39 | num_units,
40 | zero_pad = True,
41 | scale = True,
42 | scope = "positional_embedding",
43 | reuse = None):
44 | '''
45 | Positional_Encoding for a given tensor.
46 |
47 | Args:
48 | inputs: [Tensor], A tensor contains the ids to be search from the lookup table, shape = [batch_size, 1 + len(inpt)]
49 | vocab_size: [Int], Vocabulary size
50 | num_units: [Int], Hidden size of embedding
51 | zero_pad: [Boolean], If True, all the values of the first row(id = 0) should be constant zero
52 | scale: [Boolean], If True, the output will be multiplied by sqrt num_units(check details from paper)
53 | scope: [String], Optional scope for 'variable_scope'
54 | reuse: [Boolean], If to reuse the weights of a previous layer by the same name
55 |
56 | Returns:
57 | A 'Tensor' with one more rank than inputs's, with the dimensionality should be 'num_units'
58 | '''
59 | N, T = inputs.get_shape().as_list()
60 |
61 | with tf.variable_scope(scope, reuse=reuse):
62 | position_ind = tf.tile(tf.expand_dims(tf.range(T), 0), [N, 1])
63 |
64 | # First part of the PE function: sin and cos argument
65 | position_enc = np.array([
66 | [pos / np.power(10000, 2.*i/num_units) for i in range(num_units)]
67 | for pos in range(T)])
68 |
69 | # Second part, apply the cosine to even columns and sin to odds.
70 | position_enc[:, 0::2] = np.sin(position_enc[:, 0::2]) # dim 2i
71 | position_enc[:, 1::2] = np.cos(position_enc[:, 1::2]) # dim 2i+1
72 |
73 | # Convert to a tensor
74 | lookup_table = tf.convert_to_tensor(position_enc)
75 |
76 | if zero_pad:
77 | lookup_table = tf.concat((tf.zeros(shape=[1, num_units]),
78 | lookup_table[1:, :]), 0)
79 | outputs = tf.nn.embedding_lookup(lookup_table, position_ind)
80 |
81 | if scale:
82 | outputs = outputs * num_units**0.5
83 |
84 | return tf.cast(outputs, tf.float32)
85 |
86 |
87 | def embedding(inputs,
88 | vocab_size,
89 | num_units,
90 | zero_pad = True,
91 | scale = True,
92 | scope = "embedding",
93 | reuse = None):
94 | '''
95 | Embed a given tensor.
96 |
97 | Args:
98 | inputs: [Tensor], A tensor contains the ids to be search from the lookup table
99 | vocab_size: [Int], Vocabulary size
100 | num_units: [Int], Hidden size of embedding
101 | zero_pad: [Boolean], If True, all the values of the first row(id = 0) should be constant zero
102 | scale: [Boolean], If True, the output will be multiplied by sqrt num_units(check details from paper)
103 | scope: [String], Optional scope for 'variable_scope'
104 | reuse: [Boolean], If to reuse the weights of a previous layer by the same name
105 |
106 | Returns:
107 | A 'Tensor' with one more rank than inputs's, with the dimensionality should be 'num_units'
108 | '''
109 | with tf.variable_scope(scope, reuse = reuse):
110 | lookup_table = tf.get_variable('lookup_table',
111 | dtype = tf.float32,
112 | shape = [vocab_size, num_units],
113 | initializer = tf.contrib.layers.xavier_initializer())
114 |
115 | if zero_pad:
116 | lookup_table = tf.concat((tf.zeros(shape = [1, num_units]),
117 | lookup_table[1:, :]), 0)
118 | outputs = tf.nn.embedding_lookup(lookup_table, inputs)
119 |
120 | if scale:
121 | outputs = outputs * math.sqrt(num_units)
122 |
123 | return outputs
124 |
125 |
126 | def multihead_attention(queries,
127 | keys,
128 | num_units = None,
129 | num_heads = 8,
130 | dropout_rate = 0,
131 | is_training = True,
132 | causality = False,
133 | scope = "multihead_attention",
134 | reuse = None):
135 | '''
136 | Implement multihead attention
137 |
138 | Args:
139 | queries: [Tensor], A 3-dimensions tensor with shape of [N, T_q, S_q]
140 | keys: [Tensor], A 3-dimensions tensor with shape of [N, T_k, S_k]
141 | num_units: [Int], Attention size
142 | num_heads: [Int], Number of heads
143 | dropout_rate: [Float], A ratio of dropout
144 | is_training: [Boolean], If true, controller of mechanism for dropout
145 | causality: [Boolean], If true, units that reference the future are masked
146 | scope: [String], Optional scope for "variable_scope"
147 | reuse: [Boolean], If to reuse the weights of a previous layer by the same name
148 |
149 | Returns:
150 | A 3-dimensions tensor with shape of [N, T_q, S]
151 | '''
152 | with tf.variable_scope(scope, reuse = reuse):
153 | if num_units is None:
154 | # length of sentence
155 | num_units = queries.get_shape().as_list()[-1]
156 |
157 | # Linear layers in Figure 2(right)
158 | # shape = [N, T_q, S]
159 | Q = tf.layers.dense(queries, num_units, activation = tf.nn.relu)
160 | # shape = [N, T_k, S]
161 | K = tf.layers.dense(keys, num_units, activation = tf.nn.relu)
162 | # shape = [N, T_k, S]
163 | V = tf.layers.dense(keys, num_units, activation = tf.nn.relu)
164 |
165 | # Split and concat
166 | # shape = [N*h, T_q, S/h]
167 | Q_ = tf.concat(tf.split(Q, num_heads, axis = 2), axis = 0)
168 | # shape = [N*h, T_k, S/h]
169 | K_ = tf.concat(tf.split(K, num_heads, axis = 2), axis = 0)
170 | # shape = [N*h, T_k, S/h]
171 | V_ = tf.concat(tf.split(V, num_heads, axis = 2), axis = 0)
172 |
173 | # shape = [N*h, T_q, T_k]
174 | outputs = tf.matmul(Q_, tf.transpose(K_, [0, 2, 1]))
175 |
176 | # Scale
177 | outputs = outputs / (K_.get_shape().as_list()[-1] ** 0.5)
178 |
179 | # Masking
180 | # shape = [N, T_k]
181 | key_masks = tf.sign(tf.abs(tf.reduce_sum(keys, axis = -1)))
182 | # shape = [N*h, T_k]
183 | key_masks = tf.tile(key_masks, [num_heads, 1])
184 | # shape = [N*h, T_q, T_k]
185 | key_masks = tf.tile(tf.expand_dims(key_masks, 1), [1, tf.shape(queries)[1], 1])
186 |
187 | # If key_masks == 0 outputs = [1]*length(outputs)
188 | paddings = tf.ones_like(outputs) * (-math.pow(2, 32) + 1)
189 | # shape = [N*h, T_q, T_k]
190 | outputs = tf.where(tf.equal(key_masks, 0), paddings, outputs)
191 |
192 | if causality:
193 | # reduce dims : shape = [T_q, T_k]
194 | diag_vals = tf.ones_like(outputs[0, :, :])
195 | # shape = [T_q, T_k]
196 | # use triangular matrix to ignore the affect from future words
197 | # like : [[1,0,0]
198 | # [1,2,0]
199 | # [1,2,3]]
200 | tril = tf.contrib.linalg.LinearOperatorTriL(diag_vals).to_dense()
201 | # shape = [N*h, T_q, T_k]
202 | masks = tf.tile(tf.expand_dims(tril, 0), [tf.shape(outputs)[0], 1, 1])
203 |
204 | paddings = tf.ones_like(masks) * (-math.pow(2, 32) + 1)
205 | # shape = [N*h, T_q, T_k]
206 | outputs = tf.where(tf.equal(masks, 0), paddings, outputs)
207 |
208 | # Output Activation
209 | outputs = tf.nn.softmax(outputs)
210 |
211 | # Query Masking
212 | # shape = [N, T_q]
213 | query_masks = tf.sign(tf.abs(tf.reduce_sum(queries, axis = -1)))
214 | # shape = [N*h, T_q]
215 | query_masks = tf.tile(query_masks, [num_heads, 1])
216 | # shape = [N*h, T_q, T_k]
217 | query_masks = tf.tile(tf.expand_dims(query_masks, -1), [1, 1, tf.shape(keys)[1]])
218 | outputs *= query_masks
219 |
220 | # Dropouts
221 | outputs = tf.layers.dropout(outputs, rate = dropout_rate, training = tf.convert_to_tensor(is_training))
222 |
223 | # Weighted sum
224 | # shape = [N*h, T_q, S/h]
225 | outputs = tf.matmul(outputs, V_)
226 |
227 | # Restore shape
228 | # shape = [N, T_q, S]
229 | outputs = tf.concat(tf.split(outputs, num_heads, axis = 0), axis = 2)
230 |
231 | # Residual connection
232 | outputs += queries
233 |
234 | # Normalize
235 | # shape = [N, T_q, S]
236 | outputs = normalize(outputs)
237 |
238 | return outputs
239 |
240 |
241 | def feedforward(inputs,
242 | num_units = [2048, 512],
243 | scope = "multihead_attention",
244 | reuse = None):
245 | '''
246 | Position-wise feed forward neural network
247 |
248 | Args:
249 | inputs: [Tensor], A 3d tensor with shape [N, T, S]
250 | num_units: [Int], A list of convolution parameters
251 | scope: [String], Optional scope for "variable_scope"
252 | reuse: [Boolean], If to reuse the weights of a previous layer by the same name
253 |
254 | Return:
255 | A tensor converted by feedforward layers from inputs
256 | '''
257 |
258 | with tf.variable_scope(scope, reuse = reuse):
259 | # params = {"inputs": inputs, "filters": num_units[0], "kernel_size": 1, \
260 | # "activation": tf.nn.relu, "use_bias": True}
261 | # outputs = tf.layers.conv1d(inputs = inputs, filters = num_units[0], kernel_size = 1, activation = tf.nn.relu, use_bias = True)
262 | # outputs = tf.layers.conv1d(**params)
263 | params = {"inputs": inputs, "num_outputs": num_units[0], \
264 | "activation_fn": tf.nn.relu}
265 | outputs = tf.contrib.layers.fully_connected(**params)
266 |
267 | # params = {"inputs": inputs, "filters": num_units[1], "kernel_size": 1, \
268 | # "activation": None, "use_bias": True}
269 | params = {"inputs": inputs, "num_outputs": num_units[1], \
270 | "activation_fn": None}
271 | # outputs = tf.layers.conv1d(inputs = inputs, filters = num_units[1], kernel_size = 1, activation = None, use_bias = True)
272 | # outputs = tf.layers.conv1d(**params)
273 | outputs = tf.contrib.layers.fully_connected(**params)
274 |
275 | # residual connection
276 | outputs += inputs
277 |
278 | outputs = normalize(outputs)
279 |
280 | return outputs
281 |
282 |
283 | def label_smoothing(inputs, epsilon = 0.1):
284 | '''
285 | Implement label smoothing
286 |
287 | Args:
288 | inputs: [Tensor], A 3d tensor with shape of [N, T, V]
289 | epsilon: [Float], Smoothing rate
290 |
291 | Return:
292 | A tensor after smoothing
293 | '''
294 |
295 | K = inputs.get_shape().as_list()[-1]
296 | return ((1 - epsilon) * inputs) + (epsilon / K)
297 |
--------------------------------------------------------------------------------
/old_version/params.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | class Params:
3 | '''
4 | Parameters of our model
5 | '''
6 | src_train = "../data/src-train.txt"
7 | tgt_train = "../data/tgt-train.txt"
8 | src_test = "../data/src-val.txt"
9 | tgt_test = "../data/tgt-val.txt"
10 |
11 | maxlen = 10
12 | batch_size = 32
13 | hidden_units = 512
14 | logdir = 'logdir'
15 | num_epochs = 250
16 | num_identical = 6
17 | num_heads = 8
18 | dropout = 0.1
19 | learning_rate = 0.0001
20 | word_limit_size = 20
21 | word_limit_lower = 3
22 | checkpoint = 'checkpoint'
23 |
--------------------------------------------------------------------------------
/old_version/requirements.txt:
--------------------------------------------------------------------------------
1 | nltk==3.4
2 | numpy==1.15.4
3 | tqdm==4.28.1
4 | tensorflow-gpu==1.12.0
--------------------------------------------------------------------------------
/old_version/train.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import print_function
3 | import tensorflow as tf
4 | from params import Params as pm
5 | from data_loader import get_batch_data, load_vocab
6 | from modules import *
7 | from tqdm import tqdm
8 | import os
9 |
10 |
11 | class Graph():
12 | def __init__(self, is_training = True):
13 | self.graph = tf.Graph()
14 | with self.graph.as_default():
15 | if is_training:
16 | self.inpt, self.outpt, self.batch_num = get_batch_data()
17 | else:
18 | self.inpt = tf.placeholder(tf.int32, shape = (None, pm.maxlen))
19 | self.outpt = tf.placeholder(tf.int32, shape = (None, pm.maxlen))
20 |
21 | # start with 2() and without 3()
22 | self.decoder_input = tf.concat((tf.ones_like(self.outpt[:, :1])*2, self.outpt[:, :-1]), -1)
23 |
24 | en2idx, idx2en = load_vocab('en.vocab.tsv')
25 | de2idx, idx2de = load_vocab('de.vocab.tsv')
26 |
27 | # Encoder
28 | with tf.variable_scope("encoder"):
29 | self.enc = embedding(self.inpt,
30 | vocab_size = len(en2idx),
31 | num_units = pm.hidden_units,
32 | scale = True,
33 | scope = "enc_embed")
34 |
35 | # Position Encoding(use range from 0 to len(inpt) to represent position dim of each words)
36 | # tf.tile(tf.expand_dims(tf.range(tf.shape(self.inpt)[1]), 0), [tf.shape(self.inpt)[0], 1]),
37 | self.enc += positional_encoding(self.inpt,
38 | vocab_size = pm.maxlen,
39 | num_units = pm.hidden_units,
40 | zero_pad = False,
41 | scale = False,
42 | scope = "enc_pe")
43 |
44 | # Dropout
45 | self.enc = tf.layers.dropout(self.enc,
46 | rate = pm.dropout,
47 | training = tf.convert_to_tensor(is_training))
48 |
49 | # Identical
50 | for i in range(pm.num_identical):
51 | with tf.variable_scope("num_identical_{}".format(i)):
52 | # Multi-head Attention
53 | self.enc = multihead_attention(queries = self.enc,
54 | keys = self.enc,
55 | num_units = pm.hidden_units,
56 | num_heads = pm.num_heads,
57 | dropout_rate = pm.dropout,
58 | is_training = is_training,
59 | causality = False)
60 |
61 | self.enc = feedforward(self.enc, num_units = [4 * pm.hidden_units, pm.hidden_units])
62 |
63 | # Decoder
64 | with tf.variable_scope("decoder"):
65 | self.dec = embedding(self.decoder_input,
66 | vocab_size = len(de2idx),
67 | num_units = pm.hidden_units,
68 | scale = True,
69 | scope = "dec_embed")
70 |
71 | # Position Encoding(use range from 0 to len(inpt) to represent position dim)
72 | self.dec += positional_encoding(self.decoder_input,
73 | vocab_size = pm.maxlen,
74 | num_units = pm.hidden_units,
75 | zero_pad = False,
76 | scale = False,
77 | scope = "dec_pe")
78 |
79 | # Dropout
80 | self.dec = tf.layers.dropout(self.dec,
81 | rate = pm.dropout,
82 | training = tf.convert_to_tensor(is_training))
83 |
84 | # Identical
85 | for i in range(pm.num_identical):
86 | with tf.variable_scope("num_identical_{}".format(i)):
87 | # Multi-head Attention(self-attention)
88 | self.dec = multihead_attention(queries = self.dec,
89 | keys = self.dec,
90 | num_units = pm.hidden_units,
91 | num_heads = pm.num_heads,
92 | dropout_rate = pm.dropout,
93 | is_training = is_training,
94 | causality = True,
95 | scope = "self_attention")
96 |
97 | # Multi-head Attention(vanilla-attention)
98 | self.dec = multihead_attention(queries=self.dec,
99 | keys=self.enc,
100 | num_units=pm.hidden_units,
101 | num_heads=pm.num_heads,
102 | dropout_rate=pm.dropout,
103 | is_training=is_training,
104 | causality=False,
105 | scope="vanilla_attention")
106 |
107 | self.dec = feedforward(self.dec, num_units = [4 * pm.hidden_units, pm.hidden_units])
108 |
109 | # Linear
110 | self.logits = tf.layers.dense(self.dec, len(de2idx))
111 | self.preds = tf.to_int32(tf.arg_max(self.logits, dimension = -1))
112 | self.istarget = tf.to_float(tf.not_equal(self.outpt, 0))
113 | self.acc = tf.reduce_sum(tf.to_float(tf.equal(self.preds, self.outpt)) * self.istarget) / (tf.reduce_sum(self.istarget))
114 | tf.summary.scalar('acc', self.acc)
115 |
116 | if is_training:
117 | # smooth inputs
118 | self.y_smoothed = label_smoothing(tf.one_hot(self.outpt, depth = len(de2idx)))
119 | # loss function
120 | self.loss = tf.nn.softmax_cross_entropy_with_logits(logits = self.logits, labels = self.y_smoothed)
121 | self.mean_loss = tf.reduce_sum(self.loss * self.istarget) / (tf.reduce_sum(self.istarget))
122 |
123 | self.global_step = tf.Variable(0, name = 'global_step', trainable = False)
124 | # optimizer
125 | self.optimizer = tf.train.AdamOptimizer(learning_rate = pm.learning_rate, beta1 = 0.9, beta2 = 0.98, epsilon = 1e-8)
126 | self.train_op = self.optimizer.minimize(self.mean_loss, global_step = self.global_step)
127 |
128 | tf.summary.scalar('mean_loss', self.mean_loss)
129 | self.merged = tf.summary.merge_all()
130 |
131 |
132 | if __name__ == '__main__':
133 | en2idx, idx2en = load_vocab('en.vocab.tsv')
134 | de2idx, idx2de = load_vocab('de.vocab.tsv')
135 |
136 | g = Graph(True)
137 | print("MSG : Graph loaded!")
138 |
139 | # save model and use this model to training
140 | supvisor = tf.train.Supervisor(graph = g.graph,
141 | logdir = pm.logdir,
142 | save_model_secs = 0)
143 |
144 | with supvisor.managed_session() as sess:
145 | for epoch in range(1, pm.num_epochs + 1):
146 | if supvisor.should_stop():
147 | break
148 | # process bar
149 | for step in tqdm(range(g.batch_num), total = g.batch_num, ncols = 70, leave = False, unit = 'b'):
150 | sess.run(g.train_op)
151 |
152 | if not os.path.exists(pm.checkpoint):
153 | os.mkdir(pm.checkpoint)
154 | g_step = sess.run(g.global_step)
155 | supvisor.saver.save(sess, pm.checkpoint + '/model_epoch_%02d_gs_%d' % (epoch, g_step))
156 |
157 | print("MSG : Done!")
158 |
159 |
--------------------------------------------------------------------------------
/params.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | class Params:
3 | """
4 | Parameters of our model.
5 | """
6 | project_name = 'demo'
7 | vocab_path = "dictionary/"
8 | src_train = "data/src-train.txt"
9 | tgt_train = "data/tgt-train.txt"
10 | src_test = "data/src-val.txt"
11 | tgt_test = "data/tgt-val.txt"
12 |
13 | train_record = "data/processed/{}/train.tfrecord".format(project_name)
14 | test_record = "data/processed/{}/val.tfrecord".format(project_name)
15 | logdir = 'logdir'
16 | ckpt_path = 'checkpoint/{}'.format(project_name)
17 | eval_log_path = 'result/{}'.format(project_name)
18 |
19 | rebuild_vocabulary = False
20 |
21 | maxlen = 12
22 | buffer_size = 10000
23 | batch_size = 128
24 | word_limit_size = 5
25 |
26 | d_model = 512
27 | dff = 2048
28 | num_epochs = 10
29 | num_block = 6
30 | num_heads = 8
31 | dropout_rate = 0.1
32 | smooth_epsilon = 0.1
33 | learning_rate = 1e-4
34 | learning_rate_warmup_steps = 4000
35 | beta_1 = 0.9
36 | beta_2 = 0.98
37 | epsilon = 1e-9
38 | batch_show_every = 500
39 | epoch_show_every = 1
40 | plot_pos_embedding = False
41 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | nltk==3.4
2 | numpy==1.15.4
3 | tqdm==4.28.1
4 | tensorflow-gpu==2.0.0-alpha0
5 | matplotlib==3.0.2
--------------------------------------------------------------------------------
/tf1.12.0-eager/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EternalFeather/Transformer-in-generating-dialogue/fc781a61ee8cfcd0966571f34809ec7308476590/tf1.12.0-eager/__init__.py
--------------------------------------------------------------------------------
/tf1.12.0-eager/bleu.py:
--------------------------------------------------------------------------------
1 | # Copyright 2017 Google Inc. All Rights Reserved.
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | # ==============================================================================
15 |
16 | """Python implementation of BLEU and smooth-BLEU.
17 | This module provides a Python implementation of BLEU and smooth-BLEU.
18 | Smooth BLEU is computed following the method outlined in the paper:
19 | Chin-Yew Lin, Franz Josef Och. ORANGE: a method for evaluating automatic
20 | evaluation metrics for machine translation. COLING 2004.
21 | """
22 |
23 | import collections
24 | import math
25 |
26 |
27 | def _get_ngrams(segment, max_order):
28 | """Extracts all n-grams upto a given maximum order from an input segment.
29 | Args:
30 | segment: text segment from which n-grams will be extracted.
31 | max_order: maximum length in tokens of the n-grams returned by this
32 | methods.
33 | Returns:
34 | The Counter containing all n-grams upto max_order in segment
35 | with a count of how many times each n-gram occurred.
36 | """
37 | ngram_counts = collections.Counter()
38 | for order in range(1, max_order + 1):
39 | for i in range(0, len(segment) - order + 1):
40 | ngram = tuple(segment[i:i+order])
41 | ngram_counts[ngram] += 1
42 | return ngram_counts
43 |
44 |
45 | def compute_bleu(reference_corpus, translation_corpus, max_order=4,
46 | smooth=False, order_weights=True):
47 | """Computes BLEU score of translated segments against one or more references.
48 | Args:
49 | reference_corpus: list of lists of references for each translation. Each
50 | reference should be tokenized into a list of tokens.
51 | translation_corpus: list of translations to score. Each translation
52 | should be tokenized into a list of tokens.
53 | max_order: Maximum n-gram order to use when computing BLEU score.
54 | smooth: Whether or not to apply Lin et al. 2004 smoothing.
55 |
56 | order_weights: Use different weights to control accuracy. The longer, the more important.
57 | Default to True.
58 |
59 | Returns:
60 | 3-Tuple with the BLEU score, n-gram precisions, geometric mean of n-gram
61 | precisions and brevity penalty.
62 | """
63 | matches_by_order = [0] * max_order
64 | possible_matches_by_order = [0] * max_order
65 | reference_length = 0
66 | translation_length = 0
67 |
68 | empty_error_flag = False
69 |
70 | for (references, translation) in zip(reference_corpus,
71 | translation_corpus):
72 | if len(references) == 0 or len(translation) == 0:
73 | empty_error_flag = True
74 | break
75 |
76 | reference_length += min(len(r) for r in references)
77 | translation_length += len(translation)
78 |
79 | merged_ref_ngram_counts = collections.Counter()
80 | for reference in references:
81 | merged_ref_ngram_counts |= _get_ngrams(reference, max_order)
82 | translation_ngram_counts = _get_ngrams(translation, max_order)
83 | overlap = translation_ngram_counts & merged_ref_ngram_counts
84 |
85 | for ngram in overlap:
86 | matches_by_order[len(ngram)-1] += overlap[ngram]
87 | for order in range(1, max_order+1):
88 | possible_matches = len(translation) - order + 1
89 | if possible_matches > 0:
90 | possible_matches_by_order[order-1] += possible_matches
91 |
92 | if empty_error_flag:
93 | return 0.0, None, None, None, None, None
94 |
95 | precisions = [0] * max_order
96 | for i in range(0, max_order):
97 | if smooth:
98 | precisions[i] = ((matches_by_order[i] + 1.) /
99 | (possible_matches_by_order[i] + 1.))
100 | else:
101 | if possible_matches_by_order[i] > 0:
102 | precisions[i] = (float(matches_by_order[i]) /
103 | possible_matches_by_order[i])
104 | else:
105 | precisions[i] = 0.0
106 |
107 | if max(precisions) > 0:
108 | if order_weights:
109 | p_log_sum = sum((1. / (i + 1)) * math.log(p) for i, p in enumerate(reversed(precisions)) if p > 0)
110 | else:
111 | p_log_sum = sum((1. / max_order) * math.log(p) for p in precisions if p > 0)
112 | geo_mean = math.exp(p_log_sum)
113 | else:
114 | geo_mean = 0
115 |
116 | ratio = float(translation_length) / reference_length
117 |
118 | if ratio > 1.0:
119 | bp = 1.
120 | else:
121 | bp = math.exp(1 - 1. / ratio)
122 |
123 | bleu = geo_mean * bp
124 |
125 | return bleu, precisions, bp, ratio, translation_length, reference_length
126 |
127 |
128 | def bleu_metrics(per_segment_references, translations, smooth=False, max_order=3, order_weights=True):
129 | """Compute BLEU scores"""
130 | # bleu_score, precisions, bp, ratio, translation_length, reference_length
131 | bleu_score, _, _, _, _, _ = compute_bleu(
132 | per_segment_references, translations, max_order, smooth, order_weights)
133 |
134 | return 100 * bleu_score
135 |
136 |
--------------------------------------------------------------------------------
/tf1.12.0-eager/main.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "metadata": {},
7 | "outputs": [],
8 | "source": [
9 | "from __future__ import absolute_import, division, print_function, unicode_literals\n",
10 | "\n",
11 | "import tensorflow as tf\n",
12 | "\n",
13 | "import time\n",
14 | "import os\n",
15 | "from tqdm import tqdm\n",
16 | "import numpy as np\n",
17 | "\n",
18 | "from params import Params as pm\n",
19 | "from utils import en2idx, idx2en, de2idx, idx2de, dump2record, build_dataset, LRSchedule, masking, create_masks\n",
20 | "from bleu import bleu_metrics"
21 | ]
22 | },
23 | {
24 | "cell_type": "code",
25 | "execution_count": null,
26 | "metadata": {},
27 | "outputs": [],
28 | "source": [
29 | "tf.enable_eager_execution()"
30 | ]
31 | },
32 | {
33 | "cell_type": "code",
34 | "execution_count": null,
35 | "metadata": {},
36 | "outputs": [],
37 | "source": [
38 | "tf.__version__"
39 | ]
40 | },
41 | {
42 | "cell_type": "markdown",
43 | "metadata": {},
44 | "source": [
45 | "---"
46 | ]
47 | },
48 | {
49 | "cell_type": "code",
50 | "execution_count": null,
51 | "metadata": {},
52 | "outputs": [],
53 | "source": [
54 | "def get_data(corpus_file):\n",
55 | " return open(corpus_file, 'r', encoding='utf-8').read().splitlines()"
56 | ]
57 | },
58 | {
59 | "cell_type": "code",
60 | "execution_count": null,
61 | "metadata": {},
62 | "outputs": [],
63 | "source": [
64 | "src_train, src_val = get_data(pm.src_train), get_data(pm.src_test)\n",
65 | "tgt_train, tgt_val = get_data(pm.tgt_train), get_data(pm.tgt_test)"
66 | ]
67 | },
68 | {
69 | "cell_type": "code",
70 | "execution_count": null,
71 | "metadata": {},
72 | "outputs": [],
73 | "source": [
74 | "dump2record(pm.train_record, src_train, tgt_train)\n",
75 | "dump2record(pm.test_record, src_val, tgt_val)"
76 | ]
77 | },
78 | {
79 | "cell_type": "code",
80 | "execution_count": null,
81 | "metadata": {},
82 | "outputs": [],
83 | "source": [
84 | "# train_dataset = build_dataset(mode='array', corpus=[src_train, tgt_train], is_training=True)\n",
85 | "# val_dataset = build_dataset(mode='array', corpus=[src_val, tgt_val], is_training=True)\n",
86 | "\n",
87 | "train_dataset = build_dataset(mode='file', filename=pm.train_record, is_training=True)\n",
88 | "val_dataset = build_dataset(mode='file', filename=pm.test_record, is_training=True)"
89 | ]
90 | },
91 | {
92 | "cell_type": "code",
93 | "execution_count": null,
94 | "metadata": {},
95 | "outputs": [],
96 | "source": [
97 | "next(iter(train_dataset))"
98 | ]
99 | },
100 | {
101 | "cell_type": "markdown",
102 | "metadata": {},
103 | "source": [
104 | "---"
105 | ]
106 | },
107 | {
108 | "cell_type": "code",
109 | "execution_count": null,
110 | "metadata": {},
111 | "outputs": [],
112 | "source": [
113 | "from modules import positional_encoding, scaled_dot_product_attention, multihead_attention, pointwise_feedforward, EncoderBlock, DecoderBlock, Encoder, Decoder, Transformer"
114 | ]
115 | },
116 | {
117 | "cell_type": "markdown",
118 | "metadata": {},
119 | "source": [
120 | "# Positional encoding\n",
121 | "$$\\Large{PE_{(pos, 2i)} = sin(pos / 10000^{2i / d_{model}})} $$\n",
122 | "$$\\Large{PE_{(pos, 2i+1)} = cos(pos / 10000^{2i / d_{model}})} $$"
123 | ]
124 | },
125 | {
126 | "cell_type": "code",
127 | "execution_count": null,
128 | "metadata": {},
129 | "outputs": [],
130 | "source": [
131 | "pos_encoding = positional_encoding(50, 512, True)\n",
132 | "print(pos_encoding.shape)"
133 | ]
134 | },
135 | {
136 | "cell_type": "markdown",
137 | "metadata": {},
138 | "source": [
139 | "# Masking"
140 | ]
141 | },
142 | {
143 | "cell_type": "code",
144 | "execution_count": null,
145 | "metadata": {},
146 | "outputs": [],
147 | "source": [
148 | "x = tf.constant([[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]])\n",
149 | "masking(x, task='padding')"
150 | ]
151 | },
152 | {
153 | "cell_type": "code",
154 | "execution_count": null,
155 | "metadata": {},
156 | "outputs": [],
157 | "source": [
158 | "masking(x, task='look_ahead')"
159 | ]
160 | },
161 | {
162 | "cell_type": "markdown",
163 | "metadata": {},
164 | "source": [
165 | "# Scaled dot product attention"
166 | ]
167 | },
168 | {
169 | "cell_type": "markdown",
170 | "metadata": {},
171 | "source": [
172 | "\n",
173 | "$$\\Large{Attention(Q, K, V) = softmax_k(\\frac{QK^T}{\\sqrt{d_k}}) V} $$"
174 | ]
175 | },
176 | {
177 | "cell_type": "code",
178 | "execution_count": null,
179 | "metadata": {},
180 | "outputs": [],
181 | "source": [
182 | "def print_out(q, k, v):\n",
183 | " temp_out, temp_attn = scaled_dot_product_attention(q, k, v, None)\n",
184 | " print ('Attention weights are:')\n",
185 | " print (temp_attn)\n",
186 | " print ('Output is:')\n",
187 | " print (temp_out)"
188 | ]
189 | },
190 | {
191 | "cell_type": "code",
192 | "execution_count": null,
193 | "metadata": {},
194 | "outputs": [],
195 | "source": [
196 | "np.set_printoptions(suppress=True)\n",
197 | "\n",
198 | "temp_k = tf.constant([[10,0,0],\n",
199 | " [0,10,0],\n",
200 | " [0,0,10],\n",
201 | " [0,0,10]], dtype=tf.float32)\n",
202 | "\n",
203 | "temp_v = tf.constant([[ 1,0],\n",
204 | " [ 10,0],\n",
205 | " [ 100,5],\n",
206 | " [1000,6]], dtype=tf.float32)\n",
207 | "\n",
208 | "temp_q = tf.constant([[0, 10, 0]], dtype=tf.float32)\n",
209 | "print_out(temp_q, temp_k, temp_v)"
210 | ]
211 | },
212 | {
213 | "cell_type": "code",
214 | "execution_count": null,
215 | "metadata": {},
216 | "outputs": [],
217 | "source": [
218 | "temp_q = tf.constant([[0, 0, 10]], dtype=tf.float32)\n",
219 | "print_out(temp_q, temp_k, temp_v)"
220 | ]
221 | },
222 | {
223 | "cell_type": "code",
224 | "execution_count": null,
225 | "metadata": {},
226 | "outputs": [],
227 | "source": [
228 | "temp_q = tf.constant([[0, 0, 10], [0, 10, 0], [10, 10, 0]], dtype=tf.float32)\n",
229 | "print_out(temp_q, temp_k, temp_v)"
230 | ]
231 | },
232 | {
233 | "cell_type": "markdown",
234 | "metadata": {},
235 | "source": [
236 | "# Multi-head attention"
237 | ]
238 | },
239 | {
240 | "cell_type": "markdown",
241 | "metadata": {},
242 | "source": [
243 | ""
244 | ]
245 | },
246 | {
247 | "cell_type": "markdown",
248 | "metadata": {},
249 | "source": [
250 | "- **Tips: Dimention-level split**"
251 | ]
252 | },
253 | {
254 | "cell_type": "code",
255 | "execution_count": null,
256 | "metadata": {},
257 | "outputs": [],
258 | "source": [
259 | "temp_mha = multihead_attention(d_model=512, num_heads=8)\n",
260 | "y = tf.random.uniform((1, 50, 512))\n",
261 | "out, attn = temp_mha(y, k=y, q=y, mask=None)\n",
262 | "out.shape, attn.shape"
263 | ]
264 | },
265 | {
266 | "cell_type": "markdown",
267 | "metadata": {},
268 | "source": [
269 | "# Pointwise feed forward network"
270 | ]
271 | },
272 | {
273 | "cell_type": "code",
274 | "execution_count": null,
275 | "metadata": {},
276 | "outputs": [],
277 | "source": [
278 | "sample_ffn = pointwise_feedforward(512, 2048)\n",
279 | "sample_ffn(tf.random.uniform((64, 50, 512))).shape"
280 | ]
281 | },
282 | {
283 | "cell_type": "markdown",
284 | "metadata": {},
285 | "source": [
286 | "# Whole model (Encoder & Decoder)\n",
287 | ""
288 | ]
289 | },
290 | {
291 | "cell_type": "markdown",
292 | "metadata": {},
293 | "source": [
294 | "## Encoder"
295 | ]
296 | },
297 | {
298 | "cell_type": "code",
299 | "execution_count": null,
300 | "metadata": {},
301 | "outputs": [],
302 | "source": [
303 | "sample_encoder_layer = EncoderBlock(512, 8, 2048)\n",
304 | "sample_encoder_layer_output, _ = sample_encoder_layer(tf.random.uniform((64, 43, 512)), False, None)\n",
305 | "sample_encoder_layer_output.shape"
306 | ]
307 | },
308 | {
309 | "cell_type": "markdown",
310 | "metadata": {},
311 | "source": [
312 | "## Decoder"
313 | ]
314 | },
315 | {
316 | "cell_type": "code",
317 | "execution_count": null,
318 | "metadata": {},
319 | "outputs": [],
320 | "source": [
321 | "sample_decoder_layer = DecoderBlock(512, 8, 2048)\n",
322 | "\n",
323 | "sample_decoder_layer_output, _, _ = sample_decoder_layer(\n",
324 | " tf.random.uniform((64, 50, 512)), sample_encoder_layer_output, \n",
325 | " False, None, None)\n",
326 | "\n",
327 | "sample_decoder_layer_output.shape"
328 | ]
329 | },
330 | {
331 | "cell_type": "markdown",
332 | "metadata": {},
333 | "source": [
334 | "## Packed Encoder & Decoder"
335 | ]
336 | },
337 | {
338 | "cell_type": "code",
339 | "execution_count": null,
340 | "metadata": {},
341 | "outputs": [],
342 | "source": [
343 | "sample_encoder = Encoder(num_blocks=2, d_model=512, num_heads=8, dff=2048, input_vocab_size=8500, plot_pos_embedding=False)\n",
344 | "attn_dict = {}\n",
345 | "sample_encoder_output, attn_dict = sample_encoder(tf.random.uniform((64, 62)), training=False, padding_mask=None, attn_dict=attn_dict)\n",
346 | "sample_encoder_output.shape"
347 | ]
348 | },
349 | {
350 | "cell_type": "code",
351 | "execution_count": null,
352 | "metadata": {},
353 | "outputs": [],
354 | "source": [
355 | "sample_decoder = Decoder(num_blocks=2, d_model=512, num_heads=8, dff=2048, target_vocab_size=8000, plot_pos_embedding=False)\n",
356 | "output, attn_dict = sample_decoder(tf.random.uniform((64, 26)), \n",
357 | " enc_output=sample_encoder_output, \n",
358 | " training=False, look_ahead_mask=None, \n",
359 | " padding_mask=None, attn_dict=attn_dict)\n",
360 | "output.shape, attn_dict['decoder_layer2_block'].shape"
361 | ]
362 | },
363 | {
364 | "cell_type": "markdown",
365 | "metadata": {},
366 | "source": [
367 | "# Transformer"
368 | ]
369 | },
370 | {
371 | "cell_type": "code",
372 | "execution_count": null,
373 | "metadata": {},
374 | "outputs": [],
375 | "source": [
376 | "sample_transformer = Transformer(num_blocks=2, d_model=512, num_heads=8, dff=2048, input_vocab_size=8500, target_vocab_size=8000, plot_pos_embedding=False)\n",
377 | "\n",
378 | "temp_input = tf.random.uniform((64, 62))\n",
379 | "temp_target = tf.random.uniform((64, 26))\n",
380 | "\n",
381 | "fn_out, _ = sample_transformer(temp_input, \n",
382 | " temp_target, \n",
383 | " training=False, \n",
384 | " enc_padding_mask=None, \n",
385 | " look_ahead_mask=None,\n",
386 | " dec_padding_mask=None)\n",
387 | "\n",
388 | "fn_out.shape"
389 | ]
390 | },
391 | {
392 | "cell_type": "markdown",
393 | "metadata": {},
394 | "source": [
395 | "# Training"
396 | ]
397 | },
398 | {
399 | "cell_type": "code",
400 | "execution_count": null,
401 | "metadata": {},
402 | "outputs": [],
403 | "source": [
404 | "num_layers = pm.num_block\n",
405 | "d_model = pm.d_model\n",
406 | "dff = pm.dff\n",
407 | "num_heads = pm.num_heads\n",
408 | "\n",
409 | "input_vocab_size = len(en2idx)\n",
410 | "target_vocab_size = len(de2idx)\n",
411 | "dropout_rate = pm.dropout_rate\n",
412 | "\n",
413 | "EPOCHS = pm.num_epochs"
414 | ]
415 | },
416 | {
417 | "cell_type": "markdown",
418 | "metadata": {},
419 | "source": [
420 | "- Learning rate schedule\n",
421 | "$$\\Large{lrate = d_{model}^{-0.5} * min(step{\\_}num^{-0.5}, step{\\_}num * warmup{\\_}steps^{-1.5})}$$"
422 | ]
423 | },
424 | {
425 | "cell_type": "code",
426 | "execution_count": null,
427 | "metadata": {},
428 | "outputs": [],
429 | "source": [
430 | "global_step = tf.Variable(0, trainable=False)\n",
431 | "learning_rate = LRSchedule(global_step, d_model, pm.learning_rate_warmup_steps)\n",
432 | "optimizer = tf.train.AdamOptimizer(learning_rate, beta1=pm.beta_1, beta2=pm.beta_2, epsilon=pm.epsilon)"
433 | ]
434 | },
435 | {
436 | "cell_type": "code",
437 | "execution_count": null,
438 | "metadata": {},
439 | "outputs": [],
440 | "source": [
441 | "temp_learning_rate_schedule = LRSchedule(tf.range(40000, dtype=tf.float32), d_model, 4000)\n",
442 | "\n",
443 | "plt.figure(figsize=(12, 8))\n",
444 | "plt.plot(temp_learning_rate_schedule().numpy())\n",
445 | "plt.ylabel(\"Learning Rate\")\n",
446 | "plt.xlabel(\"Train Step\")"
447 | ]
448 | },
449 | {
450 | "cell_type": "markdown",
451 | "metadata": {},
452 | "source": [
453 | "- loss mask"
454 | ]
455 | },
456 | {
457 | "cell_type": "code",
458 | "execution_count": null,
459 | "metadata": {},
460 | "outputs": [],
461 | "source": [
462 | "def loss_function(real, pred):\n",
463 | " mask = tf.math.logical_not(tf.math.equal(real, 0))\n",
464 | " loss_ = tf.keras.backend.sparse_categorical_crossentropy(real, pred, from_logits=True)\n",
465 | " \n",
466 | " mask = tf.cast(mask, dtype=loss_.dtype)\n",
467 | " loss_ *= mask\n",
468 | " \n",
469 | " return tf.reduce_mean(loss_)"
470 | ]
471 | },
472 | {
473 | "cell_type": "code",
474 | "execution_count": null,
475 | "metadata": {},
476 | "outputs": [],
477 | "source": [
478 | "transformer = Transformer(num_layers, d_model, num_heads, dff, input_vocab_size, target_vocab_size, pm.plot_pos_embedding, dropout_rate)"
479 | ]
480 | },
481 | {
482 | "cell_type": "code",
483 | "execution_count": null,
484 | "metadata": {},
485 | "outputs": [],
486 | "source": [
487 | "checkpoint_path = pm.ckpt_path\n",
488 | "\n",
489 | "ckpt = tf.train.Checkpoint(transformer=transformer, optimizer=optimizer)\n",
490 | "ckpt_dir = os.path.join(checkpoint_path, 'ckpt')\n",
491 | "\n",
492 | "if tf.train.latest_checkpoint(checkpoint_path):\n",
493 | " ckpt.restore(tf.train.latest_checkpoint(checkpoint_path))\n",
494 | " print('Latest model restored!')"
495 | ]
496 | },
497 | {
498 | "cell_type": "markdown",
499 | "metadata": {},
500 | "source": [
501 | "- Teacher forcing"
502 | ]
503 | },
504 | {
505 | "cell_type": "code",
506 | "execution_count": null,
507 | "metadata": {},
508 | "outputs": [],
509 | "source": [
510 | "def train_step(inp, tar):\n",
511 | " tar_inp = tar[:, :-1]\n",
512 | " tar_real = tar[:, 1:]\n",
513 | "\n",
514 | " enc_padding_mask, combined_mask, dec_padding_mask = create_masks(inp, tar_inp)\n",
515 | "\n",
516 | " with tf.GradientTape() as tape:\n",
517 | " predictions, _ = transformer(inp, \n",
518 | " tar_inp, \n",
519 | " True, \n",
520 | " enc_padding_mask, \n",
521 | " combined_mask, \n",
522 | " dec_padding_mask)\n",
523 | " \n",
524 | " loss = loss_function(tar_real, predictions)\n",
525 | "\n",
526 | " gradients = tape.gradient(loss, transformer.trainable_variables) \n",
527 | " optimizer.apply_gradients(zip(gradients, transformer.trainable_variables), global_step=global_step)\n",
528 | " istarget = tf.cast(tf.not_equal(tar_real, 0), tf.float32)\n",
529 | " predictions = tf.cast(tf.arg_max(predictions, dimension=-1), tf.int32)\n",
530 | " \n",
531 | " return loss, tf.reduce_sum(tf.cast(tf.equal(predictions, tar_real), tf.float32) * istarget) / (tf.reduce_sum(istarget))"
532 | ]
533 | },
534 | {
535 | "cell_type": "code",
536 | "execution_count": null,
537 | "metadata": {},
538 | "outputs": [],
539 | "source": [
540 | "for epoch in range(EPOCHS):\n",
541 | " start = time.time()\n",
542 | "\n",
543 | " train_loss, train_accuracy, batch_num = 0.0, 0.0, 0\n",
544 | "\n",
545 | " for (batch, (inp, tar)) in enumerate(train_dataset):\n",
546 | " loss, acc = train_step(inp, tar)\n",
547 | " train_loss += loss\n",
548 | " train_accuracy += acc\n",
549 | " batch_num += 1\n",
550 | " \n",
551 | " if batch % 500 == 0:\n",
552 | " print ('Epoch {} Batch {} Loss {:.4f} Accuracy {:.4f}'.format(\n",
553 | " epoch + 1, batch, loss, acc))\n",
554 | "\n",
555 | " if (epoch + 1) % 5 == 0:\n",
556 | " ckpt.save(ckpt_dir)\n",
557 | " print ('Saving checkpoint for epoch {} at {}'.format(epoch + 1, ckpt_dir))\n",
558 | " \n",
559 | " print ('Epoch {} Loss {:.4f} Accuracy {:.4f}'.format(epoch + 1, train_loss / batch_num, train_accuracy / batch_num))\n",
560 | " print ('Time taken for 1 epoch: {} secs\\n'.format(time.time() - start))"
561 | ]
562 | },
563 | {
564 | "cell_type": "markdown",
565 | "metadata": {},
566 | "source": [
567 | "---"
568 | ]
569 | },
570 | {
571 | "cell_type": "code",
572 | "execution_count": null,
573 | "metadata": {},
574 | "outputs": [],
575 | "source": [
576 | "def evaluate(inp_sentence):\n",
577 | " encoder_input = inp_sentence\n",
578 | " \n",
579 | " decoder_input = [2]\n",
580 | " output = tf.expand_dims(decoder_input, 0)\n",
581 | " output = tf.tile(output, [tf.shape(encoder_input)[0], 1])\n",
582 | "\n",
583 | " for i in range(pm.maxlen):\n",
584 | " enc_padding_mask, combined_mask, dec_padding_mask = create_masks(encoder_input, output)\n",
585 | "\n",
586 | " predictions, attention_weights = transformer(encoder_input, \n",
587 | " output,\n",
588 | " False,\n",
589 | " enc_padding_mask,\n",
590 | " combined_mask,\n",
591 | " dec_padding_mask)\n",
592 | "\n",
593 | " predictions = predictions[: ,-1:, :]\n",
594 | " predicted_id = tf.cast(tf.argmax(predictions, axis=-1), tf.int32)\n",
595 | "\n",
596 | " output = tf.concat([output, predicted_id], axis=-1)\n",
597 | "\n",
598 | " return output, attention_weights"
599 | ]
600 | },
601 | {
602 | "cell_type": "code",
603 | "execution_count": null,
604 | "metadata": {},
605 | "outputs": [],
606 | "source": [
607 | "def cut_by_end(samples):\n",
608 | " output_list = []\n",
609 | " for i, sample in enumerate(samples):\n",
610 | " dtype = sample.dtype\n",
611 | " idx = tf.where(tf.equal(sample, 3))\n",
612 | " \n",
613 | " flag = tf.where(tf.equal(tf.size(idx), 0), 1, 0)\n",
614 | " if flag == 1:\n",
615 | " output_list.append(sample)\n",
616 | " else:\n",
617 | " indices = tf.cast(idx[0, 0], dtype)\n",
618 | " output_list.append(tf.concat([sample[:indices], tf.zeros(tf.shape(sample)[0] - indices, dtype=dtype)], axis=0))\n",
619 | "\n",
620 | " return tf.stack(output_list)"
621 | ]
622 | },
623 | {
624 | "cell_type": "code",
625 | "execution_count": null,
626 | "metadata": {},
627 | "outputs": [],
628 | "source": [
629 | "eval_log = os.path.join(pm.eval_log_path, '{}_eval.tsv'.format(pm.project_name))\n",
630 | "if not os.path.exists(pm.eval_log_path):\n",
631 | " os.makedirs(pm.eval_log_path)\n",
632 | "eval_file = open(eval_log, 'w', encoding='utf-8')\n",
633 | "\n",
634 | "start = time.time()\n",
635 | "count, scores = 0, 0\n",
636 | "for (batch, (inp, tar)) in enumerate(val_dataset):\n",
637 | " prediction, attention_weights = evaluate(inp)\n",
638 | " prediction = cut_by_end(prediction)\n",
639 | " \n",
640 | " preds, tars = [], []\n",
641 | " for source, real_tar, pred in zip(inp, tar, prediction):\n",
642 | " s = \" \".join([idx2en.get(i, 1) for i in source.numpy() if i < len(idx2en) and i not in [0, 2, 3]])\n",
643 | " t = \"\".join([idx2de.get(i, 1) for i in real_tar.numpy() if i < len(idx2de) and i not in [0, 2, 3]])\n",
644 | " p = \"\".join([idx2de.get(i, 1) for i in pred.numpy() if i < len(idx2de) and i not in [0, 2, 3]])\n",
645 | " \n",
646 | " preds.append(p)\n",
647 | " tars.append([t])\n",
648 | " \n",
649 | " eval_file.write('-Source : {}\\n-Target : {}\\n-Pred : {}\\n\\n'.format(s, t, p))\n",
650 | " eval_file.flush()\n",
651 | " \n",
652 | " scores += bleu_metrics(tars, preds, False, 3, True)\n",
653 | " count += 1\n",
654 | "\n",
655 | "eval_file.write('-BLEU Score : {:.4f}'.format(scores / count))\n",
656 | "eval_file.close()\n",
657 | "\n",
658 | "print(\"MSG : Done for evalutation ... Totolly {:.2f} sec.\".format(time.time() - start))"
659 | ]
660 | },
661 | {
662 | "cell_type": "code",
663 | "execution_count": null,
664 | "metadata": {},
665 | "outputs": [],
666 | "source": [
667 | "def predict(inp_sentence):\n",
668 | " start_token = [2]\n",
669 | " end_token = [3]\n",
670 | "\n",
671 | " inp_sentence = start_token + [en2idx.get(word, 1) for word in inp_sentence.split()] + end_token\n",
672 | " encoder_input = tf.expand_dims(inp_sentence, 0)\n",
673 | " \n",
674 | " decoder_input = [2]\n",
675 | " output = tf.expand_dims(decoder_input, 0)\n",
676 | "\n",
677 | " for i in range(pm.maxlen):\n",
678 | " enc_padding_mask, combined_mask, dec_padding_mask = create_masks(encoder_input, output)\n",
679 | "\n",
680 | " predictions, attention_weights = transformer(encoder_input, \n",
681 | " output,\n",
682 | " False,\n",
683 | " enc_padding_mask,\n",
684 | " combined_mask,\n",
685 | " dec_padding_mask)\n",
686 | "\n",
687 | " predictions = predictions[: ,-1:, :]\n",
688 | " predicted_id = tf.cast(tf.argmax(predictions, axis=-1), tf.int32)\n",
689 | "\n",
690 | " if tf.where(tf.equal(predicted_id[0, 0], 3), 1, 0) == 1:\n",
691 | " return tf.squeeze(output, axis=0), attention_weights\n",
692 | "\n",
693 | " output = tf.concat([output, predicted_id], axis=-1)\n",
694 | "\n",
695 | " return tf.squeeze(output, axis=0), attention_weights"
696 | ]
697 | },
698 | {
699 | "cell_type": "code",
700 | "execution_count": null,
701 | "metadata": {},
702 | "outputs": [],
703 | "source": [
704 | "def translate(sentence):\n",
705 | " result, attention_weights = predict(sentence)\n",
706 | " \n",
707 | " predicted_sentence = [idx2de.get(i, 1) for i in result.numpy() if i < len(idx2de) and i not in [0, 2, 3]]\n",
708 | "\n",
709 | " print('Input: {}'.format(sentence))\n",
710 | " print('Predicted translation: {}'.format(\" \".join(predicted_sentence)))"
711 | ]
712 | },
713 | {
714 | "cell_type": "code",
715 | "execution_count": null,
716 | "metadata": {},
717 | "outputs": [],
718 | "source": [
719 | "translate(\"明 天 就 要 上 班 了\")\n",
720 | "print(\"Real translation: 還好我沒工作QQ\")"
721 | ]
722 | },
723 | {
724 | "cell_type": "code",
725 | "execution_count": null,
726 | "metadata": {},
727 | "outputs": [],
728 | "source": []
729 | }
730 | ],
731 | "metadata": {
732 | "kernelspec": {
733 | "display_name": "Python 3",
734 | "language": "python",
735 | "name": "python3"
736 | },
737 | "language_info": {
738 | "codemirror_mode": {
739 | "name": "ipython",
740 | "version": 3
741 | },
742 | "file_extension": ".py",
743 | "mimetype": "text/x-python",
744 | "name": "python",
745 | "nbconvert_exporter": "python",
746 | "pygments_lexer": "ipython3",
747 | "version": "3.7.1"
748 | }
749 | },
750 | "nbformat": 4,
751 | "nbformat_minor": 2
752 | }
753 |
--------------------------------------------------------------------------------
/tf1.12.0-eager/modules.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import print_function
3 | import tensorflow as tf
4 | import numpy as np
5 | import matplotlib.pyplot as plt
6 |
7 |
8 | def positional_encoding(seq_len, num_units, visualization=False):
9 | """
10 | Positional_Encoding for a given tensor.
11 |
12 | Args:
13 | :param inputs: [Tensor], A tensor contains the ids to be search from the lookup table, shape = [batch_size, seq_len]
14 | :param num_units: [Int], Hidden size of embedding
15 | :param visualization: [Boolean], If True, it will plot the graph of position encoding
16 | :return: [Tensor] A tensor with shape [1, seq_len, num_units]
17 | """
18 | def __get_angles(pos, i, d_model):
19 | angle_rates = 1 / np.power(10000, (2 * (i // 2)) / np.float32(d_model))
20 | return pos * angle_rates
21 |
22 | angle_rads = __get_angles(np.arange(seq_len)[:, np.newaxis],
23 | np.arange(num_units)[np.newaxis, :],
24 | num_units)
25 |
26 | sine = np.sin(angle_rads[:, 0::2])
27 | cosine = np.cos(angle_rads[:, 1::2])
28 |
29 | pos_encoding = np.concatenate([sine, cosine], axis=-1)
30 | pos_encoding = pos_encoding[np.newaxis, ...]
31 |
32 | if visualization:
33 | plt.figure(figsize=(12, 8))
34 | plt.pcolormesh(pos_encoding[0], cmap='RdBu')
35 | plt.xlabel('Depth')
36 | plt.xlim((0, num_units))
37 | plt.ylabel('Position')
38 | plt.colorbar()
39 | plt.show()
40 |
41 | return tf.cast(pos_encoding, tf.float32)
42 |
43 |
44 | def scaled_dot_product_attention(q, k, v, mask=None):
45 | """
46 | Calculate the attention weights.
47 |
48 | Args:
49 | :param q: [Tensor], query with shape [..., seq_len_q, d_model]
50 | :param k: [Tensor], key with shape [..., seq_len_k, d_model]
51 | :param v: [Tensor], value with shape [..., seq_len_v, d_model]
52 | :param mask: [Tensor], Float tensor with shape [..., seq_len_q, seq_len_k], default to None
53 | :return: [Tensor], output, attention_weights
54 | """
55 | matmul_qk = tf.matmul(q, k, transpose_b=True)
56 |
57 | dk = tf.cast(tf.shape(k)[-1], tf.float32)
58 | scaled_attention_logits = matmul_qk / tf.math.sqrt(dk)
59 |
60 | # Heuristic mask implementation that add an infinitesimal number so that its effect can be ignored
61 | if mask is not None:
62 | scaled_attention_logits += (mask * -1e9)
63 |
64 | attention_weights = tf.nn.softmax(scaled_attention_logits, axis=-1)
65 | output = tf.matmul(attention_weights, v)
66 |
67 | return output, attention_weights
68 |
69 |
70 | class multihead_attention(tf.keras.layers.Layer):
71 | def __init__(self, d_model, num_heads):
72 | super(multihead_attention, self).__init__()
73 | self.num_heads = num_heads
74 | self.d_model = d_model
75 |
76 | assert d_model % self.num_heads == 0
77 | self.depth = d_model // num_heads
78 |
79 | self.wq = tf.keras.layers.Dense(d_model)
80 | self.wk = tf.keras.layers.Dense(d_model)
81 | self.wv = tf.keras.layers.Dense(d_model)
82 |
83 | self.dense = tf.keras.layers.Dense(d_model)
84 |
85 | def split_heads(self, x, batch_size):
86 | """
87 | Split the last dimension into (num_heads, depth).
88 | Transpose the result such that the shape is (batch_size, num_heads, seq_len, depth).
89 | """
90 |
91 | x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth))
92 | return tf.transpose(x, perm=[0, 2, 1, 3])
93 |
94 | def call(self, v, k, q, mask):
95 | batch_size = tf.shape(q)[0]
96 |
97 | q = self.wq(q)
98 | k = self.wk(k)
99 | v = self.wv(v)
100 |
101 | q = self.split_heads(q, batch_size)
102 | k = self.split_heads(k, batch_size)
103 | v = self.split_heads(v, batch_size)
104 |
105 | scaled_attention, attention_weights = scaled_dot_product_attention(q, k, v, mask)
106 | scaled_attention = tf.transpose(scaled_attention, perm=[0, 2, 1, 3])
107 | concat_attention = tf.reshape(scaled_attention, (batch_size, -1, self.d_model))
108 | output = self.dense(concat_attention)
109 |
110 | return output, attention_weights
111 |
112 |
113 | class pointwise_feedforward(tf.keras.layers.Layer):
114 | def __init__(self, d_model, dff):
115 | super(pointwise_feedforward, self).__init__()
116 | self.d_model = d_model
117 | self.dff = dff
118 |
119 | self.dense_layer_1 = tf.keras.layers.Dense(dff, activation='relu')
120 | self.dense_layer_2 = tf.keras.layers.Dense(d_model)
121 |
122 | def call(self, x):
123 | output = self.dense_layer_1(x)
124 | output = self.dense_layer_2(output)
125 |
126 | return output
127 |
128 |
129 | class EncoderBlock(tf.keras.layers.Layer):
130 | def __init__(self, d_model, num_heads, dff, rate=0.1):
131 | super(EncoderBlock, self).__init__()
132 | self.multi_attn = multihead_attention(d_model, num_heads)
133 | self.ffn = pointwise_feedforward(d_model, dff)
134 |
135 | self.layer_norm_1 = tf.contrib.layers.layer_norm
136 | self.layer_norm_2 = tf.contrib.layers.layer_norm
137 |
138 | self.dropout_1 = tf.keras.layers.Dropout(rate)
139 | self.dropout_2 = tf.keras.layers.Dropout(rate)
140 |
141 | def call(self, x, training, padding_mask):
142 | attn_output, attn_weight = self.multi_attn(x, x, x, padding_mask)
143 | attn_output = self.dropout_1(attn_output, training=training)
144 | output_1 = self.layer_norm_1(x + attn_output)
145 |
146 | ffn_output = self.ffn(output_1)
147 | ffn_output = self.dropout_2(ffn_output, training=training)
148 | output_2 = self.layer_norm_2(output_1 + ffn_output)
149 |
150 | return output_2, attn_weight
151 |
152 |
153 | class DecoderBlock(tf.keras.layers.Layer):
154 | def __init__(self, d_model, num_heads, dff, rate=0.1):
155 | super(DecoderBlock, self).__init__()
156 | self.multi_attn_1 = multihead_attention(d_model, num_heads)
157 | self.multi_attn_2 = multihead_attention(d_model, num_heads)
158 |
159 | self.ffn = pointwise_feedforward(d_model, dff)
160 |
161 | self.layer_norm_1 = tf.contrib.layers.layer_norm
162 | self.layer_norm_2 = tf.contrib.layers.layer_norm
163 | self.layer_norm_3 = tf.contrib.layers.layer_norm
164 |
165 | self.dropout_1 = tf.keras.layers.Dropout(rate)
166 | self.dropout_2 = tf.keras.layers.Dropout(rate)
167 | self.dropout_3 = tf.keras.layers.Dropout(rate)
168 |
169 | def call(self, x, enc_output, training, look_ahead_mask, padding_mask):
170 | attn_output_1, attn_weight_1 = self.multi_attn_1(x, x, x, look_ahead_mask)
171 | attn_output_1 = self.dropout_1(attn_output_1, training=training)
172 | output_1 = self.layer_norm_1(x + attn_output_1)
173 |
174 | attn_output_2, attn_weight_2 = self.multi_attn_2(enc_output, enc_output, output_1, padding_mask)
175 | attn_output_2 = self.dropout_2(attn_output_2, training=training)
176 | output_2 = self.layer_norm_2(output_1 + attn_output_2)
177 |
178 | ffn_output = self.ffn(output_2)
179 | ffn_output = self.dropout_3(ffn_output, training=training)
180 | output_3 = self.layer_norm_3(output_2 + ffn_output)
181 |
182 | return output_3, attn_weight_1, attn_weight_2
183 |
184 |
185 | class Encoder(tf.keras.layers.Layer):
186 | def __init__(self, num_blocks, d_model, num_heads, dff, input_vocab_size, plot_pos_embedding, rate=0.1):
187 | super(Encoder, self).__init__()
188 | self.d_model = d_model
189 | self.num_blocks = num_blocks
190 | self.plot_pos_embedding = plot_pos_embedding
191 |
192 | self.embedding = tf.keras.layers.Embedding(input_vocab_size, d_model)
193 | self.pos_embedding = positional_encoding(input_vocab_size, d_model, plot_pos_embedding)
194 |
195 | self.enc_blocks = [EncoderBlock(d_model, num_heads, dff, rate) for _ in range(num_blocks)]
196 | self.dropout = tf.keras.layers.Dropout(rate)
197 |
198 | def call(self, x, training, padding_mask, attn_dict):
199 | seq_len = tf.shape(x)[1]
200 |
201 | x = self.embedding(x)
202 | x *= tf.math.sqrt(tf.cast(self.d_model, tf.float32))
203 | x += self.pos_embedding[:, :seq_len, :]
204 |
205 | x = self.dropout(x, training=training)
206 |
207 | for i in range(self.num_blocks):
208 | x, attn_weight = self.enc_blocks[i](x, training, padding_mask)
209 | attn_dict['encoder_layer{}_block'.format(i + 1)] = attn_weight
210 |
211 | return x, attn_dict
212 |
213 |
214 | class Decoder(tf.keras.layers.Layer):
215 | def __init__(self, num_blocks, d_model, num_heads, dff, target_vocab_size, plot_pos_embedding, rate=0.1):
216 | super(Decoder, self).__init__()
217 | self.d_model = d_model
218 | self.num_blocks = num_blocks
219 | self.plot_pos_embedding = plot_pos_embedding
220 |
221 | self.embedding = tf.keras.layers.Embedding(target_vocab_size, d_model)
222 | self.pos_embedding = positional_encoding(target_vocab_size, d_model, plot_pos_embedding)
223 |
224 | self.dec_blocks = [DecoderBlock(d_model, num_heads, dff, rate) for _ in range(num_blocks)]
225 | self.dropout = tf.keras.layers.Dropout(rate)
226 |
227 | def call(self, x, enc_output, training, look_ahead_mask, padding_mask, attn_dict):
228 | seq_len = tf.shape(x)[1]
229 |
230 | x = self.embedding(x)
231 | x *= tf.math.sqrt(tf.cast(self.d_model, tf.float32))
232 | x += self.pos_embedding[:, :seq_len, :]
233 |
234 | x = self.dropout(x, training=training)
235 |
236 | for i in range(self.num_blocks):
237 | x, attn_weight_1, attn_weight_2 = self.dec_blocks[i](x, enc_output, training, look_ahead_mask, padding_mask)
238 | attn_dict['decoder_layer{}_block'.format(i + 1)] = attn_weight_1
239 | attn_dict['decoder_layer{}_cross'.format(i + 1)] = attn_weight_2
240 |
241 | return x, attn_dict
242 |
243 |
244 | class Transformer(tf.keras.Model):
245 | def __init__(self, num_blocks, d_model, num_heads, dff, input_vocab_size, target_vocab_size, plot_pos_embedding, rate=0.1):
246 | super(Transformer, self).__init__()
247 |
248 | self.encoder = Encoder(num_blocks, d_model, num_heads, dff, input_vocab_size, plot_pos_embedding, rate)
249 | self.decoder = Decoder(num_blocks, d_model, num_heads, dff, target_vocab_size, plot_pos_embedding, rate)
250 | self.final_layer = tf.keras.layers.Dense(target_vocab_size)
251 |
252 | def call(self, inp, tar, training, enc_padding_mask, look_ahead_mask, dec_padding_mask):
253 | attn_dict = {}
254 |
255 | enc_output, attn_dict = self.encoder(inp, training, enc_padding_mask, attn_dict)
256 | dec_output, attn_dict = self.decoder(tar, enc_output, training, look_ahead_mask, dec_padding_mask, attn_dict)
257 | final_output = self.final_layer(dec_output)
258 |
259 | return final_output, attn_dict
260 |
--------------------------------------------------------------------------------
/tf1.12.0-eager/params.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | class Params:
3 | """
4 | Parameters of our model.
5 | """
6 | project_name = 'demo'
7 | vocab_path = "dictionary/"
8 | src_train = "data/src-train.txt"
9 | tgt_train = "data/tgt-train.txt"
10 | src_test = "data/src-val.txt"
11 | tgt_test = "data/tgt-val.txt"
12 |
13 | train_record = "data/processed/{}/train.tfrecord".format(project_name)
14 | test_record = "data/processed/{}/val.tfrecord".format(project_name)
15 | logdir = 'logdir'
16 | ckpt_path = 'checkpoint/{}'.format(project_name)
17 | eval_log_path = 'result/{}'.format(project_name)
18 |
19 | rebuild_vocabulary = False
20 |
21 | maxlen = 12
22 | buffer_size = 10000
23 | batch_size = 128
24 | word_limit_size = 5
25 |
26 | d_model = 512
27 | dff = 2048
28 | num_epochs = 10
29 | num_block = 6
30 | num_heads = 8
31 | dropout_rate = 0.1
32 | smooth_epsilon = 0.1
33 | learning_rate = 1e-4
34 | learning_rate_warmup_steps = 4000
35 | beta_1 = 0.9
36 | beta_2 = 0.98
37 | epsilon = 1e-9
38 | batch_show_every = 500
39 | epoch_show_every = 1
40 | plot_pos_embedding = False
41 |
--------------------------------------------------------------------------------
/tf1.12.0-eager/requirements.txt:
--------------------------------------------------------------------------------
1 | nltk==3.4
2 | numpy==1.15.4
3 | tqdm==4.28.1
4 | tensorflow-gpu==1.12.0
5 | matplotlib==3.0.2
--------------------------------------------------------------------------------
/tf1.12.0-eager/utils.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import print_function
3 | from params import Params as pm
4 | import os
5 | from collections import Counter
6 | from tqdm import tqdm
7 | import tensorflow as tf
8 | from tensorflow.python.framework import ops
9 | from tensorflow.python.ops import math_ops
10 | import functools
11 |
12 |
13 | def build_vocab(path, fname):
14 | """
15 | Constructs vocabulary as a dictionary.
16 |
17 | Args:
18 | :param path: [String], Input file path
19 | :param fname: [String], Output file name
20 | """
21 | words = open(path, 'r', encoding='utf-8').read().split()
22 | wordCount = Counter(words)
23 | if not os.path.exists(pm.vocab_path):
24 | os.makedirs(pm.vocab_path)
25 | with open(pm.vocab_path + fname, 'w', encoding='utf-8') as f:
26 | f.write("{}\t1000000000\n{}\t1000000000\n{}\t1000000000\n{}\t1000000000\n".format("", "", "", ""))
27 | for word, count in wordCount.most_common(len(wordCount)):
28 | f.write(u"{}\t{}\n".format(word, count))
29 |
30 |
31 | def load_vocab(vocab):
32 | """
33 | Load word token from encoding dictionary.
34 |
35 | Args:
36 | :param vocab: [String], vocabulary files
37 | :return: tokenizer
38 | """
39 | vocab = [line.split()[0] for line in open(
40 | '{}{}'.format(pm.vocab_path, vocab), 'r', encoding='utf-8').read().splitlines()
41 | if int(line.split()[1]) >= pm.word_limit_size]
42 | word2idx_dic = {word: idx for idx, word in enumerate(vocab)}
43 | idx2word_dic = {idx: word for idx, word in enumerate(vocab)}
44 | return word2idx_dic, idx2word_dic
45 |
46 |
47 | if not os.path.exists(pm.vocab_path) or pm.rebuild_vocabulary:
48 | build_vocab(pm.src_train, "en.vocab.tsv")
49 | build_vocab(pm.tgt_train, "de.vocab.tsv")
50 | en2idx, idx2en = load_vocab("en.vocab.tsv")
51 | de2idx, idx2de = load_vocab("de.vocab.tsv")
52 |
53 |
54 | def tokenize_sequences(source_sent, target_sent):
55 | """
56 | Parse source sentences and target sentences from corpus with some formats.
57 | Parse word token from each sentences.
58 | Padding for word token sentence list.
59 |
60 | Args:
61 | :param source_sent: [List], encoding sentences from src-train file
62 | :param target_sent: [List], decoding sentences from tgt-train file
63 | :return: token sequences & source sentences
64 | """
65 | source_sent = source_sent.numpy().decode('utf-8')
66 | target_sent = target_sent.numpy().decode('utf-8')
67 |
68 | inpt = [en2idx.get(word, 1) for word in (u" " + source_sent + u" ").split()]
69 | outpt = [de2idx.get(word, 1) for word in (u" " + target_sent + u" ").split()]
70 |
71 | return inpt, outpt
72 |
73 |
74 | def jit_tokenize_sequences(source_sent, target_sent):
75 | return tf.py_function(tokenize_sequences, [source_sent, target_sent], [tf.int64, tf.int64])
76 |
77 |
78 | def filter_single_word(source_sent, target_sent):
79 | return tf.logical_and(tf.size(source_sent) > 1, tf.size(target_sent) > 1)
80 |
81 |
82 | def _byte_features(value):
83 | return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
84 |
85 |
86 | def dump2record(filename, corpus1, corpus2):
87 | """
88 | Writedown the data into tfrecord format.
89 |
90 | Args:
91 | :param filename:
92 | :param corpus1:
93 | :param corpus2:
94 | """
95 | assert len(corpus1) == len(corpus2)
96 | writer = tf.io.TFRecordWriter(filename)
97 |
98 | for sent1, sent2 in tqdm(zip(corpus1, corpus2)):
99 | features = {}
100 | features['src_sent'] = _byte_features(sent1.encode('utf-8'))
101 | features['tgt_sent'] = _byte_features(sent2.encode('utf-8'))
102 |
103 | tf_features = tf.train.Features(feature=features)
104 | tf_examples = tf.train.Example(features=tf_features)
105 | tf_serialized = tf_examples.SerializeToString()
106 |
107 | writer.write(tf_serialized)
108 |
109 | writer.close()
110 |
111 |
112 | def build_dataset(mode, filename=None, corpus=None, is_training=True):
113 | """
114 | Read train-data from input datasets.
115 |
116 | Args:
117 | :param mode: [String], the tfrecord load mode, including 'array'(load from array) or 'file'(load from file)
118 | :param filename: [String], if mode == 'file' then input the path of tfrecord
119 | :param corpus: [String], if mode == 'array' then input the corpus with array type
120 | :return: datasets
121 | """
122 | if mode == 'array':
123 | assert corpus is not None
124 | def _parse(example):
125 | return example[0], example[1]
126 |
127 | src, tgt = corpus
128 | real_data = [(inp.encode('utf-8'), tar.encode('utf-8')) for inp, tar in zip(src, tgt)]
129 | dataset = tf.data.Dataset.from_tensor_slices(real_data)
130 | dataset = dataset.map(_parse, num_parallel_calls=2)
131 | dataset = dataset.map(jit_tokenize_sequences, num_parallel_calls=2)
132 | dataset = dataset.filter(filter_single_word).cache().shuffle(pm.buffer_size) if is_training else dataset
133 | dataset = dataset.padded_batch(pm.batch_size, padded_shapes=([-1], [-1])) if is_training else \
134 | dataset.padded_batch(1, padded_shapes=([-1], [-1]))
135 | dataset = dataset.prefetch(tf.data.experimental.AUTOTUNE) if is_training else dataset
136 | return dataset
137 | elif mode == 'file':
138 | def _parse(example):
139 | dics = {
140 | 'src_sent': tf.io.FixedLenFeature(shape=(), dtype=tf.string, default_value=None),
141 | 'tgt_sent': tf.io.FixedLenFeature(shape=(), dtype=tf.string, default_value=None)
142 | }
143 |
144 | parsed_data = tf.io.parse_single_example(example, dics)
145 | src_sent = parsed_data['src_sent']
146 | tgt_sent = parsed_data['tgt_sent']
147 | return src_sent, tgt_sent
148 |
149 | assert filename is not None
150 | dataset = tf.data.TFRecordDataset(filename)
151 | dataset = dataset.map(_parse, num_parallel_calls=2)
152 | dataset = dataset.map(jit_tokenize_sequences, num_parallel_calls=2)
153 | dataset = dataset.filter(filter_single_word).cache().shuffle(pm.buffer_size) if is_training else dataset
154 | dataset = dataset.padded_batch(pm.batch_size, padded_shapes=([-1], [-1])) if is_training else \
155 | dataset.padded_batch(1, padded_shapes=([-1], [-1]))
156 | dataset = dataset.prefetch(tf.data.experimental.AUTOTUNE) if is_training else dataset
157 | return dataset
158 | else:
159 | raise ValueError('Something wrong about the mode when loading dataset ...')
160 |
161 |
162 | def LRSchedule(global_step, d_model, warmup_steps=4000):
163 | if global_step is None:
164 | raise ValueError("global_step is required for learning_rate_schedule.")
165 |
166 | def deal_lr(global_step, d_model, warmup_steps):
167 | d_model = ops.convert_to_tensor(d_model, dtype=tf.float32)
168 | dtype = d_model.dtype
169 | warmup_steps = math_ops.cast(warmup_steps, dtype)
170 |
171 | global_step_recomp = math_ops.cast(global_step, dtype)
172 | arg1 = math_ops.rsqrt(global_step_recomp)
173 | arg2 = math_ops.multiply(global_step_recomp, math_ops.pow(warmup_steps, -1.5))
174 |
175 | return math_ops.multiply(math_ops.rsqrt(d_model), math_ops.minimum(arg1, arg2))
176 |
177 | return functools.partial(deal_lr, global_step, d_model, warmup_steps)
178 |
179 |
180 | def masking(sequence, task='padding'):
181 | """
182 | Masking operation.
183 |
184 | Args:
185 | :param sequence: [Tensor], A tensor contains the ids to be search from the lookup table, shape = [batch_size, seq_len]
186 | :param task: [String], 'padding' or 'look_ahead' tasks, set 'padding' default
187 | :return: [Tensor], Masked matrix
188 | """
189 | if task == 'padding':
190 | return tf.cast(tf.math.equal(sequence, 0), tf.float32)[:, tf.newaxis, tf.newaxis, :]
191 |
192 | elif task == 'look_ahead':
193 | size = tf.shape(sequence)[1]
194 | return 1 - tf.linalg.band_part(tf.ones((size, size)), -1, 0)
195 |
196 | else:
197 | raise ValueError('Please check the tasks that masking operation dealing with ("padding" or "look_ahead")...')
198 |
199 |
200 | def create_masks(inp, tar):
201 | enc_padding_mask = masking(inp, task='padding')
202 | dec_padding_mask = masking(inp, task='padding')
203 |
204 | look_ahead_mask = masking(tar, task='look_ahead')
205 | dec_tar_padding_mask = masking(tar, task='padding')
206 | combined_mask = tf.maximum(dec_tar_padding_mask, look_ahead_mask)
207 |
208 | return enc_padding_mask, combined_mask, dec_padding_mask
209 |
--------------------------------------------------------------------------------
/utils_v2.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import print_function
3 | from params import Params as pm
4 | import os
5 | from collections import Counter
6 | from tqdm import tqdm
7 | import tensorflow as tf
8 | import matplotlib.pyplot as plt
9 |
10 |
11 | def build_vocab(path, fname):
12 | """
13 | Constructs vocabulary as a dictionary.
14 |
15 | Args:
16 | :param path: [String], Input file path
17 | :param fname: [String], Output file name
18 | """
19 | words = open(path, 'r', encoding='utf-8').read().split()
20 | wordCount = Counter(words)
21 | if not os.path.exists(pm.vocab_path):
22 | os.makedirs(pm.vocab_path)
23 | with open(pm.vocab_path + fname, 'w', encoding='utf-8') as f:
24 | f.write("{}\t1000000000\n{}\t1000000000\n{}\t1000000000\n{}\t1000000000\n".format("", "", "", ""))
25 | for word, count in wordCount.most_common(len(wordCount)):
26 | f.write(u"{}\t{}\n".format(word, count))
27 |
28 |
29 | def load_vocab(vocab):
30 | """
31 | Load word token from encoding dictionary.
32 |
33 | Args:
34 | :param vocab: [String], vocabulary files
35 | :return: tokenizer
36 | """
37 | vocab = [line.split()[0] for line in open(
38 | '{}{}'.format(pm.vocab_path, vocab), 'r', encoding='utf-8').read().splitlines()
39 | if int(line.split()[1]) >= pm.word_limit_size]
40 | word2idx_dic = {word: idx for idx, word in enumerate(vocab)}
41 | idx2word_dic = {idx: word for idx, word in enumerate(vocab)}
42 | return word2idx_dic, idx2word_dic
43 |
44 |
45 | if not os.path.exists(pm.vocab_path) or pm.rebuild_vocabulary:
46 | build_vocab(pm.src_train, "en.vocab.tsv")
47 | build_vocab(pm.tgt_train, "de.vocab.tsv")
48 | en2idx, idx2en = load_vocab("en.vocab.tsv")
49 | de2idx, idx2de = load_vocab("de.vocab.tsv")
50 |
51 |
52 | def tokenize_sequences(source_sent, target_sent):
53 | """
54 | Parse source sentences and target sentences from corpus with some formats.
55 | Parse word token from each sentences.
56 | Padding for word token sentence list.
57 |
58 | Args:
59 | :param source_sent: [List], encoding sentences from src-train file
60 | :param target_sent: [List], decoding sentences from tgt-train file
61 | :return: token sequences & source sentences
62 | """
63 | source_sent = source_sent.numpy().decode('utf-8')
64 | target_sent = target_sent.numpy().decode('utf-8')
65 |
66 | inpt = [en2idx.get(word, 1) for word in (u" " + source_sent + u" ").split()]
67 | outpt = [de2idx.get(word, 1) for word in (u" " + target_sent + u" ").split()]
68 |
69 | if len(inpt) < pm.maxlen:
70 | inpt += [0 for _ in range(pm.maxlen - len(inpt))]
71 | if len(outpt) < pm.maxlen:
72 | outpt += [0 for _ in range(pm.maxlen - len(outpt))]
73 |
74 | return inpt, outpt
75 |
76 |
77 | def jit_tokenize_sequences(source_sent, target_sent):
78 | return tf.py_function(tokenize_sequences, [source_sent, target_sent], [tf.int64, tf.int64])
79 |
80 |
81 | def filter_single_word(source_sent, target_sent):
82 | return tf.logical_and(tf.size(source_sent) <= pm.maxlen, tf.size(target_sent) <= pm.maxlen)
83 |
84 |
85 | def _byte_features(value):
86 | return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
87 |
88 |
89 | def dump2record(filename, corpus1, corpus2):
90 | """
91 | Writedown the data into tfrecord format.
92 |
93 | Args:
94 | :param filename:
95 | :param corpus1:
96 | :param corpus2:
97 | """
98 | assert len(corpus1) == len(corpus2)
99 | writer = tf.io.TFRecordWriter(filename)
100 |
101 | for sent1, sent2 in tqdm(zip(corpus1, corpus2)):
102 | features = {}
103 | features['src_sent'] = _byte_features(sent1.encode('utf-8'))
104 | features['tgt_sent'] = _byte_features(sent2.encode('utf-8'))
105 |
106 | tf_features = tf.train.Features(feature=features)
107 | tf_examples = tf.train.Example(features=tf_features)
108 | tf_serialized = tf_examples.SerializeToString()
109 |
110 | writer.write(tf_serialized)
111 |
112 | writer.close()
113 |
114 |
115 | def build_dataset(mode, batch_size, cache_name, filename=None, corpus=None, is_training=True):
116 | """
117 | Read train-data from input datasets.
118 |
119 | Args:
120 | :param mode: [String], the tfrecord load mode, including 'array'(load from array) or 'file'(load from file)
121 | :param batch_size: [String], cut data into batches for training
122 | :param filename: [String], if mode == 'file' then input the path of tfrecord
123 | :param corpus: [String], if mode == 'array' then input the corpus with array type
124 | :return: datasets
125 | """
126 | dataset_root = "/".join(pm.train_record.split('/')[:-1])
127 | if mode == 'array':
128 | assert corpus is not None
129 | def _parse(example):
130 | return example[0], example[1]
131 |
132 | src, tgt = corpus
133 | real_data = [(inp.encode('utf-8'), tar.encode('utf-8')) for inp, tar in zip(src, tgt)]
134 | dataset = tf.data.Dataset.from_tensor_slices(real_data)
135 | dataset = dataset.map(_parse, num_parallel_calls=tf.data.experimental.AUTOTUNE)
136 | dataset = dataset.map(jit_tokenize_sequences, num_parallel_calls=tf.data.experimental.AUTOTUNE)
137 | dataset = dataset.filter(filter_single_word).cache(filename='{}/{}'.format(dataset_root, cache_name)).shuffle(pm.buffer_size) if is_training else dataset
138 | dataset = dataset.padded_batch(batch_size, padded_shapes=([-1], [-1])) if is_training else \
139 | dataset.padded_batch(1, padded_shapes=([-1], [-1]))
140 | dataset = dataset.prefetch(tf.data.experimental.AUTOTUNE) if is_training else dataset
141 | return dataset
142 | elif mode == 'file':
143 | def _parse(example):
144 | dics = {
145 | 'src_sent': tf.io.FixedLenFeature(shape=(), dtype=tf.string, default_value=None),
146 | 'tgt_sent': tf.io.FixedLenFeature(shape=(), dtype=tf.string, default_value=None)
147 | }
148 |
149 | parsed_data = tf.io.parse_single_example(example, dics)
150 | src_sent = parsed_data['src_sent']
151 | tgt_sent = parsed_data['tgt_sent']
152 | return src_sent, tgt_sent
153 |
154 | assert filename is not None
155 | dataset = tf.data.TFRecordDataset(filename)
156 | dataset = dataset.map(_parse, num_parallel_calls=tf.data.experimental.AUTOTUNE)
157 | dataset = dataset.map(jit_tokenize_sequences, num_parallel_calls=tf.data.experimental.AUTOTUNE)
158 | dataset = dataset.filter(filter_single_word).cache(filename='{}/{}'.format(dataset_root, cache_name)).shuffle(pm.buffer_size) if is_training else dataset
159 | dataset = dataset.padded_batch(batch_size, padded_shapes=([-1], [-1])) if is_training else \
160 | dataset.padded_batch(1, padded_shapes=([-1], [-1]))
161 | dataset = dataset.prefetch(tf.data.experimental.AUTOTUNE) if is_training else dataset
162 | return dataset
163 | else:
164 | raise ValueError('Something wrong about the mode when loading dataset ...')
165 |
166 |
167 | class LRSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):
168 | def __init__(self, d_model, warmup_steps=4000):
169 | super(LRSchedule, self).__init__()
170 |
171 | # It must be tensor else raise "Could not find valid device for node." error.
172 | self.d_model = tf.cast(d_model, tf.float32)
173 | self.warmup_steps = warmup_steps
174 |
175 | def __call__(self, step):
176 | arg1 = tf.math.rsqrt(step)
177 | arg2 = step * (self.warmup_steps ** -1.5)
178 |
179 | return tf.math.rsqrt(self.d_model) * tf.minimum(arg1, arg2)
180 |
181 |
182 | class polynomialLR(tf.keras.optimizers.schedules.LearningRateSchedule):
183 | def __init__(self, sl, el, decay_steps, power):
184 | super(polynomialLR, self).__init__()
185 |
186 | # It must be tensor else raise "Could not find valid device for node." error.
187 | self.sl = sl
188 | self.el = el
189 | self.decay_steps = decay_steps
190 | self.power = power
191 |
192 | def __call__(self, step):
193 | arg1 = self.decay_steps * tf.math.ceil(step / self.decay_steps)
194 |
195 | return (self.sl - self.el) * (1 - step / arg1) ** self.power + self.el
196 |
197 |
198 | def masking(sequence, task='padding'):
199 | """
200 | Masking operation.
201 |
202 | Args:
203 | :param sequence: [Tensor], A tensor contains the ids to be search from the lookup table, shape = [batch_size, seq_len]
204 | :param task: [String], 'padding' or 'look_ahead' tasks, set 'padding' default
205 | :return: [Tensor], Masked matrix
206 | """
207 | if task == 'padding':
208 | return tf.cast(tf.math.equal(sequence, 0), tf.float32)[:, tf.newaxis, tf.newaxis, :]
209 |
210 | elif task == 'look_ahead':
211 | size = tf.shape(sequence)[1]
212 | return 1 - tf.linalg.band_part(tf.ones((size, size)), -1, 0)
213 |
214 | else:
215 | raise ValueError('Please check the tasks that masking operation dealing with ("padding" or "look_ahead")...')
216 |
217 |
218 | def create_masks(inp, tar):
219 | enc_padding_mask = masking(inp, task='padding')
220 | dec_padding_mask = masking(inp, task='padding')
221 |
222 | look_ahead_mask = masking(tar, task='look_ahead')
223 | dec_tar_padding_mask = masking(tar, task='padding')
224 | combined_mask = tf.maximum(dec_tar_padding_mask, look_ahead_mask)
225 |
226 | return enc_padding_mask, combined_mask, dec_padding_mask
227 |
228 |
229 | def plot_attention_weights(attention, sentence, result, layer):
230 | fig = plt.figure(figsize=(16, 8))
231 |
232 | sentence = [en2idx.get(word, 1) for word in sentence.split()]
233 | attention = tf.squeeze(attention[layer], axis=0)
234 |
235 | for head in range(attention.shape[0]):
236 | ax = fig.add_subplot(2, 4, head + 1)
237 |
238 | ax.matshow(attention[head][:-1, :], cmap='viridis')
239 | fontdict = {'fontsize': 10}
240 |
241 | ax.set_xticks(range(len(sentence) + 2))
242 | ax.set_yticks(range(len(result)))
243 |
244 | ax.set_ylim(len(result)-1.5, -0.5)
245 |
246 | ax.set_xticklabels([''] + [idx2en.get(i, 1) for i in sentence] + [''],
247 | fontdict=fontdict, rotation=90)
248 |
249 | ax.set_yticklabels([idx2de.get(i, 1) for i in result.numpy() if i < len(idx2de) and i not in [0, 2, 3]],
250 | fontdict=fontdict)
251 |
252 | ax.set_xlabel('Head {}'.format(head + 1))
253 |
254 | plt.tight_layout()
255 | plt.show()
256 |
--------------------------------------------------------------------------------