-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathllms-ctx-full.txt
1757 lines (1455 loc) · 64.3 KB
/
llms-ctx-full.txt
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<project title="Gaspard" summary="Gaspard is a Python library that wraps Google's Gemini API to provide a higher-level interface for creating AI applications. It automates common patterns while maintaining full control, offering features like stateful chat, prefill support, image handling, and streamlined tool use.">Things to remember when using Gaspard:
- You must set the `GEMINI_API_KEY` environment variable with your Gemini API key
- Gaspard is designed to work with multiple Gemini models (including for example `gemini-1.5-pro` and `gemini-2.0-flash-exp` ).
- The library provides support for tool calling and various forms of media including images.
- Use `Chat()` for maintaining conversation state and handling tool interactions
- When using tools, the library automatically handles the request/response loop
- Gaspard supports various media types: images, audio files, video files, PDF documents, etc..
- Gaspard's API design is similar to Claudette (for Anthropic's Claude model) and Cosette (for OpenAI's models)<docs><doc title="README" desc="Quick start guide and overview"># Gaspard
## Install
``` sh
pip install gaspard
```
## Getting started
Follow the [instructions](https://aistudio.google.com/app/apikey) to
generate an API key, and set it as an evironment variable as shown
below:
``` sh
export GEMINI_API_KEY=YOUR_API_KEY
```
Gemini’s Python SDK will automatically be installed with Gaspard, if you
don’t already have it.
``` python
from gaspard import *
```
Gaspard provides models, which lists the models available in the SDK
``` python
models
```
('gemini-2.0-flash-exp',
'gemini-exp-1206',
'learnlm-1.5-pro-experimental',
'gemini-exp-1121',
'gemini-1.5-pro',
'gemini-1.5-flash',
'gemini-1.5-flash-8b')
For our examples we’ll use `gemini-2.0-flash-exp` since it’s awesome,
has a 1M context window and is currently free while in the experimental
stage.
``` python
model = models[0]
```
## Chat
The main interface to Gaspard is the
[`Chat`](https://AnswerDotAI.github.io/gaspard/core.html#chat) class
which provides a stateful interface to the models
``` python
chat = Chat(model, sp="""You are a helpful and concise assistant.""")
chat("I'm Faisal")
```
Hi Faisal, it’s nice to meet you!
<details>
- content: {‘parts’: \[{‘text’: “Hi Faisal, it’s nice to meet you!”}\],
‘role’: ‘model’}
- finish_reason: 1
- safety_ratings: \[{‘category’: 8, ‘probability’: 1, ‘blocked’: False},
{‘category’: 10, ‘probability’: 1, ‘blocked’: False}, {‘category’: 7,
‘probability’: 1, ‘blocked’: False}, {‘category’: 9, ‘probability’: 1,
‘blocked’: False}\]
- avg_logprobs: -0.04827792942523956
- token_count: 0
- grounding_attributions: \[\]
- prompt_token_count: 14
- candidates_token_count: 12
- total_token_count: 26
- cached_content_token_count: 0
</details>
``` python
r = chat("What's my name?")
r
```
Your name is Faisal.
<details>
- content: {‘parts’: \[{‘text’: ‘Your name is Faisal.’}\], ‘role’:
‘model’}
- finish_reason: 1
- safety_ratings: \[{‘category’: 8, ‘probability’: 1, ‘blocked’: False},
{‘category’: 10, ‘probability’: 1, ‘blocked’: False}, {‘category’: 7,
‘probability’: 1, ‘blocked’: False}, {‘category’: 9, ‘probability’: 1,
‘blocked’: False}\]
- avg_logprobs: -1.644962443000016e-05
- token_count: 0
- grounding_attributions: \[\]
- prompt_token_count: 35
- candidates_token_count: 6
- total_token_count: 41
- cached_content_token_count: 0
</details>
As you see above, displaying the results of a call in a notebook shows
just the message contents, with the other details hidden behind a
collapsible section. Alternatively you can print the details:
``` python
print(r)
```
response:
GenerateContentResponse(
done=True,
iterator=None,
result=protos.GenerateContentResponse({
"candidates": [
{
"content": {
"parts": [
{
"text": "Your name is Faisal.\n"
}
],
"role": "model"
},
"finish_reason": "STOP",
"safety_ratings": [
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_HARASSMENT",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"probability": "NEGLIGIBLE"
}
],
"avg_logprobs": -1.644962443000016e-05
}
],
"usage_metadata": {
"prompt_token_count": 35,
"candidates_token_count": 6,
"total_token_count": 41
}
}),
)
You can use stream=True to stream the results as soon as they arrive
(although you will only see the gradual generation if you execute the
notebook yourself, of course!)
``` python
chat.h
```
[{'role': 'user', 'parts': [{'text': "I'm Faisal"}, ' ']},
{'role': 'model', 'parts': ["Hi Faisal, it's nice to meet you!\n"]},
{'role': 'user', 'parts': [{'text': "What's my name?"}, ' ']},
{'role': 'model', 'parts': ['Your name is Faisal.\n']}]
``` python
for o in chat("What's your name? Tell me your story", stream=True): print(o, end='')
```
I don't have a name or a personal story in the way a human does. I am a large language model, created by Google AI. I was trained on a massive amount of text data to be able to communicate and generate human-like text. I don't have a body, feelings, or memories, but I'm here to help you with information and tasks.
Woah, welcome back to the land of the living Bard!
## Tool use
Tool use lets the model use external tools.
We use docments to make defining Python functions as ergonomic as
possible. Each parameter (and the return value) should have a type, and
a docments comment with the description of what it is. As an example
we’ll write a simple function that adds numbers together, and will tell
us when it’s being called:
``` python
def sums(
a:int, # First thing to sum
b:int=1 # Second thing to sum
) -> int: # The sum of the inputs
"Adds a + b."
print(f"Finding the sum of {a} and {b}")
return a + b
```
Sometimes the model will say something like “according to the sums tool
the answer is” – generally we’d rather it just tells the user the
answer, so we can use a system prompt to help with this:
``` python
sp = "Never mention what tools you use."
```
We’ll get the model to add up some long numbers:
``` python
a,b = 604542,6458932
pr = f"What is {a}+{b}?"
pr
```
'What is 604542+6458932?'
To use tools, pass a list of them to Chat:
``` python
chat = Chat(model, sp=sp, tools=[sums])
```
Now when we call that with our prompt, the model doesn’t return the
answer, but instead returns a `function_call` message, which means we
have to call the named function (tool) with the provided parameters:
``` python
type(pr)
```
str
``` python
r = chat(pr); r
```
Finding the sum of 604542.0 and 6458932.0
function_call { name: “sums” args { fields { key: “b” value {
number_value: 6458932 } } fields { key: “a” value { number_value: 604542
} } } }
<details>
- content: {‘parts’: \[{‘function_call’: {‘name’: ‘sums’, ‘args’: {‘a’:
604542.0, ‘b’: 6458932.0}}}\], ‘role’: ‘model’}
- finish_reason: 1
- safety_ratings: \[{‘category’: 8, ‘probability’: 1, ‘blocked’: False},
{‘category’: 10, ‘probability’: 1, ‘blocked’: False}, {‘category’: 7,
‘probability’: 1, ‘blocked’: False}, {‘category’: 9, ‘probability’: 1,
‘blocked’: False}\]
- avg_logprobs: -9.219200364896096e-06
- token_count: 0
- grounding_attributions: \[\]
- prompt_token_count: 77
- candidates_token_count: 3
- total_token_count: 80
- cached_content_token_count: 0
</details>
Gaspard handles all that for us – we just have to pass along the
message, and it all happens automatically:
``` python
chat.h
```
[{'role': 'user', 'parts': [{'text': 'What is 604542+6458932?'}, ' ']},
{'role': 'model',
'parts': [function_call {
name: "sums"
args {
fields {
key: "b"
value {
number_value: 6458932
}
}
fields {
key: "a"
value {
number_value: 604542
}
}
}
}]},
{'role': 'user',
'parts': [name: "sums"
response {
fields {
key: "result"
value {
number_value: 7063474
}
}
},
{'text': ' '}]}]
``` python
chat()
```
7063474
<details>
- content: {‘parts’: \[{‘text’: ‘7063474’}\], ‘role’: ‘model’}
- finish_reason: 1
- safety_ratings: \[{‘category’: 8, ‘probability’: 1, ‘blocked’: False},
{‘category’: 10, ‘probability’: 1, ‘blocked’: False}, {‘category’: 7,
‘probability’: 1, ‘blocked’: False}, {‘category’: 9, ‘probability’: 1,
‘blocked’: False}\]
- avg_logprobs: -0.005276891868561506
- token_count: 0
- grounding_attributions: \[\]
- prompt_token_count: 128
- candidates_token_count: 8
- total_token_count: 136
- cached_content_token_count: 0
</details>
We can inspect the history to see what happens under the hood. Gaspard
calls the tool with the appropriate variables returned by the
`function_call` message from the model. The result of calling the
function is then sent back to the model, which uses that to respond to
the user.
``` python
chat.h[-3:]
```
[{'role': 'model',
'parts': [function_call {
name: "sums"
args {
fields {
key: "b"
value {
number_value: 6458932
}
}
fields {
key: "a"
value {
number_value: 604542
}
}
}
}]},
{'role': 'user',
'parts': [name: "sums"
response {
fields {
key: "result"
value {
number_value: 7063474
}
}
},
{'text': ' '}]},
{'role': 'model', 'parts': ['7063474\n']}]
You can see how many tokens have been used at any time by checking the
`use` property.
``` python
chat.use
```
In: 205; Out: 11; Total: 216
## Tool loop
We can do everything needed to use tools in a single step, by using
Chat.toolloop. This can even call multiple tools as needed solve a
problem. For example, let’s define a tool to handle multiplication:
``` python
def mults(
a:int, # First thing to multiply
b:int=1 # Second thing to multiply
) -> int: # The product of the inputs
"Multiplies a * b."
print(f"Finding the product of {a} and {b}")
return a * b
```
Now with a single call we can calculate `(a+b)*2` – by passing
`show_trace` we can see each response from the model in the process:
``` python
chat = Chat(model, sp=sp, tools=[sums,mults])
pr = f'Calculate ({a}+{b})*2'
pr
```
'Calculate (604542+6458932)*2'
``` python
def pchoice(r): print(r.parts[0])
```
``` python
r = chat.toolloop(pr, trace_func=pchoice)
```
Finding the sum of 604542.0 and 6458932.0
function_call {
name: "sums"
args {
fields {
key: "b"
value {
number_value: 6458932
}
}
fields {
key: "a"
value {
number_value: 604542
}
}
}
}
Finding the product of 7063474.0 and 2.0
function_call {
name: "mults"
args {
fields {
key: "b"
value {
number_value: 2
}
}
fields {
key: "a"
value {
number_value: 7063474
}
}
}
}
text: "(604542+6458932)*2 = 14126948\n"
We can see from the trace above that the model correctly calls the sums
function first to add the numbers inside the parenthesis and then calls
the mults function to multiply the result of the summation by `2`. The
response sent back to the user is the actual result after performing the
chained tool calls, shown below:
``` python
r
```
(604542+6458932)\*2 = 14126948
<details>
- content: {‘parts’: \[{‘text’: ’(604542+6458932)\*2 = 14126948’}\],
‘role’: ‘model’}
- finish_reason: 1
- safety_ratings: \[{‘category’: 8, ‘probability’: 1, ‘blocked’: False},
{‘category’: 10, ‘probability’: 1, ‘blocked’: False}, {‘category’: 7,
‘probability’: 1, ‘blocked’: False}, {‘category’: 9, ‘probability’: 1,
‘blocked’: False}\]
- avg_logprobs: -0.00017791306267359426
- token_count: 0
- grounding_attributions: \[\]
- prompt_token_count: 229
- candidates_token_count: 28
- total_token_count: 257
- cached_content_token_count: 0
</details>
## Structured Outputs
If you just want the immediate result from a single tool, use
[`Client.structured`](https://AnswerDotAI.github.io/gaspard/core.html#client.structured).
``` python
cli = Client(model)
```
``` python
def sums(
a:int, # First thing to sum
b:int=1 # Second thing to sum
) -> int: # The sum of the inputs
"Adds a + b."
print(f"Finding the sum of {a} and {b}")
return a + b
```
``` python
cli.structured("What is 604542+6458932", sums)
```
Finding the sum of 604542.0 and 6458932.0
[7063474.0]
This is particularly useful for getting back structured information,
e.g:
``` python
class President(BasicRepr):
"Information about a president of the United States"
def __init__(self,
first:str, # first name
last:str, # last name
spouse:str, # name of spouse
years_in_office:str, # format: "{start_year}-{end_year}"
birthplace:str, # name of city
birth_year:int # year of birth, `0` if unknown
):
assert re.match(r'\d{4}-\d{4}', years_in_office), "Invalid format: `years_in_office`"
store_attr()
```
``` python
cli.structured("Provide key information about the 3rd President of the United States", President)[0]
```
President(first='Thomas', last='Jefferson', spouse='Martha Wayles Skelton', years_in_office='1801-1809', birthplace='Shadwell', birth_year=1743.0)
## Images
As everyone knows, when testing image APIs you have to use a cute puppy.
But, that’s boring, so here’s a baby hippo instead.
``` python
img_fn = Path('samples/baby_hippo.jpg')
display.Image(filename=img_fn, width=200)
```
<img src="index_files/figure-commonmark/cell-30-output-1.jpeg"
width="200" />
We create a
[`Chat`](https://AnswerDotAI.github.io/gaspard/core.html#chat) object as
before:
``` python
chat = Chat(model)
```
For Gaspard, we can simply pass `Path` objects that repsent the path of
the images. To pass multi-part messages, such as an image along with a
prompt, we simply pass in a list of items. Note that Gaspard expects
each item to be a text or a `Path` object.
``` python
chat([img_fn, "In brief, is happening in the photo?"])
```
Certainly!
In the photo, a person’s hand is gently touching the chin of a baby
hippopotamus. The hippo is sitting on the ground and appears to be
looking straight at the camera.
<details>
- content: {‘parts’: \[{‘text’: “Certainly!the photo, a person’s hand is
gently touching the chin of a baby hippopotamus. The hippo is sitting
on the ground and appears to be looking straight at the camera.”}\],
‘role’: ‘model’}
- finish_reason: 1
- safety_ratings: \[{‘category’: 8, ‘probability’: 1, ‘blocked’: False},
{‘category’: 10, ‘probability’: 1, ‘blocked’: False}, {‘category’: 7,
‘probability’: 1, ‘blocked’: False}, {‘category’: 9, ‘probability’: 1,
‘blocked’: False}\]
- avg_logprobs: -0.3545633316040039
- token_count: 0
- grounding_attributions: \[\]
- prompt_token_count: 268
- candidates_token_count: 40
- total_token_count: 308
- cached_content_token_count: 0
</details>
Under the hood, Gaspard uploads the image using Gemini’s `File API` and
passes a reference to the model. Gemini API will automatically infer the
MIME type, and convert it appropriately. NOTE that the image is also
included in input tokens.
``` python
chat.use
```
In: 268; Out: 40; Total: 308
Alternatively, Gaspard supports creating a multi-stage chat with
separate image and text prompts. For instance, you can pass just the
image as the initial prompt (in which case the model will make some
general comments about what it sees, which can be VERY detailed
depending on the model and often begin with “Certainly!” for some
reason), and then follow up with questions in additional prompts:
``` python
chat = Chat(model)
chat(img_fn)
```
Certainly! Here’s a description of the image you sent:
**Overall Scene:**
The image is a close-up shot of a baby hippopotamus being gently petted
by a human hand. The scene is heartwarming and focuses on the
interaction between the adorable hippo calf and the human.
**Baby Hippo:**
- **Appearance:** The hippo is a very young calf with a plump, rounded
body. Its skin is a mottled gray color, with hints of pink especially
around its neck and cheeks. Its eyes are dark and soulful, giving it
an endearing expression. The calf has a small, broad snout and tiny,
rounded ears.
- **Pose:** The hippo is sitting with its short legs tucked beneath its
body. It’s looking directly at the camera with a slightly curious and
passive expression.
- **Texture:** The hippo’s skin appears smooth and moist, suggesting it
might be wet or freshly out of the water.
**Human Hand:**
- **Position:** The hand is placed gently under the hippo’s chin and
neck, supporting its head. The fingers are slightly curved and not
gripping tightly, demonstrating a caring touch.
- **Texture:** The skin of the hand appears soft and well-maintained.
**Background:**
- **Setting:** The background is out of focus, but it appears to be a
rocky, possibly aquatic, environment. The textures in the background
are muted and do not detract from the main subjects of the photo.
- **Date**: There’s a watermark saying “Thailand 9/2024”, indicating the
location and date of the image.
**Mood/Tone:**
- The image evokes a sense of gentleness and tenderness. The close-up
perspective and the gentle touch of the hand create a very intimate
and sweet scene.
- The calf’s innocent expression adds to the overall cuteness and warmth
of the image.
**Overall Impression:**
The image captures a beautiful moment of interaction between a human and
a very young, vulnerable animal. The photograph emphasizes the gentle
nature of the interaction and the sheer adorableness of the baby hippo,
making it a very touching and memorable picture.
Let me know if you would like a description from another perspective or
have any other questions about the image!
<details>
- content: {‘parts’: \[{‘text’: ’Certainly! Here's a description of the
image you sent:\*Overall Scene:\*\*image is a close-up shot of a baby
hippopotamus being gently petted by a human hand. The scene is
heartwarming and focuses on the interaction between the adorable hippo
calf and the human. \*Baby Hippo:****Appearance:** The hippo is a very
young calf with a plump, rounded body. Its skin is a mottled gray
color, with hints of pink especially around its neck and cheeks. Its
eyes are dark and soulful, giving it an endearing expression. The calf
has a small, broad snout and tiny, rounded ears.**Pose:** The hippo is
sitting with its short legs tucked beneath its body. It's looking
directly at the camera with a slightly curious and passive expression.
**Texture:\*\* The hippo's skin appears smooth and moist, suggesting
it might be wet or freshly out of the water.\*Human
Hand:****Position:** The hand is placed gently under the hippo's chin
and neck, supporting its head. The fingers are slightly curved and not
gripping tightly, demonstrating a caring touch.**Texture:\*\* The skin
of the hand appears soft and
well-maintained.\*Background:****Setting:** The background is out of
focus, but it appears to be a rocky, possibly aquatic, environment.
The textures in the background are muted and do not detract from the
main subjects of the photo.**Date\*\*: There's a watermark saying
“Thailand 9/2024”, indicating the location and date of the
image.\*Mood/Tone:\*\*The image evokes a sense of gentleness and
tenderness. The close-up perspective and the gentle touch of the hand
create a very intimate and sweet scene.The calf's innocent expression
adds to the overall cuteness and warmth of the image.\*Overall
Impression:\*\*image captures a beautiful moment of interaction
between a human and a very young, vulnerable animal. The photograph
emphasizes the gentle nature of the interaction and the sheer
adorableness of the baby hippo, making it a very touching and
memorable picture.me know if you would like a description from another
perspective or have any other questions about the image!’}\], ‘role’:
‘model’}
- finish_reason: 1
- safety_ratings: \[{‘category’: 8, ‘probability’: 1, ‘blocked’: False},
{‘category’: 10, ‘probability’: 1, ‘blocked’: False}, {‘category’: 7,
‘probability’: 1, ‘blocked’: False}, {‘category’: 9, ‘probability’: 1,
‘blocked’: False}\]
- avg_logprobs: -0.7025935932741327
- token_count: 0
- grounding_attributions: \[\]
- prompt_token_count: 260
- candidates_token_count: 472
- total_token_count: 732
- cached_content_token_count: 0
</details>
``` python
chat('What direction is the hippo facing?')
```
The hippo is facing directly towards the camera.
<details>
- content: {‘parts’: \[{‘text’: ‘The hippo is facing directly towards
the camera.’}\], ‘role’: ‘model’}
- finish_reason: 1
- safety_ratings: \[{‘category’: 8, ‘probability’: 1, ‘blocked’: False},
{‘category’: 10, ‘probability’: 1, ‘blocked’: False}, {‘category’: 7,
‘probability’: 1, ‘blocked’: False}, {‘category’: 9, ‘probability’: 1,
‘blocked’: False}\]
- avg_logprobs: -0.06370497941970825
- token_count: 0
- grounding_attributions: \[\]
- prompt_token_count: 742
- candidates_token_count: 10
- total_token_count: 752
- cached_content_token_count: 0
</details>
``` python
chat('What color is it?')
```
The hippo is a mottled gray color, with hints of pink especially around
its neck and cheeks.
<details>
- content: {‘parts’: \[{‘text’: ‘The hippo is a mottled gray color, with
hints of pink especially around its neck and cheeks.’}\], ‘role’:
‘model’}
- finish_reason: 1
- safety_ratings: \[{‘category’: 8, ‘probability’: 1, ‘blocked’: False},
{‘category’: 10, ‘probability’: 1, ‘blocked’: False}, {‘category’: 7,
‘probability’: 1, ‘blocked’: False}, {‘category’: 9, ‘probability’: 1,
‘blocked’: False}\]
- avg_logprobs: -0.08235452175140381
- token_count: 0
- grounding_attributions: \[\]
- prompt_token_count: 760
- candidates_token_count: 20
- total_token_count: 780
- cached_content_token_count: 0
</details>
Note that the image is passed in again for every input in the dialog,
via the chat history, so the number of input tokens increases quickly
with this kind of chat.
``` python
chat.use
```
In: 1762; Out: 502; Total: 2264
## Other Media
Beyond images, we can also pass in other kind of media to Gaspard, such
as audio file, video files, documents, etc.
For example, let’s try to send a pdf file to the model.
``` python
pdf_fn = Path('samples/attention_is_all_you_need.pdf')
```
``` python
chat = Chat(model)
```
``` python
chat([pdf_fn, "In brief, what are the main ideas of this paper?"])
```
Certainly! Here’s a breakdown of the main ideas presented in the paper
“Attention is All You Need”:
**Core Contribution: The Transformer Architecture**
- **Rejection of Recurrence and Convolution:** The paper proposes a
novel neural network architecture called the “Transformer” that moves
away from traditional recurrent neural networks (RNNs) and
convolutional neural networks (CNNs). These are the common
architectures for tasks involving sequence data.
- **Sole Reliance on Attention:** The Transformer relies solely on the
“attention” mechanism to capture relationships within input and output
sequences. This is the core novel idea and is in contrast to models
using attention *in addition to* RNNs or CNNs.
- **Parallelizable:** By removing recurrence, the Transformer is highly
parallelizable, which allows for faster training, especially on GPUs.
- **Attention-Based Encoder-Decoder:** The Transformer uses an
encoder-decoder architecture, like other sequence-to-sequence models,
but the encoder and decoder are based on self-attention mechanisms
rather than RNNs or CNNs.
**Key Components of the Transformer:**
- **Multi-Head Attention:** The Transformer uses multiple “attention
heads,” each learning different dependencies. This allows the model to
capture information from different representation sub-spaces.
- **Self-Attention:** Attention mechanism is applied on the same
sequence (e.g. input to input or output to output), to capture
relations within the sequence itself.
- **Encoder-Decoder Attention:** Attention mechanism is applied on two
sequences (encoder and decoder output) to align sequences between
the source and target.
- **Scaled Dot-Product Attention:** A specific form of attention that
uses dot products to calculate the attention weights with a scaling
factor to stabilize the training.
- **Position-wise Feed-Forward Networks:** Fully connected networks are
applied to each position separately after attention to add
non-linearity.
- **Positional Encoding:** Since the Transformer doesn’t have inherent
recurrence or convolutions, positional encodings are added to the
input embeddings to encode the sequence order.
**Experimental Results and Impact:**
- **Superior Translation Quality:** The paper demonstrates the
effectiveness of the Transformer on machine translation tasks
(English-to-German and English-to-French). The models achieve
state-of-the-art results with significant BLEU score improvements over
existing models including RNN and CNN based approaches.
- **Faster Training:** They show that the Transformer achieves those
state-of-the-art results with much less training time compared to
other architectures, showing the benefit of parallelization.
- **Generalization to Other Tasks:** The Transformer is also shown to
work well on English constituency parsing, highlighting its ability to
handle other sequence-based problems.
- **Interpretability:** Through attention visualizations, the paper also
suggests that the model learns to capture structural information in
the input, making it more interpretable than recurrent methods.
**In Essence:**
The paper argues for attention as a foundational building block for
sequence processing, dispensing with the need for recurrence and
convolutions. It introduces the Transformer, a model that leverages
attention mechanisms to achieve both better performance and faster
training, setting a new state-of-the-art baseline for many tasks such as
machine translation.
Let me know if you’d like any specific aspect clarified further!
<details>
- content: {‘parts’: \[{‘text’: ’Certainly! Here's a breakdown of the
main ideas presented in the paper “Attention is All You Need”:\*Core
Contribution: The Transformer Architecture****Rejection of Recurrence
and Convolution:** The paper proposes a novel neural network
architecture called the “Transformer” that moves away from traditional
recurrent neural networks (RNNs) and convolutional neural networks
(CNNs). These are the common architectures for tasks involving
sequence data.**Sole Reliance on Attention:** The Transformer relies
solely on the “attention” mechanism to capture relationships within
input and output sequences. This is the core novel idea and is in
contrast to models using attention *in addition to* RNNs or
CNNs.**Parallelizable:** By removing recurrence, the Transformer is
highly parallelizable, which allows for faster training, especially on
GPUs.**Attention-Based Encoder-Decoder:\*\* The Transformer uses an
encoder-decoder architecture, like other sequence-to-sequence models,
but the encoder and decoder are based on self-attention mechanisms
rather than RNNs or CNNs.\*Key Components of the
Transformer:****Multi-Head Attention:** The Transformer uses multiple
“attention heads,” each learning different dependencies. This allows
the model to capture information from different representation
sub-spaces.**Self-Attention:** Attention mechanism is applied on the
same sequence (e.g. input to input or output to output), to capture
relations within the sequence itself.**Encoder-Decoder Attention:**
Attention mechanism is applied on two sequences (encoder and decoder
output) to align sequences between the source and target.**Scaled
Dot-Product Attention:** A specific form of attention that uses dot
products to calculate the attention weights with a scaling factor to
stabilize the training.**Position-wise Feed-Forward Networks:** Fully
connected networks are applied to each position separately after
attention to add non-linearity.**Positional Encoding:\*\* Since the
Transformer doesn't have inherent recurrence or convolutions,
positional encodings are added to the input embeddings to encode the
sequence order.\*Experimental Results and Impact:****Superior
Translation Quality:** The paper demonstrates the effectiveness of the
Transformer on machine translation tasks (English-to-German and
English-to-French). The models achieve state-of-the-art results with
significant BLEU score improvements over existing models including RNN
and CNN based approaches.**Faster Training:** They show that the
Transformer achieves those state-of-the-art results with much less
training time compared to other architectures, showing the benefit of
parallelization.**Generalization to Other Tasks:** The Transformer is
also shown to work well on English constituency parsing, highlighting
its ability to handle other sequence-based
problems.**Interpretability:\*\* Through attention visualizations, the
paper also suggests that the model learns to capture structural
information in the input, making it more interpretable than recurrent
methods.\*In Essence:\*\*paper argues for attention as a foundational
building block for sequence processing, dispensing with the need for
recurrence and convolutions. It introduces the Transformer, a model
that leverages attention mechanisms to achieve both better performance
and faster training, setting a new state-of-the-art baseline for many
tasks such as machine translation.me know if you'd like any specific
aspect clarified further!’}\], ‘role’: ‘model’}
- finish_reason: 1
- safety_ratings: \[{‘category’: 8, ‘probability’: 1, ‘blocked’: False},
{‘category’: 10, ‘probability’: 1, ‘blocked’: False}, {‘category’: 7,
‘probability’: 1, ‘blocked’: False}, {‘category’: 9, ‘probability’: 1,
‘blocked’: False}\]
- avg_logprobs: -0.7809832342739763
- token_count: 0
- grounding_attributions: \[\]
- prompt_token_count: 14943
- candidates_token_count: 696
- total_token_count: 15639
- cached_content_token_count: 0
</details>
We can pass in audio files in the same way.
``` python
audio_fn = Path('samples/attention_is_all_you_need.mp3')
```
``` python
pr = "This is a podcast about the same paper. What important details from the paper are not in the podcast?"
```
``` python
chat([audio_fn, pr])
```
Okay, let’s analyze what details were missing from the podcast
discussion of “Attention is All You Need”. Here are some of the key
aspects not fully covered:
**1. Deeper Dive into the Math and Mechanics:**
- **Detailed Attention Formula:** The podcast mentions “scaled dot
product attention” but doesn’t delve into the actual mathematical
formula used to calculate the attention weights:
- `Attention(Q, K, V) = softmax((QK^T) / sqrt(d_k)) * V` (where
Q=query, K=key, V=value, and d_k is the dimension of the key)
- **Query, Key, Value:** While mentioned, the exact nature of how Query,
Key and Values are generated from input is never made explicit. How
are these generated by linear transformations is an essential aspect.
- **The role of the Mask:** The mask in decoder’s self-attention is also
not covered in depth. Masking is essential for the auto-regressive
nature of the output sequence.
- **Positional Encoding Equations:** The podcast mentioned positional
encoding but not the specific sine and cosine formulas and their
purpose which are key to how the model retains position information.
- `PE(pos, 2i) = sin(pos/10000^(2i/d_model))`
- `PE(pos, 2i+1) = cos(pos/10000^(2i/d_model))`
- **Detailed explanation of how d_model, d_k, d_v and head dimension
relate.** This is essential to understanding the parameter counts in
the model.
**2. Architectural Details and Hyperparameters:**
- **Number of Layers and Model Dimensions:** The paper uses 6 layers
both on the encoder and decoder side in their basic and large models.
The exact dimensionality of the model itself is also crucial to
understanding its capacity. The podcast only mentions that they are
stacked.
- **Feed Forward Layer Details:** The point-wise feed-forward network’s
dimensionality is essential for model performance. The podcast does
not go into depth about it and the dimensionality being used d_ff=2048
is key.
- **Dropout and Label Smoothing:** They are mentioned as a type of
regularization, but the specific rates of 0.1 for the base model are
never mentioned nor is the label smoothing rate of 0.1. These details
are important for reproducibility and performance.
- **Optimization Details:** There is also no mention of the Adam