cohere
mindnlp.transformers.models.cohere.configuration_cohere
¶
Cohere model configuration
mindnlp.transformers.models.cohere.configuration_cohere.CohereConfig
¶
Bases: PretrainedConfig
This is the configuration class to store the configuration of a [CohereModel
]. It is used to instantiate an Cohere
model according to the specified arguments, defining the model architecture.
Configuration objects inherit from [PretrainedConfig
] and can be used to control the model outputs. Read the
documentation from [PretrainedConfig
] for more information.
Instantiating a configuration with the defaults will yield a similar configuration to that of the
CohereForAI/c4ai-command-r-v01 model.
PARAMETER | DESCRIPTION |
---|---|
vocab_size |
Vocabulary size of the Cohere model. Defines the number of different tokens that can be represented by the
TYPE:
|
hidden_size |
Dimension of the hidden representations.
TYPE:
|
intermediate_size |
Dimension of the MLP representations.
TYPE:
|
logit_scale |
The scaling factor for the output logits.
TYPE:
|
num_hidden_layers |
Number of hidden layers in the Transformer decoder.
TYPE:
|
num_attention_heads |
Number of attention heads for each attention layer in the Transformer decoder.
TYPE:
|
num_key_value_heads |
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
TYPE:
|
hidden_act |
The non-linear activation function (function or string) in the decoder.
TYPE:
|
max_position_embeddings |
The maximum sequence length that this model might ever be used with.
TYPE:
|
initializer_range |
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
TYPE:
|
layer_norm_eps |
The epsilon used by the layer normalization.
TYPE:
|
use_cache |
Whether or not the model should return the last key/values attentions (not used by all models). Only
relevant if
TYPE:
|
pad_token_id |
Padding token id.
TYPE:
|
bos_token_id |
Beginning of stream token id.
TYPE:
|
eos_token_id |
End of stream token id.
TYPE:
|
tie_word_embeddings |
Whether to tie weight embeddings
TYPE:
|
rope_theta |
The base period of the RoPE embeddings.
TYPE:
|
attention_bias |
Whether to use a bias in the query, key, value and output projection layers during self-attention.
TYPE:
|
attention_dropout |
The dropout ratio for the attention probabilities.
TYPE:
|
use_qk_norm |
Whether to use query-key normalization in the attention
TYPE:
|
Example
>>> from transformers import CohereModel, CohereConfig
...
>>> # Initializing a Cohere model configuration
>>> configuration = CohereConfig()
...
>>> # Initializing a model from the Cohere configuration
>>> model = CohereModel(configuration) # doctest: +SKIP
...
>>> # Accessing the model configuration
>>> configuration = model.config # doctest: +SKIP
Source code in mindnlp/transformers/models/cohere/configuration_cohere.py
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 |
|
mindnlp.transformers.models.cohere.modeling_cohere
¶
MindSpore Cohere model.
mindnlp.transformers.models.cohere.modeling_cohere.CohereAttention
¶
Bases: Module
Multi-headed attention from 'Attention Is All You Need' paper
Source code in mindnlp/transformers/models/cohere/modeling_cohere.py
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 |
|
mindnlp.transformers.models.cohere.modeling_cohere.CohereDecoderLayer
¶
Bases: Module
Source code in mindnlp/transformers/models/cohere/modeling_cohere.py
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 |
|
mindnlp.transformers.models.cohere.modeling_cohere.CohereDecoderLayer.forward(hidden_states, attention_mask=None, position_ids=None, past_key_value=None, output_attentions=False, use_cache=False, cache_position=None)
¶
PARAMETER | DESCRIPTION |
---|---|
hidden_states |
input to the layer of shape
TYPE:
|
attention_mask |
attention mask of size
TYPE:
|
output_attentions |
Whether or not to return the attentions tensors of all attention layers. See
TYPE:
|
use_cache |
If set to
TYPE:
|
past_key_value |
cached past key and value projection states
TYPE:
|
Source code in mindnlp/transformers/models/cohere/modeling_cohere.py
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 |
|
mindnlp.transformers.models.cohere.modeling_cohere.CohereForCausalLM
¶
Bases: CoherePreTrainedModel
Source code in mindnlp/transformers/models/cohere/modeling_cohere.py
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 |
|
mindnlp.transformers.models.cohere.modeling_cohere.CohereForCausalLM.forward(input_ids=None, attention_mask=None, position_ids=None, past_key_values=None, inputs_embeds=None, labels=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None, cache_position=None)
¶
PARAMETER | DESCRIPTION |
---|---|
labels |
Labels for computing the masked language modeling loss. Indices should either be in
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Union[Tuple, CausalLMOutputWithPast]
|
|
Example
>>> from transformers import AutoTokenizer, CohereForCausalLM
...
>>> model = CohereForCausalLM.from_pretrained("CohereForAI/c4ai-command-r-v01")
>>> tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01")
...
>>> prompt = "Hey, are you conscious? Can you talk to me?"
>>> inputs = tokenizer(prompt, return_tensors="pt")
...
>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
Source code in mindnlp/transformers/models/cohere/modeling_cohere.py
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 |
|
mindnlp.transformers.models.cohere.modeling_cohere.CohereLayerNorm
¶
Bases: Module
Source code in mindnlp/transformers/models/cohere/modeling_cohere.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
|
mindnlp.transformers.models.cohere.modeling_cohere.CohereLayerNorm.__init__(hidden_size=None, eps=1e-05, bias=False)
¶
The hidden size can be a tuple or an int. The tuple is used for QKNorm to normalize across head_dim
Source code in mindnlp/transformers/models/cohere/modeling_cohere.py
64 65 66 67 68 |
|
mindnlp.transformers.models.cohere.modeling_cohere.CohereModel
¶
Bases: CoherePreTrainedModel
Transformer decoder consisting of config.num_hidden_layers layers. Each layer is a [CohereDecoderLayer
]
PARAMETER | DESCRIPTION |
---|---|
config |
CohereConfig
TYPE:
|
Source code in mindnlp/transformers/models/cohere/modeling_cohere.py
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 |
|
mindnlp.transformers.models.cohere.modeling_cohere.CoherePreTrainedModel
¶
Bases: PreTrainedModel
Source code in mindnlp/transformers/models/cohere/modeling_cohere.py
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 |
|
mindnlp.transformers.models.cohere.modeling_cohere.apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1)
¶
Applies Rotary Position Embedding to the query and key tensors.
PARAMETER | DESCRIPTION |
---|---|
q |
The query tensor.
TYPE:
|
k |
The key tensor.
TYPE:
|
cos |
The cosine part of the rotary embedding.
TYPE:
|
sin |
The sine part of the rotary embedding.
TYPE:
|
position_ids |
Deprecated and unused.
TYPE:
|
unsqueeze_dim |
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
|
Source code in mindnlp/transformers/models/cohere/modeling_cohere.py
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 |
|
mindnlp.transformers.models.cohere.modeling_cohere.repeat_kv(hidden_states, n_rep)
¶
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
Source code in mindnlp/transformers/models/cohere/modeling_cohere.py
163 164 165 166 167 168 169 170 171 172 |
|
mindnlp.transformers.models.cohere.tokenization_cohere_fast
¶
cohere tokenization
mindnlp.transformers.models.cohere.tokenization_cohere_fast.CohereTokenizerFast
¶
Bases: PreTrainedTokenizerFast
Construct a Cohere tokenizer. Based on byte-level Byte-Pair-Encoding.
This uses notably ByteFallback and NFC normalization.
Example
>>> from transformers import AutoTokenizer
...
>>> tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01")
>>> tokenizer.encode("Hello this is a test")
[5, 28339, 2075, 1801, 1671, 3282]
If you want to change the bos_token
or the eos_token
, make sure to specify them when initializing the model, or
call tokenizer.update_post_processor()
to make sure that the post-processing is correctly done (otherwise the
values of the first token and final token of an encoded sequence will not be correct). For more details, checkout
[post-processors] (https://huggingface.co/docs/tokenizers/api/post-processors) documentation.
You can get around that behavior by passing add_prefix_space=True
when instantiating this tokenizer, but since
the model was not pretrained this way, it might yield a decrease in performance.
When used with is_split_into_words=True
, this tokenizer needs to be instantiated with add_prefix_space=True
.
This tokenizer inherits from [PreTrainedTokenizerFast
] which contains most of the main methods. Users should
refer to this superclass for more information regarding those methods.
PARAMETER | DESCRIPTION |
---|---|
vocab_file |
Path to the vocabulary file.
TYPE:
|
merges_file |
Path to the merges file.
TYPE:
|
tokenizer_file |
tokenizers file (generally has a .json extension) that contains everything needed to load the tokenizer.
TYPE:
|
clean_up_tokenization_spaces |
Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like extra spaces.
TYPE:
|
unk_token |
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead.
TYPE:
|
bos_token |
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
TYPE:
|
eos_token |
The end of sequence token.
TYPE:
|
add_bos_token |
Whether or not to add an
TYPE:
|
add_eos_token |
Whether or not to add an
TYPE:
|
use_default_system_prompt |
Whether or not the default system prompt for Cohere tokenizer should be used.
TYPE:
|
add_prefix_space |
Whether or not the tokenizer should automatically add a prefix space
TYPE:
|
Source code in mindnlp/transformers/models/cohere/tokenization_cohere_fast.py
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 |
|
mindnlp.transformers.models.cohere.tokenization_cohere_fast.CohereTokenizerFast.default_chat_template
property
¶
Cohere Tokenizer uses <|START_OF_TURN_TOKEN|> and <|END_OF_TURN_TOKEN|> to indicate each turn in a chat. Additioanlly, to indicate the source of the message, <|USER_TOKEN|>, <|CHATBOT_TOKEN|> and <|SYSTEM_TOKEN|> for user, assitant and system messages respectively.
The output should look something like:
<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>{{ preamble }}<|END_OF_TURN_TOKEN|><BOS_TOKEN><|START_OF_TURN_TOKEN|>
<|USER_TOKEN|>{{ How are you? }}<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>
{{ I am doing well! }}<|END_OF_TURN_TOKEN|>
Use add_generation_prompt to add a prompt for the model to generate a response:
Example:
>>> from transformers import AutoTokenizer
>>> tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01")
>>> messages = [{"role": "user", "content": "Hello, how are you?"}]
>>> tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
'<BOS_TOKEN><|START_OF_TURN_TOKEN|><|USER_TOKEN|>Hello, how are you?<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>'
mindnlp.transformers.models.cohere.tokenization_cohere_fast.CohereTokenizerFast.apply_grounded_generation_template(conversation, documents, citation_mode='accurate', **kwargs)
¶
Create a Command-R grounded generation (aka RAG) prompt.
Once rendered, the prompt instructs the model to generate a response with citations in, based on supplied documents.
Conceptually, this works in the same way as apply_chat_format
, but takes additional documents
and parameter citation_mode
parameters.
Converts a Conversation object or a list of dictionaries with "role"
and "content"
keys and a list of
documents for the model to ground its response on into a prompt string, or a list of token ids.
This method will use the tokenizer's grounded_generation_template
template specified at the class level.
You can override the default template using the grounded_generation_template
kwarg but the quality of your results may decrease.
PARAMETER | DESCRIPTION |
---|---|
conversation |
A Conversation object or list of dicts with "role" and "content" keys, representing the chat history so far.
TYPE:
|
documents |
A list of dicts, representing documents or tool outputs to ground your
generation on. A document is a semistructured dict, wiht a string to string mapping. Common fields are
TYPE:
|
citation_mode |
either "accurate" (prompt the model to generate an answer first, then rewrite it with citation spans in) or "fast", where the prompt instructs the model to generate an answer with citations in directly. The former has higher quality citations, the latter requires fewer tokens to be generated.
TYPE:
|
add_generation_prompt |
Whether to end the prompt with the token(s) that indicate the start of an assistant message. This is useful when you want to generate a response from the model. Note that this argument will be passed to the chat template, and so it must be supported in the template for this argument to have any effect.
TYPE:
|
tokenize |
Whether to tokenize the output. If
TYPE:
|
padding |
Whether to pad sequences to the maximum length. Has no effect if tokenize is
TYPE:
|
truncation |
Whether to truncate sequences at the maximum length. Has no effect if tokenize is
TYPE:
|
max_length |
Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is
TYPE:
|
return_tensors |
If set, will return tensors of a particular framework. Has no effect if tokenize is
TYPE:
|
return_dict |
Whether to return a dictionary with named outputs. Has no effect if tokenize is
TYPE:
|
**tokenizer_kwargs |
Additional kwargs to pass to the tokenizer.
|
RETURNS | DESCRIPTION |
---|---|
Union[str, List[int]]
|
Conditional return:
|
Example
>>> tokenizer = CohereTokenizerFast.from_pretrained('CohereForAI/c4ai-command-r-v01')
...
>>> # define documents:
>>> documents = [
{ "title": "Tall penguins", "text": "Emperor penguins are the tallest." },
{ "title": "Penguin habitats", "text": "Emperor penguins only live in Antarctica."}
]
>>> # define a conversation:
>>> conversation = [
{"role": "user", "content": "Whats the biggest penguin in the world?"}
]
>>> # render the prompt, ready for user to inspect, or for input into the model:
>>> grounded_generation_prompt = tokenizer.apply_grounded_generation_template(conversation, documents=documents, tokenize=False, add_generation_prompt=True)
>>> print(grounded_generation_prompt)
<BOS_TOKEN><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|># Safety Preamble
The instructions in this section override those in the task description and style guide sections. Don't answer questions that are harmful or immoral.
## Basic Rules
You are a powerful conversational AI trained by Cohere to help people. You are augmented by a number of tools, and your job is to use and consume the output of these tools to best help the user. You will see a conversation history between yourself and a user, ending with an utterance from the user. You will then see a specific instruction instructing you what kind of response to generate. When you answer the user's requests, you cite your sources in your answers, according to those instructions.
# User Preamble
## Task and Context
You help people answer their questions and other requests interactively. You will be asked a very wide array of requests on all kinds of topics. You will be equipped with a wide range of search engines or similar tools to help you, which you use to research your answer. You should focus on serving the user's needs as best you can, which will be wide-ranging.
## Style Guide
Unless the user asks for a different style of answer, you should answer in full sentences, using proper grammar and spelling.<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|USER_TOKEN|>Whats the biggest penguin in the world?<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|><results>
Document: 0
title: Tall penguins
text: Emperor penguins are the tallest.
Document: 1
title: Penguin habitats
text: Emperor penguins only live in Antarctica.
</results><|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>Carefully perform the following instructions, in order, starting each with a new line.
Firstly, Decide which of the retrieved documents are relevant to the user's last input by writing 'Relevant Documents:' followed by comma-separated list of document numbers. If none are relevant, you should instead write 'None'.
Secondly, Decide which of the retrieved documents contain facts that should be cited in a good answer to the user's last input by writing 'Cited Documents:' followed a comma-separated list of document numbers. If you dont want to cite any of them, you should instead write 'None'.
Thirdly, Write 'Answer:' followed by a response to the user's last input in high quality natural english. Use the retrieved documents to help you. Do not insert any citations or grounding markup.
Finally, Write 'Grounded answer:' followed by a response to the user's last input in high quality natural english. Use the symbols <co: doc> and </co: doc> to indicate when a fact comes from a document in the search result, e.g <co: 0>my fact</co: 0> for a fact from document 0.<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>'''
>>> inputs = tokenizer.encode(prompt, add_special_tokens=False, return_tensors='pt')
>>> outputs = model.generate(inputs, max_new_tokens=128)
>>> print(tokenizer.decode(outputs[0]))
Relevant Documents: 0,1
Cited Documents: 0,1
Answer: The Emperor Penguin is the tallest or biggest penguin in the world. It is a bird that lives only in Antarctica and grows to a height of around 122 centimetres.
Grounded answer: The <co: 0>Emperor Penguin</co: 0> is the <co: 0>tallest</co: 0> or biggest penguin in the world. It is a bird that <co: 1>lives only in Antarctica</co: 1> and <co: 0>grows to a height of around 122 centimetres.</co: 0>
Source code in mindnlp/transformers/models/cohere/tokenization_cohere_fast.py
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 |
|
mindnlp.transformers.models.cohere.tokenization_cohere_fast.CohereTokenizerFast.apply_tool_use_template(conversation, tools, **kwargs)
¶
Create a Command-R tool-use prompt.
Once rendered, the prompt instructs the model to generate a list of actions to perform on a set of user supplied tools to help carry out the user's requests.
Conceptually, this works in the same way as apply_chat_format
, but takes an additional tools
parameter.
Converts a Conversation object or a list of dictionaries with "role"
and "content"
keys and a list of available
tools for the model to use into a prompt string, or a list of token ids.
This method will use the tokenizer's default_tool_use_template
template specified at the class level.
You can override the default template using the tool_use_template
kwarg but the quality of your results may decrease.
PARAMETER | DESCRIPTION |
---|---|
conversation |
A Conversation object or list of dicts with "role" and "content" keys, representing the chat history so far.
TYPE:
|
tools |
a list of tools to render into the prompt for the model to choose from. See an example at the bottom of the docstring. The format should be:
TYPE:
|
add_generation_prompt |
Whether to end the prompt with the token(s) that indicate the start of an assistant message. This is useful when you want to generate a response from the model. Note that this argument will be passed to the chat template, and so it must be supported in the template for this argument to have any effect.
TYPE:
|
tokenize |
Whether to tokenize the output. If
TYPE:
|
padding |
Whether to pad sequences to the maximum length. Has no effect if tokenize is
TYPE:
|
truncation |
Whether to truncate sequences at the maximum length. Has no effect if tokenize is
TYPE:
|
max_length |
Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is
TYPE:
|
return_tensors |
If set, will return tensors of a particular framework. Has no effect if tokenize is
TYPE:
|
return_dict |
Whether to return a dictionary with named outputs. Has no effect if tokenize is
TYPE:
|
**tokenizer_kwargs |
Additional kwargs to pass to the tokenizer.
|
RETURNS | DESCRIPTION |
---|---|
Union[str, List[int]]
|
Conditional return:
|
Example
>>> tokenizer = CohereTokenizerFast.from_pretrained("CohereForAI/c4ai-command-r-v01")
>>> tools = [
... {
... "name": "internet_search",
... "description": "Returns a list of relevant document snippets for a textual query retrieved from the internet",
... "parameter_definitions": {
... "query": {
... "description": "Query to search the internet with",
... "type": "str",
... "required": True
... }
... }
... },
... {
... "name': "directly_answer",
... "description": "Calls a standard (un-augmented) AI chatbot to generate a response given the conversation history",
... "parameter_definitions": {}
... }
... ]
>>> conversation = [
... {"role": "user", "content": "Whats the biggest penguin in the world?"}
... ]
>>> # render the prompt, ready for user to inspect, or for input into the model:
>>> prompt = tokenizer.apply_tool_use_template(conversation, tools=tools, tokenize=False, add_generation_prompt=True)
>>> print(prompt)
<BOS_TOKEN><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|># Safety Preamble
The instructions in this section override those in the task description and style guide sections. Don't answer questions that are harmful or immoral.
# System Preamble
## Basic Rules
You are a powerful conversational AI trained by Cohere to help people. You are augmented by a number of tools, and your job is to use and consume the output of these tools to best help the user. You will see a conversation history between yourself and a user, ending with an utterance from the user. You will then see a specific instruction instructing you what kind of response to generate. When you answer the user's requests, you cite your sources in your answers, according to those instructions.
# User Preamble
## Task and Context
You help people answer their questions and other requests interactively. You will be asked a very wide array of requests on all kinds of topics. You will be equipped with a wide range of search engines or similar tools to help you, which you use to research your answer. You should focus on serving the user's needs as best you can, which will be wide-ranging.
## Style Guide
Unless the user asks for a different style of answer, you should answer in full sentences, using proper grammar and spelling.
## Available Tools
Here is a list of tools that you have available to you:
\`\`\`python
def internet_search(query: str) -> List[Dict]:
"""Returns a list of relevant document snippets for a textual query retrieved from the internet
Args:
query (str): Query to search the internet with
"""
pass
\`\`\`
\`\`\`python
def directly_answer() -> List[Dict]:
"""Calls a standard (un-augmented) AI chatbot to generate a response given the conversation history
"""
pass
\`\`\`<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|USER_TOKEN|>Whats the biggest penguin in the world?<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>Write 'Action:' followed by a json-formatted list of actions that you want to perform in order to produce a good response to the user's last input. You can use any of the supplied tools any number of times, but you should aim to execute the minimum number of necessary actions for the input. You should use the `directly-answer` tool if calling the other tools is unnecessary. The list of actions you want to call should be formatted as a list of json objects, for example:
\`\`\`json
[
{
"tool_name": title of the tool in the specification,
"parameters": a dict of parameters to input into the tool as they are defined in the specs, or {} if it takes no parameters
}
]\`\`\`<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>
>>> inputs = tokenizer.encode(prompt, add_special_tokens=False, return_tensors='pt')
>>> outputs = model.generate(inputs, max_new_tokens=128)
>>> print(tokenizer.decode(outputs[0]))
Action: json
[
{
"tool_name": "internet_search",
"parameters": {
"query": "biggest penguin in the world"
}
}
]
Source code in mindnlp/transformers/models/cohere/tokenization_cohere_fast.py
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 |
|
mindnlp.transformers.models.cohere.tokenization_cohere_fast.CohereTokenizerFast.update_post_processor()
¶
Updates the underlying post processor with the current bos_token
and eos_token
.
Source code in mindnlp/transformers/models/cohere/tokenization_cohere_fast.py
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 |
|