File size: 24,676 Bytes
e2afaaf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "5d9aca72-957a-4ee2-862f-e011b9cd3a62",
   "metadata": {},
   "source": [
    "---\n",
    "title: \"Inference Endpoints\"\n",
    "---\n",
    "\n",
    "# How to use Inference Endpoints to Embed Documents\n",
    "\n",
    "_Authored by: [Derek Thomas](https://huggingface.co/derek-thomas)_\n",
    "\n",
    "## Goal\n",
    "I have a dataset I want to embed for semantic search (or QA, or RAG), I want the easiest way to do embed this and put it in a new dataset.\n",
    "\n",
    "## Approach\n",
    "I'm using a dataset from my favorite subreddit [r/bestofredditorupdates](https://www.reddit.com/r/bestofredditorupdates/). Because it has long entries, I will use the new [jinaai/jina-embeddings-v2-base-en](https://huggingface.co/jinaai/jina-embeddings-v2-base-en) since it has an 8k context length. I will deploy this using [Inference Endpoint](https://huggingface.co/inference-endpoints) to save time and money. To follow this tutorial, you will need to **have already added a payment method**. If you haven't, you can add one here in [billing](https://huggingface.co/docs/hub/billing#billing). To make it even easier, I'll make this fully API based.\n",
    "\n",
    "To make this MUCH faster I will use the [Text Embeddings Inference](https://github.com/huggingface/text-embeddings-inference) image. This has many benefits like:\n",
    "- No model graph compilation step\n",
    "- Small docker images and fast boot times. Get ready for true serverless!\n",
    "- Token based dynamic batching\n",
    "- Optimized transformers code for inference using Flash Attention, Candle and cuBLASLt\n",
    "- Safetensors weight loading\n",
    "- Production ready (distributed tracing with Open Telemetry, Prometheus metrics)\n",
    "\n",
    "![img](https://media.githubusercontent.com/media/huggingface/text-embeddings-inference/main/assets/bs1-tp.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c830114-dd88-45a9-81b9-78b0e3da7384",
   "metadata": {},
   "source": [
    "## Requirements"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35386f72-32cb-49fa-a108-3aa504e20429",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "!pip install -q aiohttp==3.8.3 datasets==2.14.6 pandas==1.5.3 requests==2.31.0 tqdm==4.66.1 huggingface-hub>=0.20"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b6f72042-173d-4a72-ade1-9304b43b528d",
   "metadata": {},
   "source": [
    "## Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e2beecdd-d033-4736-bd45-6754ec53b4ac",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import asyncio\n",
    "from getpass import getpass\n",
    "import json\n",
    "from pathlib import Path\n",
    "import time\n",
    "from typing import Optional\n",
    "\n",
    "from aiohttp import ClientSession, ClientTimeout\n",
    "from datasets import load_dataset, Dataset, DatasetDict\n",
    "from huggingface_hub import notebook_login, create_inference_endpoint, list_inference_endpoints, whoami\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import requests\n",
    "from tqdm.auto import tqdm"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5eece903-64ce-435d-a2fd-096c0ff650bf",
   "metadata": {},
   "source": [
    "## Config\n",
    "`DATASET_IN` is where your text data is\n",
    "`DATASET_OUT` is where your embeddings will be stored\n",
    "\n",
    "Note I used 5 for the `MAX_WORKERS` since `jina-embeddings-v2` are quite memory hungry. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "df2f79f0-9f28-46e6-9fc7-27e9537ff5be",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "DATASET_IN = 'derek-thomas/dataset-creator-reddit-bestofredditorupdates'\n",
    "DATASET_OUT = \"processed-subset-bestofredditorupdates\"\n",
    "ENDPOINT_NAME = \"boru-jina-embeddings-demo-ie\"\n",
    "\n",
    "MAX_WORKERS = 5  # This is for how many async workers you want. Choose based on the model and hardware \n",
    "ROW_COUNT = 100  # Choose None to use all rows, Im using 100 just for a demo"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e680f3d-4900-46cc-8b49-bb6ba3e27e2b",
   "metadata": {},
   "source": [
    "Hugging Face offers a number of GPUs that you can choose from a number of GPUs that you can choose in Inference Endpoints. Here they are in table form:\n",
    "\n",
    "| GPU                 | instanceType   | instanceSize | vRAM  |\n",
    "|---------------------|----------------|--------------|-------|\n",
    "| 1x Nvidia Tesla T4 | g4dn.xlarge | small | 16GB |\n",
    "| 4x Nvidia Tesla T4 | g4dn.12xlarge | large | 64GB |\n",
    "| 1x Nvidia A10G | g5.2xlarge | medium | 24GB |\n",
    "| 4x Nvidia A10G | g5.12xlarge | xxlarge | 96GB |\n",
    "| 1x Nvidia A100* | p4de | xlarge | 80GB |\n",
    "| 2x Nvidia A100* | p4de | 2xlarge | 160GB |\n",
    "\n",
    "\\*Note that for A100s you might get a note to email us to get access."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "3c2106c1-2e5a-443a-9ea8-a3cd0e9c5a94",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# GPU Choice\n",
    "VENDOR=\"aws\"\n",
    "REGION=\"us-east-1\"\n",
    "INSTANCE_SIZE=\"medium\"\n",
    "INSTANCE_TYPE=\"g5.2xlarge\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0ca1140c-3fcc-4b99-9210-6da1505a27b7",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "ee80821056e147fa9cabf30f64dc85a8",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(HTML(value='<center> <img\\nsrc=https://huggingface.co/front/assets/huggingface_logo-noborder.sv…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "notebook_login()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5f4ba0a8-0a6c-4705-a73b-7be09b889610",
   "metadata": {},
   "source": [
    "Some users might have payment registered in an organization. This allows you to connect to an organization (that you are a member of) with a payment method.\n",
    "\n",
    "Leave it blank is you want to use your username."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "88cdbd73-5923-4ae9-9940-b6be935f70fa",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "What is your Hugging Face 🤗 username or organization? (with an added payment method) ········\n"
     ]
    }
   ],
   "source": [
    "who = whoami()\n",
    "organization = getpass(prompt=\"What is your Hugging Face 🤗 username or organization? (with an added payment method)\")\n",
    "\n",
    "namespace = organization or who['name']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b972a719-2aed-4d2e-a24f-fae7776d5fa4",
   "metadata": {},
   "source": [
    "## Get Dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "27835fa4-3a4f-44b1-a02a-5e31584a1bba",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "4041cedd3b3f4f8db3e29ec102f46a3a",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading readme:   0%|          | 0.00/1.73k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "Dataset({\n",
       "    features: ['id', 'content', 'score', 'date_utc', 'title', 'flair', 'poster', 'permalink', 'new', 'updated'],\n",
       "    num_rows: 10042\n",
       "})"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dataset = load_dataset(DATASET_IN)\n",
    "dataset['train']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "8846087e-4d0d-4c0e-8aeb-ea95d9e97126",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(100,\n",
       " {'id': '10004zw',\n",
       "  'content': '[removed]',\n",
       "  'score': 1,\n",
       "  'date_utc': Timestamp('2022-12-31 18:16:22'),\n",
       "  'title': 'To All BORU contributors, Thank you :)',\n",
       "  'flair': 'CONCLUDED',\n",
       "  'poster': 'IsItAcOnSeQuEnCe',\n",
       "  'permalink': '/r/BestofRedditorUpdates/comments/10004zw/to_all_boru_contributors_thank_you/',\n",
       "  'new': False,\n",
       "  'updated': False})"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "documents = dataset['train'].to_pandas().to_dict('records')[:ROW_COUNT]\n",
    "len(documents), documents[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "93096cbc-81c6-4137-a283-6afb0f48fbb9",
   "metadata": {},
   "source": [
    "# Inference Endpoints\n",
    "## Create Inference Endpoint\n",
    "We are going to use the [API](https://huggingface.co/docs/inference-endpoints/api_reference) to create an [Inference Endpoint](https://huggingface.co/inference-endpoints). This should provide a few main benefits:\n",
    "- It's convenient (No clicking)\n",
    "- It's repeatable (We have the code to run it easily)\n",
    "- It's cheaper (No time spent waiting for it to load, and automatically shut it down)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "9e59de46-26b7-4bb9-bbad-8bba9931bde7",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    endpoint = create_inference_endpoint(\n",
    "        ENDPOINT_NAME,\n",
    "        repository=\"jinaai/jina-embeddings-v2-base-en\",\n",
    "        revision=\"7302ac470bed880590f9344bfeee32ff8722d0e5\",\n",
    "        task=\"sentence-embeddings\",\n",
    "        framework=\"pytorch\",\n",
    "        accelerator=\"gpu\",\n",
    "        instance_size=INSTANCE_SIZE,\n",
    "        instance_type=INSTANCE_TYPE,\n",
    "        region=REGION,\n",
    "        vendor=VENDOR,\n",
    "        namespace=namespace,\n",
    "        custom_image={\n",
    "            \"health_route\": \"/health\",\n",
    "            \"env\": {\n",
    "                \"MAX_BATCH_TOKENS\": str(MAX_WORKERS * 2048),\n",
    "                \"MAX_CONCURRENT_REQUESTS\": \"512\",\n",
    "                \"MODEL_ID\": \"/repository\"\n",
    "            },\n",
    "            \"url\": \"ghcr.io/huggingface/text-embeddings-inference:0.5.0\",\n",
    "        },\n",
    "        type=\"protected\",\n",
    "    )\n",
    "except:\n",
    "    endpoint = [ie for ie in list_inference_endpoints(namespace=namespace) if ie.name == ENDPOINT_NAME][0]\n",
    "    print('Loaded endpoint')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0f2c97dc-34e8-49e9-b60e-f5b7366294c0",
   "metadata": {},
   "source": [
    "There are a few design choices here:\n",
    "- As discussed before we are using `jinaai/jina-embeddings-v2-base-en` as our model. \n",
    "    - For reproducibility we are pinning it to a specific revision.\n",
    "- If you are interested in more models, check out the supported list [here](https://huggingface.co/docs/text-embeddings-inference/supported_models). \n",
    "    - Note that most embedding models are based on the BERT architecture.\n",
    "- `MAX_BATCH_TOKENS` is chosen based on our number of workers and the context window of our embedding model.\n",
    "- `type=\"protected\"` utilized the security from Inference Endpoints detailed here.\n",
    "- I'm using **1x Nvidia A10** since `jina-embeddings-v2` is memory hungry (remember the 8k context length). \n",
    "- You should consider further tuning `MAX_BATCH_TOKENS` and `MAX_CONCURRENT_REQUESTS` if you have high workloads\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "96d173b2-8980-4554-9039-c62843d3fc7d",
   "metadata": {},
   "source": [
    "## Wait until it's running"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "5f3a8bd2-753c-49a8-9452-899578beddc5",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 48.1 ms, sys: 15.7 ms, total: 63.8 ms\n",
      "Wall time: 52.6 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "InferenceEndpoint(name='boru-jina-embeddings-demo-ie', namespace='HF-test-lab', repository='jinaai/jina-embeddings-v2-base-en', status='running', url='https://k7l1xeok1jwnpbx5.us-east-1.aws.endpoints.huggingface.cloud')"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "endpoint.wait()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a906645e-60de-4eb6-b8b6-3ec98a9d9b00",
   "metadata": {},
   "source": [
    "When we use `endpoint.client.post` we get a bytes string back. This is a little tedious because we need to convert this to an `np.array`, but it's just a couple quick lines in python."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "e09253d5-70ff-4d0e-8888-0022ce0adf7b",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([-0.05630935, -0.03560849,  0.02789049,  0.02792823, -0.02800371,\n",
       "       -0.01530391, -0.01863454, -0.0077982 ,  0.05374297,  0.03672185,\n",
       "       -0.06114018, -0.06880157, -0.0093503 , -0.03174005, -0.03206085,\n",
       "        0.0610647 ,  0.02243694,  0.03217408,  0.04181686,  0.00248854])"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response = endpoint.client.post(json={\"inputs\": 'This sound track was beautiful! It paints the senery in your mind so well I would recomend it even to people who hate vid. game music!', 'truncate': True}, task=\"feature-extraction\")\n",
    "response = np.array(json.loads(response.decode()))\n",
    "response[0][:20]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0d024788-6e6e-4a8d-b192-36ee3dacca13",
   "metadata": {},
   "source": [
    "You may have inputs that exceed the context. In such scenarios, it's up to you to handle them. In my case, I'd like to truncate rather than have an error. Let's test that it works."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "a4a1cd15-dda3-4cfa-8bda-788d8c1b9e32",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The length of the embedding_input is: 300000\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([-0.03088215, -0.0351537 ,  0.05749275,  0.00983467,  0.02108356,\n",
       "        0.04539965,  0.06107162, -0.02536954,  0.03887688,  0.01998681,\n",
       "       -0.05391388,  0.01529677, -0.1279156 ,  0.01653782, -0.01940958,\n",
       "        0.0367411 ,  0.0031748 ,  0.04716022, -0.00713609, -0.00155313])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "embedding_input = 'This input will get multiplied' * 10000\n",
    "print(f'The length of the embedding_input is: {len(embedding_input)}')\n",
    "response = endpoint.client.post(json={\"inputs\": embedding_input, 'truncate': True}, task=\"feature-extraction\")\n",
    "response = np.array(json.loads(response.decode()))\n",
    "response[0][:20]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f7186126-ef6a-47d0-b158-112810649cd9",
   "metadata": {},
   "source": [
    "# Get Embeddings"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1dadfd68-6d46-4ce8-a165-bfeb43b1f114",
   "metadata": {},
   "source": [
    "Here I send a document, update it with the embedding, and return it. This happens in parallel with `MAX_WORKERS`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "ad3193fb-3def-42a8-968e-c63f2b864ca8",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "async def request(document, semaphore):\n",
    "    # Semaphore guard\n",
    "    async with semaphore:\n",
    "        result = await endpoint.async_client.post(json={\"inputs\": document['content'], 'truncate': True}, task=\"feature-extraction\")\n",
    "        result = np.array(json.loads(result.decode()))\n",
    "        document['embedding'] = result[0]  # Assuming the API's output can be directly assigned\n",
    "        return document\n",
    "\n",
    "async def main(documents):\n",
    "    # Semaphore to limit concurrent requests. Adjust the number as needed.\n",
    "    semaphore = asyncio.BoundedSemaphore(MAX_WORKERS)\n",
    "\n",
    "    # Creating a list of tasks\n",
    "    tasks = [request(document, semaphore) for document in documents]\n",
    "    \n",
    "    # Using tqdm to show progress. It's been integrated into the async loop.\n",
    "    for f in tqdm(asyncio.as_completed(tasks), total=len(documents)):\n",
    "        await f"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "ec4983af-65eb-4841-808a-3738fb4d682d",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "48a2affdee8d46f3b0c1f691eaac4b89",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "  0%|          | 0/100 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Embeddings = 100 documents = 100\n",
      "0 min 21.33 sec\n"
     ]
    }
   ],
   "source": [
    "start = time.perf_counter()\n",
    "\n",
    "# Get embeddings\n",
    "await main(documents)\n",
    "\n",
    "# Make sure we got it all\n",
    "count = 0\n",
    "for document in documents:\n",
    "    if 'embedding' in document.keys() and len(document['embedding']) == 768:\n",
    "        count += 1\n",
    "print(f'Embeddings = {count} documents = {len(documents)}')\n",
    "\n",
    "            \n",
    "# Print elapsed time\n",
    "elapsed_time = time.perf_counter() - start\n",
    "minutes, seconds = divmod(elapsed_time, 60)\n",
    "print(f\"{int(minutes)} min {seconds:.2f} sec\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bab97c7b-7bac-4bf5-9752-b528294dadc7",
   "metadata": {},
   "source": [
    "## Pause Inference Endpoint\n",
    "Now that we have finished, let's pause the endpoint so we don't incur any extra charges, this will also allow us to analyze the cost."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "540a0978-7670-4ce3-95c1-3823cc113b85",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Endpoint Status: paused\n"
     ]
    }
   ],
   "source": [
    "endpoint = endpoint.pause()\n",
    "\n",
    "print(f\"Endpoint Status: {endpoint.status}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "45ad65b7-3da2-4113-9b95-8fb4e21ae793",
   "metadata": {},
   "source": [
    "# Push updated dataset to Hub\n",
    "We now have our documents updated with the embeddings we wanted. First we need to convert it back to a `Dataset` format. I find it easiest to go from list of dicts -> `pd.DataFrame` -> `Dataset`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "9bb993f8-d624-4192-9626-8e9ed9888a1b",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "df = pd.DataFrame(documents)\n",
    "dd = DatasetDict({'train': Dataset.from_pandas(df)})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "129760c8-cae1-4b1e-8216-f5152df8c536",
   "metadata": {},
   "source": [
    "I'm uploading it to the user's account by default (as opposed to uploading to an organization) but feel free to push to wherever you want by setting the user in the `repo_id` or in the config by setting `DATASET_OUT`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "f48e7c55-d5b7-4ed6-8516-272ae38716b1",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "d3af2e864770481db5adc3968500b5d3",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Pushing dataset shards to the dataset hub:   0%|          | 0/1 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "4e063c42d8f4490c939bc64e626b507a",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading metadata:   0%|          | 0.00/823 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "dd.push_to_hub(repo_id=DATASET_OUT)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "85ea2244-a4c6-4f04-b187-965a2fc356a8",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dataset is at https://huggingface.co/datasets/derek-thomas/processed-subset-bestofredditorupdates\n"
     ]
    }
   ],
   "source": [
    "print(f'Dataset is at https://huggingface.co/datasets/{who[\"name\"]}/{DATASET_OUT}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41abea64-379d-49de-8d9a-355c2f4ce1ac",
   "metadata": {},
   "source": [
    "# Analyze Usage\n",
    "1. Go to your `dashboard_url` printed below\n",
    "1. Click on the Usage & Cost tab\n",
    "1. See how much you have spent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "16815445-3079-43da-b14e-b54176a07a62",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "https://ui.endpoints.huggingface.co/HF-test-lab/endpoints/boru-jina-embeddings-demo-ie\n"
     ]
    }
   ],
   "source": [
    "dashboard_url = f'https://ui.endpoints.huggingface.co/{namespace}/endpoints/{ENDPOINT_NAME}'\n",
    "print(dashboard_url)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "81096c6f-d12f-4781-84ec-9066cfa465b3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hit enter to continue with the notebook \n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "''"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "input(\"Hit enter to continue with the notebook\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "847d524e-9aa6-4a6f-a275-8a552e289818",
   "metadata": {},
   "source": [
    "We can see that it only took `$0.04` to pay for this!\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b953d5be-2494-4ff8-be42-9daf00c99c41",
   "metadata": {},
   "source": [
    "\n",
    "# Delete Endpoint\n",
    "Now that we are done, we don't need our endpoint anymore. We can delete our endpoint programmatically. \n",
    "\n",
    "![Cost](https://huggingface.co/datasets/huggingface/cookbook-images/resolve/main/automatic_embedding_tei_inference_endpoints.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "c310c0f3-6f12-4d5c-838b-3a4c1f2e54ad",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Endpoint deleted successfully\n"
     ]
    }
   ],
   "source": [
    "endpoint = endpoint.delete()\n",
    "\n",
    "if not endpoint:\n",
    "    print('Endpoint deleted successfully')\n",
    "else:\n",
    "    print('Delete Endpoint in manually') "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "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.10.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}