📦 mymusise / Auto-CLUD

📄 run_chid_0shot_tf.ipynb · 447 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447{
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.6"
  },
  "orig_nbformat": 2,
  "kernelspec": {
   "name": "python386jvsc74a57bd0822f53e720c9305923484d9f11c14ce5a186e3d4e0b3a51085fc65ff877163b4",
   "display_name": "Python 3.8.6 64-bit ('env')"
  },
  "metadata": {
   "interpreter": {
    "hash": "aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2,
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Num GPUs Available:  0\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"  \n",
    "os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n",
    "import tensorflow as tf\n",
    "print(\"Num GPUs Available: \", len(tf.config.experimental.list_physical_devices('GPU')))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import configs\n",
    "import os\n",
    "import json\n",
    "\n",
    "import numpy as np\n",
    "import jieba\n",
    "import tensorflow as tf\n",
    "\n",
    "from transformers import TFGPT2LMHeadModel, TFGPT2ForSequenceClassification, GPT2Config\n",
    "from transformers import TFTrainer, TFTrainingArguments\n",
    "from transformers import XLNetTokenizer\n",
    "\n",
    "\n",
    "task_name = 'chid'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import jieba\n",
    "\n",
    "\n",
    "class XLNetTokenizer(XLNetTokenizer):\n",
    "    translator = str.maketrans(\" \\n\", \"\\u2582\\u2583\")\n",
    "\n",
    "    def _tokenize(self, text, *args, **kwargs):\n",
    "        text = [x.translate(self.translator) for x in jieba.cut(text, cut_all=False)]\n",
    "        text = \" \".join(text)\n",
    "        return super()._tokenize(text, *args, **kwargs)\n",
    "\n",
    "    def _decode(self, *args, **kwargs):\n",
    "        text = super()._decode(*args, **kwargs)\n",
    "        text = text.replace(\" \", \"\").replace(\"\\u2582\", \" \").replace(\"\\u2583\", \"\\n\")\n",
    "        return text\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "def load_json2list(filename, task_name):\n",
    "    with open(filename) as f:\n",
    "        for line in f.readlines():\n",
    "            if line:\n",
    "                data = json.loads(line)\n",
    "                yield data\n",
    "\n",
    "\n",
    "def load_dataset(task_name: str):\n",
    "    path = os.path.join(configs.DATA_PATH, task_name)\n",
    "\n",
    "    train_file = os.path.join(path, \"train.json\")\n",
    "    dev_file = os.path.join(path, \"dev.json\")\n",
    "    test_file = os.path.join(path, \"test.json\")\n",
    "    train_dataset = list(load_json2list(train_file, task_name))\n",
    "    dev_dataset = list(load_json2list(dev_file, task_name))\n",
    "    test_dataset = list(load_json2list(test_file, task_name))\n",
    "    return train_dataset, dev_dataset, test_dataset\n",
    "\n",
    "train_dataset, dev_dataset, test_dataset = load_dataset(task_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stderr",
     "text": [
      "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n"
     ]
    }
   ],
   "source": [
    "\n",
    "def load_tokenizer():\n",
    "    tokenizer = XLNetTokenizer.from_pretrained(configs.MODEL_PATH, padding_side=\"right\")\n",
    "    return tokenizer\n",
    "\n",
    "tokenizer = load_tokenizer()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "\n",
    "def load_answer_dict(task_name: str):\n",
    "    path = os.path.join(configs.DATA_PATH, task_name)\n",
    "    train_answer = json.load(open(os.path.join(path, \"train_answer.json\")))\n",
    "    dev_answer = json.load(open(os.path.join(path, \"dev_answer.json\")))\n",
    "    return train_answer, dev_answer\n",
    "\n",
    "def conver4ZeroShot(item, tokenizer, answer_dict):\n",
    "    max_length = 0\n",
    "    \n",
    "    for sentence in item['content']:\n",
    "        print(sentence)\n",
    "        re.search()\n",
    "\n",
    "\n",
    "train_answer, dev_answer = load_answer_dict(task_name)\n",
    "dev_dataset[0]\n",
    "answer_dict = dev_answer\n",
    "# conver4ZeroShot(dev_dataset[0], tokenizer, dev_answer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stderr",
     "text": [
      "All model checkpoint layers were used when initializing TFGPT2LMHeadModel.\n",
      "\n",
      "All the layers of TFGPT2LMHeadModel were initialized from the model checkpoint at /data2/Text-Suggestion/models.\n",
      "If your task is similar to the task the model of the checkpoint was trained on, you can already use TFGPT2LMHeadModel for predictions without further training.\n"
     ]
    }
   ],
   "source": [
    "def load_model(task_name: str) -> TFGPT2ForSequenceClassification:\n",
    "    model = TFGPT2LMHeadModel.from_pretrained(configs.MODEL_PATH)\n",
    "    return model\n",
    "\n",
    "model = load_model(task_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "#idiom577159# 对消费者而言,保险是一种较为特殊的金融理财产品,其最基本原则是对风险的保障。虽然目前保险公司开发了诸多强调投资收益的险种,但无论任何种类的产品都不能偏离保险的本质。尤其是对于注重保障的人身保险而言,强调投资价值实属祸不单行。消费者在投资保险理财产品时,需端正心态,树立科学、健康的保险理念,避免走进购买误区。\n#idiom577159# 对消费者而言,保险是一种较为特殊的金融理财产品,其最基本原则是对风险的保障。虽然目前保险公司开发了诸多强调投资收益的险种,但无论任何种类的产品都不能偏离保险的本质。尤其是对于注重保障的人身保险而言,强调投资价值实属急功近利。消费者在投资保险理财产品时,需端正心态,树立科学、健康的保险理念,避免走进购买误区。\n#idiom577159# 对消费者而言,保险是一种较为特殊的金融理财产品,其最基本原则是对风险的保障。虽然目前保险公司开发了诸多强调投资收益的险种,但无论任何种类的产品都不能偏离保险的本质。尤其是对于注重保障的人身保险而言,强调投资价值实属瓜熟蒂落。消费者在投资保险理财产品时,需端正心态,树立科学、健康的保险理念,避免走进购买误区。\n#idiom577159# 对消费者而言,保险是一种较为特殊的金融理财产品,其最基本原则是对风险的保障。虽然目前保险公司开发了诸多强调投资收益的险种,但无论任何种类的产品都不能偏离保险的本质。尤其是对于注重保障的人身保险而言,强调投资价值实属画蛇添足。消费者在投资保险理财产品时,需端正心态,树立科学、健康的保险理念,避免走进购买误区。\n#idiom577159# 对消费者而言,保险是一种较为特殊的金融理财产品,其最基本原则是对风险的保障。虽然目前保险公司开发了诸多强调投资收益的险种,但无论任何种类的产品都不能偏离保险的本质。尤其是对于注重保障的人身保险而言,强调投资价值实属本末倒置。消费者在投资保险理财产品时,需端正心态,树立科学、健康的保险理念,避免走进购买误区。\n#idiom577159# 对消费者而言,保险是一种较为特殊的金融理财产品,其最基本原则是对风险的保障。虽然目前保险公司开发了诸多强调投资收益的险种,但无论任何种类的产品都不能偏离保险的本质。尤其是对于注重保障的人身保险而言,强调投资价值实属因噎废食。消费者在投资保险理财产品时,需端正心态,树立科学、健康的保险理念,避免走进购买误区。\n#idiom577159# 对消费者而言,保险是一种较为特殊的金融理财产品,其最基本原则是对风险的保障。虽然目前保险公司开发了诸多强调投资收益的险种,但无论任何种类的产品都不能偏离保险的本质。尤其是对于注重保障的人身保险而言,强调投资价值实属约定俗成。消费者在投资保险理财产品时,需端正心态,树立科学、健康的保险理念,避免走进购买误区。\n#idiom577159# 对消费者而言,保险是一种较为特殊的金融理财产品,其最基本原则是对风险的保障。虽然目前保险公司开发了诸多强调投资收益的险种,但无论任何种类的产品都不能偏离保险的本质。尤其是对于注重保障的人身保险而言,强调投资价值实属不伦不类。消费者在投资保险理财产品时,需端正心态,树立科学、健康的保险理念,避免走进购买误区。\n#idiom577159# 对消费者而言,保险是一种较为特殊的金融理财产品,其最基本原则是对风险的保障。虽然目前保险公司开发了诸多强调投资收益的险种,但无论任何种类的产品都不能偏离保险的本质。尤其是对于注重保障的人身保险而言,强调投资价值实属芒刺在背。消费者在投资保险理财产品时,需端正心态,树立科学、健康的保险理念,避免走进购买误区。\n#idiom577159# 对消费者而言,保险是一种较为特殊的金融理财产品,其最基本原则是对风险的保障。虽然目前保险公司开发了诸多强调投资收益的险种,但无论任何种类的产品都不能偏离保险的本质。尤其是对于注重保障的人身保险而言,强调投资价值实属不合时宜。消费者在投资保险理财产品时,需端正心态,树立科学、健康的保险理念,避免走进购买误区。\n"
     ]
    }
   ],
   "source": [
    "candidates = dev_dataset[0]['candidates']\n",
    "\n",
    "sentence = dev_dataset[0]['content'][2]\n",
    "res =  re.finditer(r\"#idiom\\d+#\", sentence, flags=0)\n",
    "sentence_filled = []\n",
    "\n",
    "for r in res:\n",
    "    answer = answer_dict[r.group()]\n",
    "    for candidate in candidates:\n",
    "        new_sentence = sentence[:r.start()] + candidate + sentence[r.end():]\n",
    "        new_sentence = re.sub('#idiom\\d+#', '', new_sentence)\n",
    "        print(r.group(), new_sentence)\n",
    "        sentence_filled.append(new_sentence)\n",
    "\n",
    "\n",
    "ids = tokenizer(sentence_filled, padding=True, return_tensors='tf', add_special_tokens=False)\n",
    "ids['labels'] = ids['input_ids']\n",
    "labels = ids['labels'][:, 1:]\n",
    "# labels = ids['input_ids']\n",
    "# mask = tf.equal(labels, tokenizer.pad_token_id)\n",
    "# active_label = tf.not_equal(labels, tokenizer.pad_token_id)\n",
    "# active_label = labels * tf.cast(active_label, tf.int32)\n",
    "# mask = tf.cast(mask, tf.int32) * -100\n",
    "# labels = active_label + mask\n",
    "# print(active_label)\n",
    "# print(ids)\n",
    "# out = model(ids, return_dict=True)\n",
    "# out.loss\n",
    "# labels = labels[:, :-1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "loss1: tf.Tensor(\n[7.7241654 7.719291  7.808548  7.731908  7.706756  7.7336817 7.72089\n 7.7075067 7.7773967 7.680266 ], shape=(10,), dtype=float32)\n9\ntf.Tensor(\n[7.7241654 7.719291  7.808548  7.731908  7.706756  7.7336817 7.72089\n 7.7075067 7.7773967 7.680266 ], shape=(10,), dtype=float32)\n9\ntruth answer 4\ntf.Tensor(\n[[27480 27856 27205 ... 28346 27322 26966]\n [27480 27856 27205 ... 28346 27322 26966]\n [27480 27856 27205 ... 28346 27322 26966]\n ...\n [27480 27856 27205 ... 28346 27322 26966]\n [27480 27856 27205 ... 28346 27322 26966]\n [27480 27856 27205 ... 28346 27322 26966]], shape=(10, 141), dtype=int32)\n"
     ]
    }
   ],
   "source": [
    "\n",
    "def loss_fun(labels, logits):\n",
    "    loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(\n",
    "        from_logits=True, reduction=tf.keras.losses.Reduction.NONE)\n",
    "    return loss_fn(labels, logits)\n",
    "\n",
    "\n",
    "def build_loss(tokenizer):\n",
    "    def custom_loss(labels, logits):\n",
    "        loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(\n",
    "            from_logits=True, reduction=tf.keras.losses.Reduction.NONE\n",
    "        )\n",
    "        mask = tf.not_equal(labels, tokenizer.pad_token_id)\n",
    "\n",
    "        labels = tf.cast(labels,tf.int32) * tf.cast(mask,tf.int32) \n",
    "        raw_loss = loss_fn(labels, logits)\n",
    "\n",
    "        mask = tf.cast(mask,tf.float32)\n",
    "        losses = tf.cast(raw_loss,tf.float32) * mask\n",
    "        losses = tf.reduce_sum(losses,axis=-1) / tf.reduce_sum(mask,axis=-1)\n",
    "        return losses\n",
    "\n",
    "    return custom_loss\n",
    "\n",
    "loss = build_loss(tokenizer)\n",
    "model.compute_loss = loss\n",
    "out = model(ids, return_dict=True)\n",
    "\n",
    "print(\"loss1:\", out.loss)\n",
    "print(np.argmin(out.loss))\n",
    "\n",
    "mask = tf.not_equal(labels, -100)\n",
    "\n",
    "labels = tf.cast(labels,tf.int32) * tf.cast(mask,tf.int32) \n",
    "raw_loss = loss_fun(labels,out.logits)\n",
    "\n",
    "mask = tf.cast(mask,tf.float32)\n",
    "\n",
    "losses = tf.cast(raw_loss, tf.float32) * mask\n",
    "losses = tf.reduce_sum(losses,axis=-1) / tf.reduce_sum(mask,axis=-1)\n",
    "print(losses)\n",
    "print(np.argmin(losses))\n",
    "\n",
    "print(\"truth answer\", answer)\n",
    "print(labels)\n",
    "# from transformers.modeling_tf_utils import shape_list\n",
    "\n",
    "# logits, labels = out.logits, ids['labels'][:,:-1]\n",
    "# print(labels.shape)\n",
    "# shape1 = labels.shape[-1]\n",
    "# active_loss = tf.not_equal(tf.reshape(labels, (-1,)), -100)\n",
    "# labels = tf.boolean_mask(tf.reshape(labels, (-1,)), active_loss)\n",
    "# print(labels)\n",
    "# reduced_logits = tf.boolean_mask(tf.reshape(logits, (-1, shape_list(logits)[2])), active_loss)\n",
    "# reduced_logits = tf.reshape(reduced_logits, (-1, shape1, reduced_logits.shape[-1]))\n",
    "# labels = tf.reshape(labels, (-1, shape1))\n",
    "# print(reduced_logits)\n",
    "# print(loss_fun(labels, reduced_logits))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "{'input_ids': <tf.Tensor: shape=(10, 119), dtype=int32, numpy=\n",
       "array([[  39,    8, 2272, ...,    8,   12,    5],\n",
       "       [  39,    8, 2272, ...,   12,    5,    5],\n",
       "       [  39,    8, 2272, ...,    8,   12,    5],\n",
       "       ...,\n",
       "       [  39,    8, 2272, ...,    8,   12,    5],\n",
       "       [  39,    8, 2272, ...,  194,    8,   12],\n",
       "       [  39,    8, 2272, ...,   12,    5,    5]], dtype=int32)>, 'token_type_ids': <tf.Tensor: shape=(10, 119), dtype=int32, numpy=\n",
       "array([[0, 0, 0, ..., 0, 0, 3],\n",
       "       [0, 0, 0, ..., 0, 3, 3],\n",
       "       [0, 0, 0, ..., 0, 0, 3],\n",
       "       ...,\n",
       "       [0, 0, 0, ..., 0, 0, 3],\n",
       "       [0, 0, 0, ..., 0, 0, 0],\n",
       "       [0, 0, 0, ..., 0, 3, 3]], dtype=int32)>, 'attention_mask': <tf.Tensor: shape=(10, 119), dtype=int32, numpy=\n",
       "array([[1, 1, 1, ..., 1, 1, 0],\n",
       "       [1, 1, 1, ..., 1, 0, 0],\n",
       "       [1, 1, 1, ..., 1, 1, 0],\n",
       "       ...,\n",
       "       [1, 1, 1, ..., 1, 1, 0],\n",
       "       [1, 1, 1, ..., 1, 1, 1],\n",
       "       [1, 1, 1, ..., 1, 0, 0]], dtype=int32)>, 'labels': <tf.Tensor: shape=(10, 119), dtype=int32, numpy=\n",
       "array([[  39,    8, 2272, ...,    8,   12,    5],\n",
       "       [  39,    8, 2272, ...,   12,    5,    5],\n",
       "       [  39,    8, 2272, ...,    8,   12,    5],\n",
       "       ...,\n",
       "       [  39,    8, 2272, ...,    8,   12,    5],\n",
       "       [  39,    8, 2272, ...,  194,    8,   12],\n",
       "       [  39,    8, 2272, ...,   12,    5,    5]], dtype=int32)>}"
      ]
     },
     "metadata": {},
     "execution_count": 76
    }
   ],
   "source": [
    "ids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "[9.835991  6.812191  4.5883446]\ntf.Tensor(1113.1414, shape=(), dtype=float32) tf.Tensor(125, shape=(), dtype=int32)\n[ 6.812191   4.5883446 13.638993 ]\ntf.Tensor(1087.4413, shape=(), dtype=float32) tf.Tensor(122, shape=(), dtype=int32)\n[ 4.5883446 13.638993  11.257914 ]\ntf.Tensor(1110.6835, shape=(), dtype=float32) tf.Tensor(124, shape=(), dtype=int32)\n[13.638993 11.257914 10.230735]\ntf.Tensor(1050.977, shape=(), dtype=float32) tf.Tensor(122, shape=(), dtype=int32)\n[8.90513, 8.913453, 8.957125, 8.614566]\n"
     ]
    }
   ],
   "source": [
    "start_i = 0\n",
    "losses = []\n",
    "for mask in ids['attention_mask']:\n",
    "    active_count = sum(mask)\n",
    "    loss = out.loss[start_i: start_i+active_count]\n",
    "    print(loss[:3].numpy())\n",
    "    loss_sum = sum(loss)\n",
    "    print(loss_sum, active_count)\n",
    "    loss = loss_sum / tf.cast(active_count, tf.float32)\n",
    "    losses.append(loss.numpy())\n",
    "    start_i += active_count\n",
    "print(losses)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 113,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "mask tf.Tensor(\n[[ True  True  True  True  True  True False False False]\n [ True  True  True  True  True  True  True  True  True]], shape=(2, 9), dtype=bool)\nlabels tf.Tensor(\n[[28051  5749 26988 27841 27160 27840     0     0     0]\n [26977 27172 26971 26968 27320 27952 27970  6796  1149]], shape=(2, 9), dtype=int32)\nraw_loss tf.Tensor(\n[[9.3518257e+00 4.0583386e+00 4.1490216e+00 6.1921062e+00 5.2340332e-02\n  1.2677022e-03 1.0334850e+01 7.9349532e+00 7.4530206e+00]\n [4.3851023e+00 5.5624809e+00 1.8138936e+00 6.0646114e+00 1.5625546e-02\n  1.1773869e+01 4.4465199e+00 1.3087559e+00 6.4660233e-01]], shape=(2, 9), dtype=float32)\nlosses tf.Tensor(\n[[9.3518257e+00 4.0583386e+00 4.1490216e+00 6.1921062e+00 5.2340332e-02\n  1.2677022e-03 0.0000000e+00 0.0000000e+00 0.0000000e+00]\n [4.3851023e+00 5.5624809e+00 1.8138936e+00 6.0646114e+00 1.5625546e-02\n  1.1773869e+01 4.4465199e+00 1.3087559e+00 6.4660233e-01]], shape=(2, 9), dtype=float32)\n"
     ]
    }
   ],
   "source": [
    "def loss_fun(labels, logits):\n",
    "    loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(\n",
    "        from_logits=True, reduction=tf.keras.losses.Reduction.NONE)\n",
    "    return loss_fn(labels, logits)\n",
    "mask = tf.not_equal(labels, 0)\n",
    "print(\"mask\", mask)\n",
    "labels = tf.cast(labels,tf.int32) * tf.cast(mask,tf.int32)\n",
    "print(\"labels\", labels)\n",
    "raw_loss = loss_fun(labels,out.logits)\n",
    "print(\"raw_loss\", raw_loss)\n",
    "mask = tf.cast(mask,tf.float32)\n",
    "losses = tf.cast(raw_loss,tf.float32) * mask\n",
    "print(\"losses\", losses)\n",
    "# losses = tf.reduce_sum(losses,axis=-1) / tf.reduce_sum(mask,axis=-1)\n",
    "# print(\"losses\", losses)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "(<tf.Tensor: shape=(2,), dtype=float32, numpy=array([23.804901, 36.01746 ], dtype=float32)>,\n",
       " <tf.Tensor: shape=(2,), dtype=float32, numpy=array([6., 9.], dtype=float32)>)"
      ]
     },
     "metadata": {},
     "execution_count": 115
    }
   ],
   "source": [
    "tf.reduce_sum(losses,axis=-1), tf.reduce_sum(mask,axis=-1)"
   ]
  }
 ]
}