source stringclasses 470
values | url stringlengths 49 167 | file_type stringclasses 1
value | chunk stringlengths 1 512 | chunk_id stringlengths 5 9 |
|---|---|---|---|---|
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/language_modeling.md | https://huggingface.co/docs/transformers/en/tasks/language_modeling/#inference | .md | Great, now that you've finetuned a model, you can use it for inference!
Come up with a prompt you'd like to generate text from:
```py
>>> prompt = "Somatic hypermutation allows the immune system to"
```
The simplest way to try out your finetuned model for inference is to use it in a [`pipeline`]. Instantiate a `p... | 99_5_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/language_modeling.md | https://huggingface.co/docs/transformers/en/tasks/language_modeling/#inference | .md | >>> generator = pipeline("text-generation", model="username/my_awesome_eli5_clm-model")
>>> generator(prompt)
[{'generated_text': "Somatic hypermutation allows the immune system to be able to effectively reverse the damage caused by an infection.\n\n\nThe damage caused by an infection is caused by the immune system's a... | 99_5_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/language_modeling.md | https://huggingface.co/docs/transformers/en/tasks/language_modeling/#inference | .md | ```
<frameworkcontent>
<pt>
Tokenize the text and return the `input_ids` as PyTorch tensors:
```py
>>> from transformers import AutoTokenizer | 99_5_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/language_modeling.md | https://huggingface.co/docs/transformers/en/tasks/language_modeling/#inference | .md | >>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_eli5_clm-model")
>>> inputs = tokenizer(prompt, return_tensors="pt").input_ids
```
Use the [`~generation.GenerationMixin.generate`] method to generate text.
For more details about the different text generation strategies and parameters for controlling... | 99_5_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/language_modeling.md | https://huggingface.co/docs/transformers/en/tasks/language_modeling/#inference | .md | >>> model = AutoModelForCausalLM.from_pretrained("username/my_awesome_eli5_clm-model")
>>> outputs = model.generate(inputs, max_new_tokens=100, do_sample=True, top_k=50, top_p=0.95)
```
Decode the generated token ids back into text:
```py
>>> tokenizer.batch_decode(outputs, skip_special_tokens=True) | 99_5_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/language_modeling.md | https://huggingface.co/docs/transformers/en/tasks/language_modeling/#inference | .md | ["Somatic hypermutation allows the immune system to react to drugs with the ability to adapt to a different environmental situation. In other words, a system of 'hypermutation' can help the immune system to adapt to a different environmental situation or in some cases even a single life. In contrast, researchers at the... | 99_5_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/language_modeling.md | https://huggingface.co/docs/transformers/en/tasks/language_modeling/#inference | .md | is much stronger in mice than in humans but can be found in humans, and that it's not completely unknown to the immune system. A study on how the immune system"] | 99_5_6 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/language_modeling.md | https://huggingface.co/docs/transformers/en/tasks/language_modeling/#inference | .md | ```
</pt>
<tf>
Tokenize the text and return the `input_ids` as TensorFlow tensors:
```py
>>> from transformers import AutoTokenizer | 99_5_7 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/language_modeling.md | https://huggingface.co/docs/transformers/en/tasks/language_modeling/#inference | .md | >>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_eli5_clm-model")
>>> inputs = tokenizer(prompt, return_tensors="tf").input_ids
```
Use the [`~transformers.generation_tf_utils.TFGenerationMixin.generate`] method to create the summarization. For more details about the different text generation strate... | 99_5_8 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/language_modeling.md | https://huggingface.co/docs/transformers/en/tasks/language_modeling/#inference | .md | >>> model = TFAutoModelForCausalLM.from_pretrained("username/my_awesome_eli5_clm-model")
>>> outputs = model.generate(input_ids=inputs, max_new_tokens=100, do_sample=True, top_k=50, top_p=0.95)
```
Decode the generated token ids back into text:
```py
>>> tokenizer.batch_decode(outputs, skip_special_tokens=True) | 99_5_9 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/language_modeling.md | https://huggingface.co/docs/transformers/en/tasks/language_modeling/#inference | .md | ['Somatic hypermutation allows the immune system to detect the presence of other viruses as they become more prevalent. Therefore, researchers have identified a high proportion of human viruses. The proportion of virus-associated viruses in our study increases with age. Therefore, we propose a simple algorithm to detec... | 99_5_10 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/language_modeling.md | https://huggingface.co/docs/transformers/en/tasks/language_modeling/#inference | .md | improved immunity. A first study based on this algorithm, which will be published in Science on Friday, aims to show that this finding could translate into the development of a better vaccine that is more effective for'] | 99_5_11 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/language_modeling.md | https://huggingface.co/docs/transformers/en/tasks/language_modeling/#inference | .md | ```
</tf>
</frameworkcontent> | 99_5_12 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/ | .md | <!--Copyright 2023 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... | 100_0_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/ | .md | an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
rendered ... | 100_0_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#llm-prompting-guide | .md | [[open-in-colab]]
Large Language Models such as Falcon, LLaMA, etc. are pretrained transformer models initially trained to predict the
next token given some input text. They typically have billions of parameters and have been trained on trillions of
tokens for an extended period of time. As a result, these models bec... | 100_1_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#llm-prompting-guide | .md | them to solve multiple NLP tasks out of the box by instructing the models with natural language prompts.
Designing such prompts to ensure the optimal output is often called "prompt engineering". Prompt engineering is an
iterative process that requires a fair amount of experimentation. Natural languages are much more ... | 100_1_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#llm-prompting-guide | .md | than programming languages, however, they can also introduce some ambiguity. At the same time, prompts in natural language
are quite sensitive to changes. Even minor modifications in prompts can lead to wildly different outputs.
While there is no exact recipe for creating prompts to match all cases, researchers have ... | 100_1_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#llm-prompting-guide | .md | practices that help to achieve optimal results more consistently.
This guide covers the prompt engineering best practices to help you craft better LLM prompts and solve various NLP tasks.
You'll learn:
- [Basics of prompting](#basics-of-prompting)
- [Best practices of LLM prompting](#best-practices-of-llm-prompting... | 100_1_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#llm-prompting-guide | .md | - [When to fine-tune instead of prompting](#prompting-vs-fine-tuning)
<Tip>
Prompt engineering is only a part of the LLM output optimization process. Another essential component is choosing the
optimal text generation strategy. You can customize how your LLM selects each of the subsequent tokens when generating
the... | 100_1_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#llm-prompting-guide | .md | the text without modifying any of the trainable parameters. By tweaking the text generation parameters, you can reduce
repetition in the generated text and make it more coherent and human-sounding.
Text generation strategies and parameters are out of scope for this guide, but you can learn more about these topics in
th... | 100_1_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#types-of-models | .md | The majority of modern LLMs are decoder-only transformers. Some examples include: [LLaMA](../model_doc/llama),
[Llama2](../model_doc/llama2), [Falcon](../model_doc/falcon), [GPT2](../model_doc/gpt2). However, you may encounter
encoder-decoder transformer LLMs as well, for instance, [Flan-T5](../model_doc/flan-t5) and [... | 100_2_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#types-of-models | .md | Encoder-decoder-style models are typically used in generative tasks where the output **heavily** relies on the input, for
example, in translation and summarization. The decoder-only models are used for all other types of generative tasks.
When using a pipeline to generate text with an LLM, it's important to know what... | 100_2_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#types-of-models | .md | they use different pipelines.
Run inference with decoder-only models with the `text-generation` pipeline:
```python
>>> from transformers import pipeline
>>> import torch | 100_2_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#types-of-models | .md | >>> torch.manual_seed(0) # doctest: +IGNORE_RESULT
>>> generator = pipeline('text-generation', model = 'openai-community/gpt2')
>>> prompt = "Hello, I'm a language model" | 100_2_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#types-of-models | .md | >>> generator(prompt, max_length = 30)
[{'generated_text': "Hello, I'm a language model programmer so you can use some of my stuff. But you also need some sort of a C program to run."}]
```
To run inference with an encoder-decoder, use the `text2text-generation` pipeline:
```python
>>> text2text_generator = pipelin... | 100_2_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#types-of-models | .md | >>> text2text_generator(prompt)
[{'generated_text': 'Je suis très heureuse de vous rencontrer.'}]
``` | 100_2_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#base-vs-instructchat-models | .md | Most of the recent LLM checkpoints available on 🤗 Hub come in two versions: base and instruct (or chat). For example,
[`tiiuae/falcon-7b`](https://huggingface.co/tiiuae/falcon-7b) and [`tiiuae/falcon-7b-instruct`](https://huggingface.co/tiiuae/falcon-7b-instruct).
Base models are excellent at completing the text whe... | 100_3_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#base-vs-instructchat-models | .md | where they need to follow instructions, or for conversational use. This is where the instruct (chat) versions come in.
These checkpoints are the result of further fine-tuning of the pre-trained base versions on instructions and conversational data.
This additional fine-tuning makes them a better choice for many NLP tas... | 100_3_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#nlp-tasks | .md | First, let's set up the environment:
```bash
pip install -q transformers accelerate
```
Next, let's load the model with the appropriate pipeline (`"text-generation"`):
```python
>>> from transformers import pipeline, AutoTokenizer
>>> import torch
>>> torch.manual_seed(0) # doctest: +IGNORE_RESULT
>>> model = "t... | 100_4_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#nlp-tasks | .md | >>> tokenizer = AutoTokenizer.from_pretrained(model)
>>> pipe = pipeline(
... "text-generation",
... model=model,
... tokenizer=tokenizer,
... torch_dtype=torch.bfloat16,
... device_map="auto",
... )
```
<Tip>
Note that Falcon models were trained using the `bfloat16` datatype, so we recommend yo... | 100_4_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#nlp-tasks | .md | version of CUDA and works best on modern cards.
</Tip>
Now that we have the model loaded via the pipeline, let's explore how you can use prompts to solve NLP tasks. | 100_4_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#text-classification | .md | One of the most common forms of text classification is sentiment analysis, which assigns a label like "positive", "negative",
or "neutral" to a sequence of text. Let's write a prompt that instructs the model to classify a given text (a movie review).
We'll start by giving the instruction, and then specifying the text t... | 100_5_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#text-classification | .md | also adding the beginning of the response - `"Sentiment: "`:
```python
>>> torch.manual_seed(0) # doctest: +IGNORE_RESULT
>>> prompt = """Classify the text into neutral, negative or positive.
... Text: This movie is definitely one of my favorite movies of its kind. The interaction between respectable and morally stro... | 100_5_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#text-classification | .md | >>> sequences = pipe(
... prompt,
... max_new_tokens=10,
... ) | 100_5_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#text-classification | .md | >>> for seq in sequences:
... print(f"Result: {seq['generated_text']}")
Result: Classify the text into neutral, negative or positive.
Text: This movie is definitely one of my favorite movies of its kind. The interaction between respectable and morally strong characters is an ode to chivalry and the honor code among... | 100_5_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#text-classification | .md | <Tip>
You may notice that in addition to the prompt, we pass a `max_new_tokens` parameter. It controls the number of tokens the
model shall generate, and it is one of the many text generation parameters that you can learn about
in [Text generation strategies](../generation_strategies) guide.
</Tip> | 100_5_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#named-entity-recognition | .md | Named Entity Recognition (NER) is a task of finding named entities in a piece of text, such as a person, location, or organization.
Let's modify the instructions in the prompt to make the LLM perform this task. Here, let's also set `return_full_text = False`
so that output doesn't contain the prompt:
```python
>>> to... | 100_6_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#named-entity-recognition | .md | ```python
>>> torch.manual_seed(1) # doctest: +IGNORE_RESULT
>>> prompt = """Return a list of named entities in the text.
... Text: The Golden State Warriors are an American professional basketball team based in San Francisco.
... Named entities:
... """ | 100_6_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#named-entity-recognition | .md | >>> sequences = pipe(
... prompt,
... max_new_tokens=15,
... return_full_text = False,
... )
>>> for seq in sequences:
... print(f"{seq['generated_text']}")
- Golden State Warriors
- San Francisco
```
As you can see, the model correctly identified two named entities from the given text. | 100_6_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#translation | .md | Another task LLMs can perform is translation. You can choose to use encoder-decoder models for this task, however, here,
for the simplicity of the examples, we'll keep using Falcon-7b-instruct, which does a decent job. Once again, here's how
you can write a basic prompt to instruct a model to translate a piece of text ... | 100_7_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#translation | .md | ```python
>>> torch.manual_seed(2) # doctest: +IGNORE_RESULT
>>> prompt = """Translate the English text to Italian.
... Text: Sometimes, I've believed as many as six impossible things before breakfast.
... Translation:
... """ | 100_7_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#translation | .md | >>> sequences = pipe(
... prompt,
... max_new_tokens=20,
... do_sample=True,
... top_k=10,
... return_full_text = False,
... )
>>> for seq in sequences:
... print(f"{seq['generated_text']}")
A volte, ho creduto a sei impossibili cose prima di colazione.
```
Here we've added a `do_sample=True`... | 100_7_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#text-summarization | .md | Similar to the translation, text summarization is another generative task where the output **heavily** relies on the input,
and encoder-decoder models can be a better choice. However, decoder-style models can be used for this task as well.
Previously, we have placed the instructions at the very beginning of the prompt.... | 100_8_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#text-summarization | .md | ```python
>>> torch.manual_seed(3) # doctest: +IGNORE_RESULT | 100_8_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#text-summarization | .md | >>> prompt = """Permaculture is a design process mimicking the diversity, functionality and resilience of natural ecosystems. The principles and practices are drawn from traditional ecological knowledge of indigenous cultures combined with modern scientific understanding and technological innovations. Permaculture desi... | 100_8_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#text-summarization | .md | develop innovative, creative and effective strategies for meeting basic needs while preparing for and mitigating the projected impacts of climate change. | 100_8_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#text-summarization | .md | ... Write a summary of the above text.
... Summary:
... """ | 100_8_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#text-summarization | .md | >>> sequences = pipe(
... prompt,
... max_new_tokens=30,
... do_sample=True,
... top_k=10,
... return_full_text = False,
... )
>>> for seq in sequences:
... print(f"{seq['generated_text']}")
Permaculture is an ecological design mimicking natural ecosystems to meet basic needs and prepare for cl... | 100_8_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#question-answering | .md | For question answering task we can structure the prompt into the following logical components: instructions, context, question, and
the leading word or phrase (`"Answer:"`) to nudge the model to start generating the answer:
```python
>>> torch.manual_seed(4) # doctest: +IGNORE_RESULT
>>> prompt = """Answer the questi... | 100_9_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#question-answering | .md | ... Context: Gazpacho is a cold soup and drink made of raw, blended vegetables. Most gazpacho includes stale bread, tomato, cucumbers, onion, bell peppers, garlic, olive oil, wine vinegar, water, and salt. Northern recipes often include cumin and/or pimentón (smoked sweet paprika). Traditionally, gazpacho was made by p... | 100_9_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#question-answering | .md | method is still sometimes used as it helps keep the gazpacho cool and avoids the foam and silky consistency of smoothie versions made in blenders or food processors. | 100_9_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#question-answering | .md | ... Question: What modern tool is used to make gazpacho?
... Answer:
... """ | 100_9_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#question-answering | .md | >>> sequences = pipe(
... prompt,
... max_new_tokens=10,
... do_sample=True,
... top_k=10,
... return_full_text = False,
... )
>>> for seq in sequences:
... print(f"Result: {seq['generated_text']}")
Result: Modern tools often used to make gazpacho include
``` | 100_9_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#reasoning | .md | Reasoning is one of the most difficult tasks for LLMs, and achieving good results often requires applying advanced prompting techniques, like
[Chain-of-thought](#chain-of-thought).
Let's try if we can make a model reason about a simple arithmetics task with a basic prompt:
```python
>>> torch.manual_seed(5) # docte... | 100_10_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#reasoning | .md | >>> sequences = pipe(
... prompt,
... max_new_tokens=30,
... do_sample=True,
... top_k=10,
... return_full_text = False,
... ) | 100_10_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#reasoning | .md | >>> for seq in sequences:
... print(f"Result: {seq['generated_text']}")
Result:
There are a total of 5 groups, so there are 5 x 4=20 students in the class.
```
Correct! Let's increase the complexity a little and see if we can still get away with a basic prompt:
```python
>>> torch.manual_seed(6) # doctest: +IGN... | 100_10_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#reasoning | .md | >>> sequences = pipe(
... prompt,
... max_new_tokens=10,
... do_sample=True,
... top_k=10,
... return_full_text = False,
... ) | 100_10_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#reasoning | .md | >>> for seq in sequences:
... print(f"Result: {seq['generated_text']}")
Result:
The total number of muffins now is 21
```
This is a wrong answer, it should be 12. In this case, this can be due to the prompt being too basic, or due to the choice
of model, after all we've picked the smallest version of Falcon. Reas... | 100_10_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#best-practices-of-llm-prompting | .md | In this section of the guide we have compiled a list of best practices that tend to improve the prompt results:
* When choosing the model to work with, the latest and most capable models are likely to perform better.
* Start with a simple and short prompt, and iterate from there. | 100_11_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#best-practices-of-llm-prompting | .md | * Start with a simple and short prompt, and iterate from there.
* Put the instructions at the beginning of the prompt, or at the very end. When working with large context, models apply various optimizations to prevent Attention complexity from scaling quadratically. This may make a model more attentive to the beginning... | 100_11_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#best-practices-of-llm-prompting | .md | * Clearly separate instructions from the text they apply to - more on this in the next section.
* Be specific and descriptive about the task and the desired outcome - its format, length, style, language, etc.
* Avoid ambiguous descriptions and instructions.
* Favor instructions that say "what to do" instead of those th... | 100_11_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#best-practices-of-llm-prompting | .md | * "Lead" the output in the right direction by writing the first word (or even begin the first sentence for the model).
* Use advanced techniques like [Few-shot prompting](#few-shot-prompting) and [Chain-of-thought](#chain-of-thought)
* Test your prompts with different models to assess their robustness.
* Version and tr... | 100_11_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#few-shot-prompting | .md | The basic prompts in the sections above are the examples of "zero-shot" prompts, meaning, the model has been given
instructions and context, but no examples with solutions. LLMs that have been fine-tuned on instruction datasets, generally
perform well on such "zero-shot" tasks. However, you may find that your task has ... | 100_12_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#few-shot-prompting | .md | you have some requirements for the output that the model doesn't catch on just from the instructions. In this case, you can
try the technique called few-shot prompting.
In few-shot prompting, we provide examples in the prompt giving the model more context to improve the performance.
The examples condition the model t... | 100_12_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#few-shot-prompting | .md | Here's an example:
```python
>>> torch.manual_seed(0) # doctest: +IGNORE_RESULT
>>> prompt = """Text: The first human went into space and orbited the Earth on April 12, 1961.
... Date: 04/12/1961
... Text: The first-ever televised presidential debate in the United States took place on September 28, 1960, between pres... | 100_12_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#few-shot-prompting | .md | >>> sequences = pipe(
... prompt,
... max_new_tokens=8,
... do_sample=True,
... top_k=10,
... ) | 100_12_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#few-shot-prompting | .md | >>> for seq in sequences:
... print(f"Result: {seq['generated_text']}")
Result: Text: The first human went into space and orbited the Earth on April 12, 1961.
Date: 04/12/1961
Text: The first-ever televised presidential debate in the United States took place on September 28, 1960, between presidential candidates Jo... | 100_12_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#few-shot-prompting | .md | In the above code snippet we used a single example to demonstrate the desired output to the model, so this can be called a
"one-shot" prompting. However, depending on the task complexity you may need to use more than one example.
Limitations of the few-shot prompting technique:
- While LLMs can pick up on the pattern... | 100_12_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#few-shot-prompting | .md | - While LLMs can pick up on the patterns in the examples, these technique doesn't work well on complex reasoning tasks
- Few-shot prompting requires creating lengthy prompts. Prompts with large number of tokens can increase computation and latency. There's also a limit to the length of the prompts.
- Sometimes when giv... | 100_12_6 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#chain-of-thought | .md | Chain-of-thought (CoT) prompting is a technique that nudges a model to produce intermediate reasoning steps thus improving
the results on complex reasoning tasks.
There are two ways of steering a model to producing the reasoning steps:
- few-shot prompting by illustrating examples with detailed answers to questions, ... | 100_13_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#chain-of-thought | .md | - by instructing the model to reason by adding phrases like "Let's think step by step" or "Take a deep breath and work through the problem step by step."
If we apply the CoT technique to the muffins example from the [reasoning section](#reasoning) and use a larger model,
such as (`tiiuae/falcon-180B-chat`) which you ... | 100_13_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#chain-of-thought | .md | we'll get a significant improvement on the reasoning result:
```text
Let's go through this step-by-step:
1. You start with 15 muffins.
2. You eat 2 muffins, leaving you with 13 muffins.
3. You give 5 muffins to your neighbor, leaving you with 8 muffins.
4. Your partner buys 6 more muffins, bringing the total number o... | 100_13_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#prompting-vs-fine-tuning | .md | You can achieve great results by optimizing your prompts, however, you may still ponder whether fine-tuning a model
would work better for your case. Here are some scenarios when fine-tuning a smaller model may be a preferred option:
- Your domain is wildly different from what LLMs were pre-trained on and extensive pr... | 100_14_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#prompting-vs-fine-tuning | .md | - You need your model to work well in a low-resource language.
- You need the model to be trained on sensitive data that is under strict regulations.
- You have to use a small model due to cost, privacy, infrastructure or other limitations.
In all of the above examples, you will need to make sure that you either alre... | 100_14_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/prompting.md | https://huggingface.co/docs/transformers/en/tasks/prompting/#prompting-vs-fine-tuning | .md | to fine-tune a model.
If the above examples are not the case for you, optimizing prompts can prove to be more beneficial. | 100_14_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_feature_extraction.md | https://huggingface.co/docs/transformers/en/tasks/image_feature_extraction/ | .md | <!--Copyright 2024 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... | 101_0_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_feature_extraction.md | https://huggingface.co/docs/transformers/en/tasks/image_feature_extraction/ | .md | an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
rendered ... | 101_0_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_feature_extraction.md | https://huggingface.co/docs/transformers/en/tasks/image_feature_extraction/#image-feature-extraction | .md | [[open-in-colab]] | 101_1_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_feature_extraction.md | https://huggingface.co/docs/transformers/en/tasks/image_feature_extraction/#image-feature-extraction | .md | Image feature extraction is the task of extracting semantically meaningful features given an image. This has many use cases, including image similarity and image retrieval. Moreover, most computer vision models can be used for image feature extraction, where one can remove the task-specific head (image classification, ... | 101_1_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_feature_extraction.md | https://huggingface.co/docs/transformers/en/tasks/image_feature_extraction/#image-feature-extraction | .md | are very useful on a higher level: edge detection, corner detection and so on. They may also contain information about the real world (e.g. what a cat looks like) depending on how deep the model is. Therefore, these outputs can be used to train new classifiers on a specific dataset. | 101_1_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_feature_extraction.md | https://huggingface.co/docs/transformers/en/tasks/image_feature_extraction/#image-feature-extraction | .md | In this guide, you will:
- Learn to build a simple image similarity system on top of the `image-feature-extraction` pipeline.
- Accomplish the same task with bare model inference. | 101_1_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_feature_extraction.md | https://huggingface.co/docs/transformers/en/tasks/image_feature_extraction/#image-similarity-using-image-feature-extraction-pipeline | .md | We have two images of cats sitting on top of fish nets, one of them is generated.
```python
from PIL import Image
import requests | 101_2_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_feature_extraction.md | https://huggingface.co/docs/transformers/en/tasks/image_feature_extraction/#image-similarity-using-image-feature-extraction-pipeline | .md | img_urls = ["https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png", "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.jpeg"]
image_real = Image.open(requests.get(img_urls[0], stream=True).raw).convert("RGB")
image_gen = Image.open(requests.get(img_urls... | 101_2_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_feature_extraction.md | https://huggingface.co/docs/transformers/en/tasks/image_feature_extraction/#image-similarity-using-image-feature-extraction-pipeline | .md | image_gen = Image.open(requests.get(img_urls[1], stream=True).raw).convert("RGB")
```
Let's see the pipeline in action. First, initialize the pipeline. If you don't pass any model to it, the pipeline will be automatically initialized with [google/vit-base-patch16-224](google/vit-base-patch16-224). If you'd like to ca... | 101_2_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_feature_extraction.md | https://huggingface.co/docs/transformers/en/tasks/image_feature_extraction/#image-similarity-using-image-feature-extraction-pipeline | .md | ```python
import torch
from transformers import pipeline
from accelerate.test_utils.testing import get_backend
# automatically detects the underlying device type (CUDA, CPU, XPU, MPS, etc.)
DEVICE, _, _ = get_backend()
pipe = pipeline(task="image-feature-extraction", model_name="google/vit-base-patch16-384", device=DEV... | 101_2_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_feature_extraction.md | https://huggingface.co/docs/transformers/en/tasks/image_feature_extraction/#image-similarity-using-image-feature-extraction-pipeline | .md | ```python
outputs = pipe([image_real, image_gen])
```
The output contains pooled embeddings of those two images.
```python
# get the length of a single output
print(len(outputs[0][0]))
# show outputs
print(outputs) | 101_2_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_feature_extraction.md | https://huggingface.co/docs/transformers/en/tasks/image_feature_extraction/#image-similarity-using-image-feature-extraction-pipeline | .md | # 768
# [[[-0.03909236937761307, 0.43381670117378235, -0.06913255900144577,
```
To get the similarity score, we need to pass them to a similarity function.
```python
from torch.nn.functional import cosine_similarity
similarity_score = cosine_similarity(torch.Tensor(outputs[0]),
torch.Tensor(outputs[1]), dim=1)
pr... | 101_2_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_feature_extraction.md | https://huggingface.co/docs/transformers/en/tasks/image_feature_extraction/#image-similarity-using-image-feature-extraction-pipeline | .md | # tensor([0.6043])
```
If you want to get the last hidden states before pooling, avoid passing any value for the `pool` parameter, as it is set to `False`by default. These hidden states are useful for training new classifiers or models based on the features from the model.
```python
pipe = pipeline(task="image-feat... | 101_2_6 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_feature_extraction.md | https://huggingface.co/docs/transformers/en/tasks/image_feature_extraction/#image-similarity-using-image-feature-extraction-pipeline | .md | outputs = pipe(image_real)
```
Since the outputs are unpooled, we get the last hidden states where the first dimension is the batch size, and the last two are the embedding shape.
```python
import numpy as np
print(np.array(outputs).shape)
# (1, 197, 768)
``` | 101_2_7 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_feature_extraction.md | https://huggingface.co/docs/transformers/en/tasks/image_feature_extraction/#getting-features-and-similarities-using-automodel | .md | We can also use `AutoModel`class of transformers to get the features. `AutoModel` loads any transformers model with no task-specific head, and we can use this to get the features.
```python
from transformers import AutoImageProcessor, AutoModel | 101_3_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_feature_extraction.md | https://huggingface.co/docs/transformers/en/tasks/image_feature_extraction/#getting-features-and-similarities-using-automodel | .md | processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
model = AutoModel.from_pretrained("google/vit-base-patch16-224").to(DEVICE)
```
Let's write a simple function for inference. We will pass the inputs to the `processor` first and pass its outputs to the `model`.
```python
def infer(image):... | 101_3_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_feature_extraction.md | https://huggingface.co/docs/transformers/en/tasks/image_feature_extraction/#getting-features-and-similarities-using-automodel | .md | inputs = processor(image, return_tensors="pt").to(DEVICE)
outputs = model(**inputs)
return outputs.pooler_output
```
We can pass the images directly to this function and get the embeddings.
```python
embed_real = infer(image_real)
embed_gen = infer(image_gen)
```
We can get the similarity again over the embedding... | 101_3_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_feature_extraction.md | https://huggingface.co/docs/transformers/en/tasks/image_feature_extraction/#getting-features-and-similarities-using-automodel | .md | similarity_score = cosine_similarity(embed_real, embed_gen, dim=1)
print(similarity_score)
# tensor([0.6061], device='cuda:0', grad_fn=<SumBackward1>)
``` | 101_3_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/model_doc/timesformer.md | https://huggingface.co/docs/transformers/en/model_doc/timesformer/ | .md | <!--Copyright 2022 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... | 102_0_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/model_doc/timesformer.md | https://huggingface.co/docs/transformers/en/model_doc/timesformer/ | .md | an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
rendered ... | 102_0_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/model_doc/timesformer.md | https://huggingface.co/docs/transformers/en/model_doc/timesformer/#overview | .md | The TimeSformer model was proposed in [TimeSformer: Is Space-Time Attention All You Need for Video Understanding?](https://arxiv.org/abs/2102.05095) by Facebook Research.
This work is a milestone in action-recognition field being the first video transformer. It inspired many transformer based video understanding and cl... | 102_1_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/model_doc/timesformer.md | https://huggingface.co/docs/transformers/en/model_doc/timesformer/#overview | .md | *We present a convolution-free approach to video classification built exclusively on self-attention over space and time. Our method, named "TimeSformer," adapts the standard Transformer architecture to video by enabling spatiotemporal feature learning directly from a sequence of frame-level patches. Our experimental st... | 102_1_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/model_doc/timesformer.md | https://huggingface.co/docs/transformers/en/model_doc/timesformer/#overview | .md | "divided attention," where temporal attention and spatial attention are separately applied within each block, leads to the best video classification accuracy among the design choices considered. Despite the radically new design, TimeSformer achieves state-of-the-art results on several action recognition benchmarks, inc... | 102_1_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/model_doc/timesformer.md | https://huggingface.co/docs/transformers/en/model_doc/timesformer/#overview | .md | Finally, compared to 3D convolutional networks, our model is faster to train, it can achieve dramatically higher test efficiency (at a small drop in accuracy), and it can also be applied to much longer video clips (over one minute long). Code and models are available at: [this https URL](https://github.com/facebookrese... | 102_1_3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.