├── .devcontainer └── devcontainer.json ├── .github └── workflows │ └── gitleaks.yml ├── .gitignore ├── .python-version ├── 1_instruction_tuning ├── README.md ├── chat_templates.md ├── notebooks │ ├── .env.example │ ├── chat_templates_example.ipynb │ └── sft_finetuning_example.ipynb └── supervised_fine_tuning.md ├── 2_preference_alignment ├── README.md ├── dpo.md ├── notebooks │ ├── dpo_finetuning_example.ipynb │ └── orpo_finetuning_example.ipynb └── orpo.md ├── 3_parameter_efficient_finetuning ├── README.md ├── images │ └── lora_adapter.png ├── lora_adapters.md ├── notebooks │ ├── finetune_sft_peft.ipynb │ └── load_lora_adapter.ipynb └── prompt_tuning.md ├── 4_evaluation ├── README.md ├── automatic_benchmarks.md ├── custom_evaluation.md ├── notebooks │ └── lighteval_evaluate_and_analyse_your_LLM.ipynb └── project │ ├── README.md │ ├── annotate_dataset.py │ ├── create_dataset.py │ ├── evaluation_task.py │ ├── generate_dataset.py │ └── images │ ├── domain_eval_argilla_view.png │ └── domain_eval_dataset_viewer.png ├── 5_vision_language_models ├── README.md ├── images │ ├── VLM_Architecture.png │ ├── VLM_Process.png │ └── VLM_Usage.png ├── notebooks │ ├── vlm_sft_sample.ipynb │ └── vlm_usage_sample.ipynb ├── vlm_finetuning.md └── vlm_usage.md ├── 6_synthetic_datasets ├── README.md ├── images │ ├── pipeline.png │ └── taxonomy-synthetic-data.png ├── instruction_datasets.md ├── notebooks │ ├── instruction_sft_dataset.ipynb │ └── preference_dpo_dataset.ipynb └── preference_datasets.md ├── 7_inference ├── README.md ├── inference_pipeline.md └── text_generation_inference.md ├── 8_agents ├── README.md ├── code_agents.md ├── custom_functions.md ├── notebooks │ └── agents.ipynb └── retrieval_agents.md ├── LICENSE ├── README.md ├── banner.png ├── es ├── 1_instruction_tuning │ ├── README.md │ ├── chat_templates.md │ ├── notebooks │ │ ├── .env.example │ │ ├── chat_templates_example.ipynb │ │ └── sft_finetuning_example.ipynb │ └── supervised_fine_tuning.md ├── 2_preference_alignment │ ├── README.md │ ├── dpo.md │ ├── notebooks │ │ ├── dpo_finetuning_example.ipynb │ │ └── orpo_finetuning_example.ipynb │ └── orpo.md ├── 3_parameter_efficient_finetuning │ ├── README.md │ ├── lora_adapters.md │ ├── notebooks │ │ ├── finetune_sft_peft.ipynb │ │ └── load_lora_adapter_example.ipynb │ └── prompt_tuning.md ├── 4_evaluation │ ├── README.md │ ├── automatic_benchmarks.md │ ├── custom_evaluation.md │ ├── notebooks │ │ └── lighteval_evaluate_and_analyse_your_LLM.ipynb │ └── project │ │ ├── README.md │ │ ├── annotate_dataset.py │ │ ├── create_dataset.py │ │ ├── evaluation_task.py │ │ ├── generate_dataset.py │ │ └── images │ │ ├── domain_eval_argilla_view.png │ │ └── domain_eval_dataset_viewer.png ├── README.md └── banner.png ├── ja ├── 1_instruction_tuning │ ├── README.md │ ├── chat_templates.md │ ├── notebooks │ │ ├── .env.example │ │ ├── chat_templates_example.ipynb │ │ └── sft_finetuning_example.ipynb │ └── supervised_fine_tuning.md ├── 2_preference_alignment │ ├── README.md │ ├── dpo.md │ ├── notebooks │ │ ├── dpo_finetuning_example.ipynb │ │ └── orpo_finetuning_example.ipynb │ └── orpo.md ├── 3_parameter_efficient_finetuning │ ├── README.md │ ├── images │ │ └── lora_adapter.png │ ├── lora_adapters.md │ ├── notebooks │ │ ├── finetune_sft_peft.ipynb │ │ └── load_lora_adapter.ipynb │ └── prompt_tuning.md ├── 4_evaluation │ ├── README.md │ ├── automatic_benchmarks.md │ ├── custom_evaluation.md │ ├── notebooks │ │ └── lighteval_evaluate_and_analyse_your_LLM.ipynb │ └── project │ │ ├── README.md │ │ ├── annotate_dataset.py │ │ ├── create_dataset.py │ │ ├── evaluation_task.py │ │ └── generate_dataset.py ├── 5_vision_language_models │ ├── README.md │ ├── images │ │ ├── VLM_Architecture.png │ │ ├── VLM_Process.png │ │ └── VLM_Usage.png │ ├── notebooks │ │ ├── vlm_sft_sample.ipynb │ │ └── vlm_usage_sample.ipynb │ ├── vlm_finetuning.md │ └── vlm_usage.md ├── 6_synthetic_datasets │ ├── README.md │ ├── images │ │ ├── pipeline.png │ │ └── taxonomy-synthetic-data.png │ ├── instruction_datasets.md │ ├── notebooks │ │ ├── instruction_sft_dataset.ipynb │ │ └── preference_dpo_dataset.ipynb │ └── preference_datasets.md └── README.md ├── ko ├── 1_instruction_tuning │ ├── README.md │ ├── chat_templates.md │ ├── notebooks │ │ ├── .env.example │ │ ├── chat_templates_example.ipynb │ │ └── sft_finetuning_example.ipynb │ └── supervised_fine_tuning.md ├── 3_parameter_efficient_finetuning │ ├── README.md │ ├── images │ │ └── lora_adapter.png │ ├── lora_adapters.md │ ├── notebooks │ │ ├── finetune_sft_peft.ipynb │ │ └── load_lora_adapter.ipynb │ └── prompt_tuning.md └── README.md ├── pt-br ├── 1_instruction_tuning │ ├── README.md │ ├── chat_templates.md │ ├── notebooks │ │ ├── .env.example │ │ ├── chat_templates_example.ipynb │ │ └── sft_finetuning_example.ipynb │ └── supervised_fine_tuning.md ├── 2_preference_alignment │ ├── README.md │ ├── dpo.md │ ├── notebooks │ │ ├── dpo_finetuning_example.ipynb │ │ └── orpo_finetuning_example.ipynb │ └── orpo.md ├── 3_parameter_efficient_finetuning │ ├── README.md │ ├── images │ │ └── lora_adapter.png │ ├── lora_adapters.md │ ├── notebooks │ │ ├── finetune_sft_peft.ipynb │ │ └── load_lora_adapter.ipynb │ └── prompt_tuning.md ├── 4_evaluation │ ├── README.md │ ├── automatic_benchmarks.md │ ├── custom_evaluation.md │ ├── notebooks │ │ └── lighteval_evaluate_and_analyse_your_LLM.ipynb │ └── project │ │ ├── README.md │ │ ├── annotate_dataset.py │ │ ├── create_dataset.py │ │ ├── evaluation_task.py │ │ ├── generate_dataset.py │ │ └── images │ │ ├── domain_eval_argilla_view.png │ │ └── domain_eval_dataset_viewer.png └── README.md ├── pull_request_template.md ├── pyproject.toml ├── requirements.txt ├── uv.lock └── vi ├── 1_instruction_tuning ├── README.md ├── chat_templates.md ├── notebooks │ ├── .env.example │ ├── chat_templates_example.ipynb │ └── sft_finetuning_example.ipynb └── supervised_fine_tuning.md ├── 2_preference_alignment ├── README.md ├── dpo.md ├── notebooks │ ├── dpo_finetuning_example.ipynb │ └── orpo_finetuning_example.ipynb └── orpo.md ├── 3_parameter_efficient_finetuning ├── README.md ├── images │ ├── lora_adapter.png │ └── prompt_tuning.png ├── lora_adapters.md ├── notebooks │ ├── finetune_sft_peft.ipynb │ └── load_lora_adapter.ipynb └── prompt_tuning.md ├── 4_evaluation ├── README.md ├── automatic_benchmarks.md ├── custom_evaluation.md ├── notebooks │ └── lighteval_evaluate_and_analyse_your_LLM.ipynb └── project │ ├── README.md │ ├── annotate_dataset.py │ ├── create_dataset.py │ ├── evaluation_task.py │ ├── generate_dataset.py │ └── images │ ├── domain_eval_argilla_view.png │ └── domain_eval_dataset_viewer.png ├── 5_vision_language_models ├── README.md ├── images │ ├── VLM_Architecture.png │ ├── VLM_Process.png │ └── VLM_Usage.png ├── notebooks │ ├── vlm_sft_sample.ipynb │ └── vlm_usage_sample.ipynb ├── vlm_finetuning.md └── vlm_usage.md ├── 6_synthetic_datasets ├── README.md ├── images │ ├── pipeline.png │ └── taxonomy-synthetic-data.png ├── instruction_datasets.md ├── notebooks │ ├── instruction_sft_dataset.ipynb │ └── preference_dpo_dataset.ipynb └── preference_datasets.md └── README.md /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | // DevContainer configuration for Smol Course Development Environment 2 | // This file configures a development container with Python 3.12, Jupyter support, 3 | // and essential Python development extensions. It uses the uv package manager 4 | // and automatically sets up the Python virtual environment with required dependencies. 5 | // You can use it with Microsoft VS Code, Codespaces, Daytona.io and other tools that 6 | // support Dev Containers standard. 7 | { 8 | "name": "Smol Course Development Environment", 9 | "image": "mcr.microsoft.com/devcontainers/python:3.12", 10 | "forwardPorts": [ 11 | 8888 12 | ], 13 | "features": { 14 | "ghcr.io/va-h/devcontainers-features/uv:1": {} 15 | }, 16 | "customizations": { 17 | "vscode": { 18 | "settings": { 19 | "python.defaultInterpreterPath": "/usr/local/bin/python" 20 | }, 21 | "extensions": [ 22 | "ms-python.python", 23 | "ms-python.pylint", 24 | "ms-python.flake8", 25 | "ms-python.black-formatter", 26 | "njpwerner.autodocstring", 27 | "matangover.mypy", 28 | "ms-python.autopep8", 29 | "ms-toolsai.jupyter", 30 | "ms-toolsai.vscode-jupyter-powertoys", 31 | "ms-toolsai.jupyter-hub" 32 | ] 33 | } 34 | }, 35 | "postCreateCommand": "uv venv && uv pip sync requirements.txt" 36 | } -------------------------------------------------------------------------------- /.github/workflows/gitleaks.yml: -------------------------------------------------------------------------------- 1 | name: gitleaks 2 | on: 3 | pull_request: 4 | push: 5 | workflow_dispatch: 6 | jobs: 7 | scan: 8 | name: gitleaks 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v4 12 | with: 13 | fetch-depth: 0 14 | - uses: gitleaks/gitleaks-action@v2 15 | env: 16 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 110 | .pdm.toml 111 | .pdm-python 112 | .pdm-build/ 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # Model output files 158 | sft_output/ 159 | # PyCharm 160 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 161 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 162 | # and can be added to the global gitignore or merged into this file. For a more nuclear 163 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 164 | #.idea/ 165 | .DS_Store 166 | -------------------------------------------------------------------------------- /.python-version: -------------------------------------------------------------------------------- 1 | 3.11 2 | -------------------------------------------------------------------------------- /1_instruction_tuning/README.md: -------------------------------------------------------------------------------- 1 | # Instruction Tuning 2 | 3 | This module will guide you through instruction tuning language models. Instruction tuning involves adapting pre-trained models to specific tasks by further training them on task-specific datasets. This process helps models improve their performance on targeted tasks. 4 | 5 | In this module, we will explore two topics: 1) Chat Templates and 2) Supervised Fine-Tuning. 6 | 7 | ## 1️⃣ Chat Templates 8 | 9 | Chat templates structure interactions between users and AI models, ensuring consistent and contextually appropriate responses. They include components like system prompts and role-based messages. For more detailed information, refer to the [Chat Templates](./chat_templates.md) section. 10 | 11 | ## 2️⃣ Supervised Fine-Tuning 12 | 13 | Supervised Fine-Tuning (SFT) is a critical process for adapting pre-trained language models to specific tasks. It involves training the model on a task-specific dataset with labeled examples. For a detailed guide on SFT, including key steps and best practices, see the [Supervised Fine-Tuning](./supervised_fine_tuning.md) page. 14 | 15 | ## Exercise Notebooks 16 | 17 | | Title | Description | Exercise | Link | Colab | 18 | |-------|-------------|----------|------|-------| 19 | | Chat Templates | Learn how to use chat templates with SmolLM2 and process datasets into chatml format | 🐢 Convert the `HuggingFaceTB/smoltalk` dataset into chatml format
🐕 Convert the `openai/gsm8k` dataset into chatml format | [Notebook](./notebooks/chat_templates_example.ipynb) | Open In Colab | 20 | | Supervised Fine-Tuning | Learn how to fine-tune SmolLM2 using the SFTTrainer | 🐢 Use the `HuggingFaceTB/smoltalk` dataset
🐕 Try out the `bigcode/the-stack-smol` dataset
🦁 Select a dataset for a real world use case | [Notebook](./notebooks/sft_finetuning_example.ipynb) | Open In Colab | 21 | 22 | ## References 23 | 24 | - [Transformers documentation on chat templates](https://huggingface.co/docs/transformers/main/en/chat_templating) 25 | - [Script for Supervised Fine-Tuning in TRL](https://github.com/huggingface/trl/blob/main/examples/scripts/sft.py) 26 | - [`SFTTrainer` in TRL](https://huggingface.co/docs/trl/main/en/sft_trainer) 27 | - [Direct Preference Optimization Paper](https://arxiv.org/abs/2305.18290) 28 | - [Supervised Fine-Tuning with TRL](https://huggingface.co/docs/trl/main/en/tutorials/supervised_finetuning) 29 | - [How to fine-tune Google Gemma with ChatML and Hugging Face TRL](https://www.philschmid.de/fine-tune-google-gemma) 30 | - [Fine-tuning LLM to Generate Persian Product Catalogs in JSON Format](https://huggingface.co/learn/cookbook/en/fine_tuning_llm_to_generate_persian_product_catalogs_in_json_format) 31 | -------------------------------------------------------------------------------- /1_instruction_tuning/notebooks/.env.example: -------------------------------------------------------------------------------- 1 | # Duplicate this file to .env and fill in secret values 2 | HF_TOKEN= 3 | -------------------------------------------------------------------------------- /1_instruction_tuning/supervised_fine_tuning.md: -------------------------------------------------------------------------------- 1 | # Supervised Fine-Tuning 2 | 3 | Supervised Fine-Tuning (SFT) is a critical process for adapting pre-trained language models to specific tasks or domains. While pre-trained models have impressive general capabilities, they often need to be customized to excel at particular use cases. SFT bridges this gap by further training the model on carefully curated datasets with human-validated examples. 4 | 5 | ## Understanding Supervised Fine-Tuning 6 | 7 | At its core, supervised fine-tuning is about teaching a pre-trained model to perform specific tasks through examples of labeled tokens. The process involves showing the model many examples of the desired input-output behavior, allowing it to learn the patterns specific to your use case. 8 | 9 | SFT is effective because it uses the foundational knowledge acquired during pre-training while adapting the model's behavior to match your specific needs. 10 | 11 | ## When to Use Supervised Fine-Tuning 12 | 13 | The decision to use SFT often comes down to the gap between your model's current capabilities and your specific requirements. SFT becomes particularly valuable when you need precise control over the model's outputs or when working in specialized domains. 14 | 15 | For example, if you're developing a customer service application, you might want your model to consistently follow company guidelines and handle technical queries in a standardized way. Similarly, in medical or legal applications, accuracy and adherence to domain-specific terminology becomes crucial. In these cases, SFT can help align the model's responses with professional standards and domain expertise. 16 | 17 | ## The Fine-Tuning Process 18 | 19 | The supervised fine-tuning process involves adjusting a model's weights on a task-specific dataset. 20 | 21 | First, you'll need to prepare or select a dataset that represents your target task. This dataset should include diverse examples that cover the range of scenarios your model will encounter. The quality of this data is important - each example should demonstrate the kind of output you want your model to produce. Next comes the actual fine-tuning phase, where you'll use frameworks like Hugging Face's `transformers` and `trl` to train the model on your dataset. 22 | 23 | Throughout the process, continuous evaluation is essential. You'll want to monitor the model's performance on a validation set to ensure it's learning the desired behaviors without losing its general capabilities. In [module 4](../4_evaluation), we'll cover how to evaluate your model. 24 | 25 | ## The Role of SFT in Preference Alignment 26 | 27 | SFT plays a fundamental role in aligning language models with human preferences. Techniques such as Reinforcement Learning from Human Feedback (RLHF) and Direct Preference Optimization (DPO) rely on SFT to form a base level of task understanding before further aligning the model’s responses with desired outcomes. Pre-trained models, despite their general language proficiency, may not always generate outputs that match human preferences. SFT bridges this gap by introducing domain-specific data and guidance, which improves the model’s ability to generate responses that align more closely with human expectations. 28 | 29 | ## Supervised Fine-Tuning With Transformer Reinforcement Learning 30 | 31 | A key software package for Supervised Fine-Tuning is Transformer Reinforcement Learning (TRL). TRL is a toolkit used to train transformer language models using reinforcement learning (RL). 32 | 33 | Built on top of the Hugging Face Transformers library, TRL allows users to directly load pretrained language models and supports most decoder and encoder-decoder architectures. The library facilitates major processes of RL used in language modelling, including supervised fine-tuning (SFT), reward modeling (RM), proximal policy optimization (PPO), and Direct Preference Optimization (DPO). We will use TRL in a number of modules throughout this repo. 34 | 35 | # Next Steps 36 | 37 | Try out the following tutorials to get hands on experience with SFT using TRL: 38 | 39 | ⏭️ [Chat Templates Tutorial](./notebooks/chat_templates_example.ipynb) 40 | 41 | ⏭️ [Supervised Fine-Tuning Tutorial](./notebooks/sft_finetuning_example.ipynb) 42 | -------------------------------------------------------------------------------- /3_parameter_efficient_finetuning/README.md: -------------------------------------------------------------------------------- 1 | # Parameter-Efficient Fine-Tuning (PEFT) 2 | 3 | As language models grow larger, traditional fine-tuning becomes increasingly challenging. A full fine-tuning of even a 1.7B parameter model requires substantial GPU memory, makes storing separate model copies expensive, and risks catastrophic forgetting of the model's original capabilities. Parameter-efficient fine-tuning (PEFT) methods address these challenges by modifying only a small subset of model parameters while keeping most of the model frozen. 4 | 5 | Traditional fine-tuning updates all model parameters during training, which becomes impractical for large models. PEFT methods introduce approaches to adapt models using fewer trainable parameters - often less than 1% of the original model size. This dramatic reduction in trainable parameters enables: 6 | 7 | - Fine-tuning on consumer hardware with limited GPU memory 8 | - Storing multiple task-specific adaptations efficiently 9 | - Better generalization in low-data scenarios 10 | - Faster training and iteration cycles 11 | 12 | ## Available Methods 13 | 14 | In this module, we will cover two popular PEFT methods: 15 | 16 | ### 1️⃣ LoRA (Low-Rank Adaptation) 17 | 18 | LoRA has emerged as the most widely adopted PEFT method, offering an elegant solution to efficient model adaptation. Instead of modifying the entire model, **LoRA injects trainable matrices into the model's attention layers.** This approach typically reduces trainable parameters by about 90% while maintaining comparable performance to full fine-tuning. We will explore LoRA in the [LoRA (Low-Rank Adaptation)](./lora_adapters.md) section. 19 | 20 | ### 2️⃣ Prompt Tuning 21 | 22 | Prompt tuning offers an **even lighter** approach by **adding trainable tokens to the input** rather than modifying model weights. Prompt tuning is less popular than LoRA, but can be a useful technique for quickly adapting a model to new tasks or domains. We will explore prompt tuning in the [Prompt Tuning](./prompt_tuning.md) section. 23 | 24 | ## Exercise Notebooks 25 | 26 | | Title | Description | Exercise | Link | Colab | 27 | |-------|-------------|----------|------|-------| 28 | | LoRA Fine-tuning | Learn how to fine-tune models using LoRA adapters | 🐢 Train a model using LoRA
🐕 Experiment with different rank values
🦁 Compare performance with full fine-tuning | [Notebook](./notebooks/finetune_sft_peft.ipynb) | Open In Colab | 29 | | Load LoRA Adapters | Learn how to load and use trained LoRA adapters | 🐢 Load pre-trained adapters
🐕 Merge adapters with base model
🦁 Switch between multiple adapters | [Notebook](./notebooks/load_lora_adapter.ipynb) | Open In Colab | 30 | 31 | 32 | ## Resources 33 | - [PEFT Documentation](https://huggingface.co/docs/peft) 34 | - [LoRA Paper](https://arxiv.org/abs/2106.09685) 35 | - [QLoRA Paper](https://arxiv.org/abs/2305.14314) 36 | - [Prompt Tuning Paper](https://arxiv.org/abs/2104.08691) 37 | - [Hugging Face PEFT Guide](https://huggingface.co/blog/peft) 38 | - [How to Fine-Tune LLMs in 2024 with Hugging Face](https://www.philschmid.de/fine-tune-llms-in-2024-with-trl) 39 | - [TRL](https://huggingface.co/docs/trl/index) 40 | -------------------------------------------------------------------------------- /3_parameter_efficient_finetuning/images/lora_adapter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/3_parameter_efficient_finetuning/images/lora_adapter.png -------------------------------------------------------------------------------- /4_evaluation/README.md: -------------------------------------------------------------------------------- 1 | # Evaluation 2 | 3 | Evaluation is a critical step in developing and deploying language models. It helps us understand how well our models perform across different capabilities and identify areas for improvement. This module covers both standard benchmarks and domain-specific evaluation approaches to comprehensively assess your smol model. 4 | 5 | We'll use [`lighteval`](https://github.com/huggingface/lighteval), a powerful evaluation library developed by Hugging Face that integrates seamlessly with the Hugging Face ecosystem. For a deeper dive into evaluation concepts and best practices, check out the evaluation [guidebook](https://github.com/huggingface/evaluation-guidebook). 6 | 7 | ## Module Overview 8 | 9 | A thorough evaluation strategy examines multiple aspects of model performance. We assess task-specific capabilities like question answering and summarization to understand how well the model handles different types of problems. We measure output quality through factors like coherence and factual accuracy. Safety evaluation helps identify potential harmful outputs or biases. Finally, domain expertise testing verifies the model's specialized knowledge in your target field. 10 | 11 | ## Contents 12 | 13 | ### 1️⃣ [Automatic Benchmarks](./automatic_benchmarks.md) 14 | 15 | Learn to evaluate your model using standardized benchmarks and metrics. We'll explore common benchmarks like MMLU and TruthfulQA, understand key evaluation metrics and settings, and cover best practices for reproducible evaluation. 16 | 17 | 18 | ### 2️⃣ [Custom Domain Evaluation](./custom_evaluation.md) 19 | Discover how to create evaluation pipelines tailored to your specific use case. We'll walk through designing custom evaluation tasks, implementing specialized metrics, and building evaluation datasets that match your requirements. 20 | 21 | ### 3️⃣ [Domain Evaluation Project](./project/README.md) 22 | Follow a complete example of building a domain-specific evaluation pipeline. You'll learn to generate evaluation datasets, use Argilla for data annotation, create standardized datasets, and evaluate models using LightEval. 23 | 24 | ### Exercise Notebooks 25 | 26 | | Title | Description | Exercise | Link | Colab | 27 | |-------|-------------|----------|------|-------| 28 | | Evaluate and Analyze Your LLM | Learn how to use LightEval to evaluate and compare models on specific domains | 🐢 Use medical domain tasks to evaluate a model
🐕 Create a new domain evaluation with different MMLU tasks
🦁 Create a custom evaluation task for your domain | [Notebook](./notebooks/lighteval_evaluate_and_analyse_your_LLM.ipynb) | Open In Colab | 29 | 30 | 31 | ## Resources 32 | 33 | - [Evaluation Guidebook](https://github.com/huggingface/evaluation-guidebook) - Comprehensive guide to LLM evaluation 34 | - [LightEval Documentation](https://github.com/huggingface/lighteval) - Official docs for the LightEval library 35 | - [Argilla Documentation](https://docs.argilla.io) - Learn about the Argilla annotation platform 36 | - [MMLU Paper](https://arxiv.org/abs/2009.03300) - Paper describing the MMLU benchmark 37 | - [Creating a Custom Task](https://github.com/huggingface/lighteval/wiki/Adding-a-Custom-Task) 38 | - [Creating a Custom Metric](https://github.com/huggingface/lighteval/wiki/Adding-a-New-Metric) 39 | - [Using existing metrics](https://github.com/huggingface/lighteval/wiki/Metric-List) -------------------------------------------------------------------------------- /4_evaluation/project/annotate_dataset.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import json 3 | from random import choices, sample 4 | 5 | import argilla as rg 6 | from distilabel.distiset import Distiset 7 | 8 | ################################################################################ 9 | # Script Parameters 10 | ################################################################################ 11 | 12 | parser = argparse.ArgumentParser( 13 | description="Annotate exam questions dataset using Argilla." 14 | ) 15 | parser.add_argument( 16 | "--argilla_api_key", 17 | type=str, 18 | default="argilla.apikey", 19 | help="API key for Argilla", 20 | ) 21 | parser.add_argument( 22 | "--argilla_api_url", 23 | type=str, 24 | default="http://localhost:6900", 25 | help="API URL for Argilla", 26 | ) 27 | parser.add_argument( 28 | "--dataset_path", 29 | type=str, 30 | default="exam_questions", 31 | help="Path to the exam questions dataset", 32 | ) 33 | parser.add_argument( 34 | "--dataset_config", 35 | type=str, 36 | default="default", 37 | help="Configuration of the dataset", 38 | ) 39 | parser.add_argument( 40 | "--dataset_split", 41 | type=str, 42 | default="train", 43 | help="Split of the dataset to use", 44 | ) 45 | parser.add_argument( 46 | "--output_dataset_name", 47 | type=str, 48 | default="exam_questions", 49 | help="Name of the output Argilla dataset", 50 | ) 51 | 52 | args = parser.parse_args() 53 | 54 | ################################################################################ 55 | # Create Argilla dataset with the feedback task for validation 56 | ################################################################################ 57 | 58 | client = rg.Argilla(api_key=args.argilla_api_key, api_url=args.argilla_api_url) 59 | 60 | if client.datasets(args.output_dataset_name): 61 | print(f"Deleting existing dataset '{args.output_dataset_name}'") 62 | client.datasets(args.output_dataset_name).delete() 63 | 64 | settings = rg.Settings( 65 | fields=[ 66 | rg.TextField("question"), 67 | rg.TextField("answer_a"), 68 | rg.TextField("answer_b"), 69 | rg.TextField("answer_c"), 70 | rg.TextField("answer_d"), 71 | ], 72 | questions=[ 73 | rg.LabelQuestion( 74 | name="correct_answer", 75 | labels=["answer_a", "answer_b", "answer_c", "answer_d"], 76 | ), 77 | rg.TextQuestion( 78 | name="improved_question", 79 | description="Could you improve the question?", 80 | ), 81 | rg.TextQuestion( 82 | name="improved_answer", 83 | description="Could you improve the best answer?", 84 | ), 85 | ], 86 | ) 87 | 88 | dataset = rg.Dataset(settings=settings, name=args.output_dataset_name) 89 | dataset.create() 90 | 91 | ################################################################################ 92 | # Load the Distiset and process and add records to Argilla dataset 93 | # We will validate that questions appear in random order to avoid bias 94 | # but we will show correct answers in the Argilla UI as suggestions. 95 | ################################################################################ 96 | 97 | distiset = Distiset.load_from_disk(args.dataset_path) 98 | answer_names = ["answer_a", "answer_b", "answer_c", "answer_d"] 99 | dataset_records = [] 100 | 101 | for exam in distiset[args.dataset_config][args.dataset_split]: 102 | exam_json = json.loads(exam["generation"])["exam"] 103 | 104 | for question in exam_json: 105 | answer = question["answer"] 106 | distractors = question["distractors"] 107 | distractors = choices(distractors, k=3) 108 | answers = distractors + [answer] 109 | answers = sample(answers, len(answers)) 110 | suggestion_idx = answers.index(answer) 111 | fields = dict(zip(answer_names, answers)) 112 | fields["question"] = question["question"] 113 | 114 | record = rg.Record( 115 | fields=fields, 116 | suggestions=[ 117 | rg.Suggestion( 118 | question_name="correct_answer", 119 | value=answer_names[suggestion_idx], 120 | ) 121 | ], 122 | ) 123 | dataset_records.append(record) 124 | 125 | dataset.records.log(dataset_records) 126 | 127 | print( 128 | f"Dataset '{args.output_dataset_name}' has been created and populated in Argilla." 129 | ) 130 | -------------------------------------------------------------------------------- /4_evaluation/project/create_dataset.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | import argilla as rg 4 | from datasets import Dataset 5 | 6 | ################################################################################ 7 | # Script Parameters 8 | ################################################################################ 9 | 10 | parser = argparse.ArgumentParser( 11 | description="Create a Hugging Face dataset from annotated Argilla data." 12 | ) 13 | parser.add_argument( 14 | "--argilla_api_key", 15 | type=str, 16 | default="argilla.apikey", 17 | help="API key for Argilla", 18 | ) 19 | parser.add_argument( 20 | "--argilla_api_url", 21 | type=str, 22 | default="http://localhost:6900", 23 | help="API URL for Argilla", 24 | ) 25 | parser.add_argument( 26 | "--dataset_path", 27 | type=str, 28 | default="exam_questions", 29 | help="Path to the Argilla dataset", 30 | ) 31 | parser.add_argument( 32 | "--dataset_repo_id", 33 | type=str, 34 | default="burtenshaw/exam_questions", 35 | help="Hugging Face dataset repository ID", 36 | ) 37 | 38 | args = parser.parse_args() 39 | 40 | ################################################################################ 41 | # Initialize Argilla client and load dataset 42 | ################################################################################ 43 | 44 | client = rg.Argilla(api_key=args.argilla_api_key, api_url=args.argilla_api_url) 45 | dataset = client.datasets(args.dataset_path) 46 | 47 | ################################################################################ 48 | # Process Argilla records 49 | ################################################################################ 50 | 51 | dataset_rows = [] 52 | 53 | for record in dataset.records(with_suggestions=True, with_responses=True): 54 | row = record.fields 55 | 56 | if len(record.responses) == 0: 57 | answer = record.suggestions["correct_answer"].value 58 | row["correct_answer"] = answer 59 | else: 60 | for response in record.responses: 61 | if response.question_name == "correct_answer": 62 | row["correct_answer"] = response.value 63 | dataset_rows.append(row) 64 | 65 | ################################################################################ 66 | # Create Hugging Face dataset and push to Hub 67 | ################################################################################ 68 | 69 | hf_dataset = Dataset.from_list(dataset_rows) 70 | hf_dataset.push_to_hub(repo_id=args.dataset_repo_id) 71 | 72 | print(f"Dataset has been successfully pushed to {args.dataset_repo_id}") 73 | -------------------------------------------------------------------------------- /4_evaluation/project/evaluation_task.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | from lighteval.tasks.lighteval_task import LightevalTaskConfig 4 | from lighteval.tasks.requests import Doc 5 | from lighteval.metrics.utils.metric_utils import ( 6 | SampleLevelMetric, 7 | MetricCategory, 8 | MetricUseCase, 9 | ) 10 | 11 | ################################################################################ 12 | # Define the prompt function based on the structure of the dataset 13 | ################################################################################ 14 | 15 | 16 | def prompt_fn(line, task_name: str = None): 17 | """Converts a dataset line to a Doc object for evaluation.""" 18 | instruction = "Choose the correct answer for the following exam question:" 19 | return Doc( 20 | task_name=task_name, 21 | query=f"{instruction} {line['question']}", 22 | choices=[ 23 | f" {line['answer_a']}", 24 | f" {line['answer_b']}", 25 | f" {line['answer_c']}", 26 | f" {line['answer_d']}", 27 | ], 28 | gold_index=["answer_a", "answer_b", "answer_c", "answer_d"].index( 29 | line["correct_answer"] 30 | ), 31 | instruction=instruction, 32 | ) 33 | 34 | 35 | ################################################################################ 36 | # Define the custom metric based on guide here https://github.com/huggingface/lighteval/wiki/Adding-a-New-Metric 37 | # Or use an existing metric based on the guide here: https://github.com/huggingface/lighteval/wiki/Metric-List 38 | # Existing metrics can be imported from lighteval.metrics.metrics 39 | ################################################################################ 40 | 41 | 42 | def sample_level_fn(formatted_doc: Doc, **kwargs) -> bool: 43 | response = np.argmin(kwargs["choices_logprob"]) 44 | return response == formatted_doc.gold_index 45 | 46 | 47 | custom_metric = SampleLevelMetric( 48 | metric_name="exam_question_accuracy", 49 | higher_is_better=True, 50 | category=MetricCategory.MULTICHOICE, 51 | use_case=MetricUseCase.NONE, 52 | sample_level_fn=sample_level_fn, 53 | corpus_level_fn=np.mean, 54 | ) 55 | 56 | ################################################################################ 57 | # Define the task based on the prompt function and the custom metric 58 | # Based on the guide here: https://github.com/huggingface/lighteval/wiki/Adding-a-Custom-Task 59 | ################################################################################ 60 | 61 | task = LightevalTaskConfig( 62 | name="example", 63 | prompt_function=prompt_fn, 64 | suite=["community"], 65 | hf_repo="burtenshaw/exam_questions", 66 | hf_subset="default", 67 | hf_avail_splits=["train"], 68 | evaluation_splits=["train"], 69 | few_shots_split=None, 70 | few_shots_select=None, 71 | metric=[custom_metric], 72 | ) 73 | 74 | # Add the task to TASKS_TABLE 75 | TASKS_TABLE = [task] 76 | 77 | # MODULE LOGIC 78 | if __name__ == "__main__": 79 | print([t.name for t in TASKS_TABLE]) 80 | print(len(TASKS_TABLE)) 81 | 82 | # lighteval accelerate \ 83 | # "pretrained=HuggingFaceTB/SmolLM2-135M-Instruct" \ 84 | # "community|example|0|0" \ 85 | # --custom-tasks "submitted_tasks/example.py" \ 86 | # --output-dir "results" 87 | -------------------------------------------------------------------------------- /4_evaluation/project/images/domain_eval_argilla_view.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/4_evaluation/project/images/domain_eval_argilla_view.png -------------------------------------------------------------------------------- /4_evaluation/project/images/domain_eval_dataset_viewer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/4_evaluation/project/images/domain_eval_dataset_viewer.png -------------------------------------------------------------------------------- /5_vision_language_models/README.md: -------------------------------------------------------------------------------- 1 | # Vision Language Models 2 | 3 | ## 1. VLM Usage 4 | 5 | Vision Language Models (VLMs) process image inputs alongside text to enable tasks like image captioning, visual question answering, and multimodal reasoning. 6 | 7 | A typical VLM architecture consists of an image encoder to extract visual features, a projection layer to align visual and textual representations, and a language model to process or generate text. This allows the model to establish connections between visual elements and language concepts. 8 | 9 | VLMs can be used in different configurations depending on the use case. Base models handle general vision-language tasks, while chat-optimized variants support conversational interactions. Some models include additional components for grounding predictions in visual evidence or specializing in specific tasks like object detection. 10 | 11 | For more on the technicality and usage of VLMs, refer to the [VLM Usage](./vlm_usage.md) page. 12 | 13 | ## 2. VLM Fine-Tuning 14 | 15 | Fine-tuning a VLM involves adapting a pre-trained model to perform specific tasks or to operate effectively on a particular dataset. The process can follow methodologies such as supervised fine-tuning, preference optimization, or a hybrid approach that combines both, as introduced in Modules 1 and 2. 16 | 17 | While the core tools and techniques remain similar to those used for LLMs, fine-tuning VLMs requires additional focus on data representation and preparation for images. This ensures the model effectively integrates and processes both visual and textual data for optimal performance. Given that the demo model, SmolVLM, is significantly larger than the language model used in the previous module, it's essential to explore methods for efficient fine-tuning. Techniques like quantization and PEFT can help make the process more accessible and cost-effective, allowing more users to experiment with the model. 18 | 19 | For detailed guidance on fine-tuning VLMs, visit the [VLM Fine-Tuning](./vlm_finetuning.md) page. 20 | 21 | 22 | ## Exercise Notebooks 23 | 24 | 25 | | Title | Description | Exercise | Link | Colab | 26 | |-------|-------------|----------|------|-------| 27 | | VLM Usage | Learn how to load and use a pre-trained VLM for various tasks | 🐢 Process an image
🐕 Process multiple images with batch handling
🦁 Process a full video| [Notebook](./notebooks/vlm_usage_sample.ipynb) | Open In Colab | 28 | | VLM Fine-Tuning | Learn how to fine-tune a pre-trained VLM for task-specific datasets | 🐢 Use a basic dataset for fine-tuning
🐕 Try a new dataset
🦁 Experiment with alternative fine-tuning methods | [Notebook](./notebooks/vlm_sft_sample.ipynb)| Open In Colab | 29 | 30 | 31 | ## References 32 | - [Hugging Face Learn: Supervised Fine-Tuning VLMs](https://huggingface.co/learn/cookbook/fine_tuning_vlm_trl) 33 | - [Hugging Face Learn: Supervised Fine-Tuning SmolVLM](https://huggingface.co/learn/cookbook/fine_tuning_smol_vlm_sft_trl) 34 | - [Hugging Face Learn: Preference Optimization Fine-Tuning SmolVLM](https://huggingface.co/learn/cookbook/fine_tuning_vlm_dpo_smolvlm_instruct) 35 | - [Hugging Face Blog: Preference Optimization for VLMs](https://huggingface.co/blog/dpo_vlm) 36 | - [Hugging Face Blog: Vision Language Models](https://huggingface.co/blog/vlms) 37 | - [Hugging Face Blog: SmolVLM](https://huggingface.co/blog/smolvlm) 38 | - [Hugging Face Model: SmolVLM-Instruct](https://huggingface.co/HuggingFaceTB/SmolVLM-Instruct) 39 | - [CLIP: Learning Transferable Visual Models from Natural Language Supervision](https://arxiv.org/abs/2103.00020) 40 | - [Align Before Fuse: Vision and Language Representation Learning with Momentum Distillation](https://arxiv.org/abs/2107.07651) 41 | -------------------------------------------------------------------------------- /5_vision_language_models/images/VLM_Architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/5_vision_language_models/images/VLM_Architecture.png -------------------------------------------------------------------------------- /5_vision_language_models/images/VLM_Process.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/5_vision_language_models/images/VLM_Process.png -------------------------------------------------------------------------------- /5_vision_language_models/images/VLM_Usage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/5_vision_language_models/images/VLM_Usage.png -------------------------------------------------------------------------------- /5_vision_language_models/vlm_usage.md: -------------------------------------------------------------------------------- 1 | # Visual Language Models 2 | 3 | Visual Language Models (VLMs) bridge the gap between images and text, enabling advanced tasks like generating image captions, answering questions based on visuals, or understanding the relationship between textual and visual data. Their architecture is designed to process both modalities seamlessly. 4 | 5 | ### Architecture 6 | 7 | VLMs combine image-processing components with text-generation models to achieve a unified understanding. The primary elements of their architecture are: 8 | 9 | ![VLM Architecture](./images/VLM_Architecture.png) 10 | 11 | - **Image Encoder**: Transforms raw images into compact numerical representations. Pretrained encoders such as CLIP or vision transformers (ViT) are commonly used. 12 | - **Embedding Projector**: Maps image features into a space compatible with textual embeddings, often using dense layers or linear transformations. 13 | - **Text Decoder**: Acts as the language-generation component, translating fused multimodal information into coherent text. Examples include generative models like Llama or Vicuna. 14 | - **Multimodal Projector**: Provides an additional layer to blend image and text representations. It is critical for models like LLaVA to establish stronger connections between the two modalities. 15 | 16 | Most VLMs leverage pretrained image encoders and text decoders and align them through additional fine-tuning on paired image-text datasets. This approach makes training efficient while allowing the models to generalize effectively. 17 | 18 | ### Usage 19 | 20 | ![VLM Process](./images/VLM_Process.png) 21 | 22 | VLMs are applied to a range of multimodal tasks. Their adaptability allows them to perform in diverse domains with varying levels of fine-tuning: 23 | 24 | - **Image Captioning**: Generating descriptions for images. 25 | - **Visual Question Answering (VQA)**: Answering questions about the content of an image. 26 | - **Cross-Modal Retrieval**: Finding corresponding text for a given image or vice versa. 27 | - **Creative Applications**: Assisting in design, art generation, or creating engaging multimedia content. 28 | 29 | ![VLM Usage](./images/VLM_Usage.png) 30 | 31 | Training and fine-tuning VLMs depend on high-quality datasets that pair images with text annotations. Tools like Hugging Face's `transformers` library provide convenient access to pretrained VLMs and streamlined workflows for custom fine-tuning. 32 | 33 | ### Chat Format 34 | 35 | Many VLMs are structured to interact in a chatbot-like manner, enhancing usability. This format includes: 36 | 37 | - A **system message** that sets the role or context for the model, such as "You are an assistant analyzing visual data." 38 | - **User queries** that combine text inputs and associated images. 39 | - **Assistant responses** that provide text outputs derived from the multimodal analysis. 40 | 41 | This conversational structure is intuitive and aligns with user expectations, especially for interactive applications like customer service or educational tools. 42 | 43 | Here’s an example of how a formatted input might look: 44 | 45 | ```json 46 | [ 47 | { 48 | "role": "system", 49 | "content": [{"type": "text", "text": "You are a Vision Language Model specialized in interpreting visual data from chart images..."}] 50 | }, 51 | { 52 | "role": "user", 53 | "content": [ 54 | {"type": "image", "image": ""}, 55 | {"type": "text", "text": "What is the highest value in the bar chart?"} 56 | ] 57 | }, 58 | { 59 | "role": "assistant", 60 | "content": [{"type": "text", "text": "42"}] 61 | } 62 | ] 63 | ``` 64 | 65 | **Working with Multiple Images and Videos** 66 | 67 | VLMs can also process multiple images or even videos by adapting the input structure to accommodate sequential or parallel visual inputs. For videos, frames can be extracted and processed as individual images, while maintaining temporal order. 68 | 69 | ## Resources 70 | 71 | - [Hugging Face Blog: Vision Language Models](https://huggingface.co/blog/vlms) 72 | - [Hugging Face Blog: SmolVLM](https://huggingface.co/blog/smolvlm) 73 | 74 | ## Next Steps 75 | 76 | ⏩ Try the [vlm_usage_sample.ipynb](./notebooks/vlm_usage_sample.ipynb) to try different usages of SMOLVLM. -------------------------------------------------------------------------------- /6_synthetic_datasets/README.md: -------------------------------------------------------------------------------- 1 | # Synthetic Datasets 2 | 3 | Synthetic data is artificially generated data that mimics real-world usage. It allows overcoming data limitations by expanding or enhancing datasets. Even though synthetic data was already used for some use cases, large language models have made synthetic datasets more popular for pre- and post-training, and the evaluation of language models. 4 | 5 | We'll use [`distilabel`](https://distilabel.argilla.io/latest/), a framework for synthetic data and AI feedback for engineers who need fast, reliable and scalable pipelines based on verified research papers. For a deeper dive into the package and best practices, check out the [documentation](https://distilabel.argilla.io/latest/). 6 | 7 | ## Module Overview 8 | 9 | Synthetic data for language models can be categorized into three taxonomies: instructions, preferences and critiques. We will focus on the first two categories, which focus on the generation of datasets for instruction tuning and preference alignment. In both categories, we will cover aspects of the third category, which focuses on improving existing data with model critiques and rewrites. 10 | 11 | ![Synthetic Data Taxonomies](./images/taxonomy-synthetic-data.png) 12 | 13 | ## Contents 14 | 15 | ### 1. [Instruction Datasets](./instruction_datasets.md) 16 | 17 | Learn how to generate instruction datasets for instruction tuning. We will explore creating instruction tuning datasets thorugh basic prompting and using prompts more refined techniques from papers. Instruction tuning datasets with seed data for in-context learning can be created through methods like SelfInstruct and Magpie. Additionally, we will explore instruction evolution through EvolInstruct. [Start learning](./instruction_datasets.md). 18 | 19 | ### 2. [Preference Datasets](./preference_datasets.md) 20 | 21 | Learn how to generate preference datasets for preference alignment. We will build on top of the methods and techniques introduced in section 1, by generating additional responses. Next, we will learn how to improve such responses with the EvolQuality prompt. Finally, we will explore how to evaluate responses with the the UltraFeedback prompt which will produce a score and critique, allowing us to create preference pairs. [Start learning](./preference_datasets.md). 22 | 23 | ### Exercise Notebooks 24 | 25 | | Title | Description | Exercise | Link | Colab | 26 | |-------|-------------|----------|------|-------| 27 | | Instruction Dataset | Generate a dataset for instruction tuning | 🐢 Generate an instruction tuning dataset
🐕 Generate a dataset for instruction tuning with seed data
🦁 Generate a dataset for instruction tuning with seed data and with instruction evolution | [Link](./notebooks/instruction_sft_dataset.ipynb) | [Colab](https://githubtocolab.com/huggingface/smol-course/tree/main/6_synthetic_datasets/notebooks/instruction_sft_dataset.ipynb) | 28 | | Preference Dataset | Generate a dataset for preference alignment | 🐢 Generate a preference alignment dataset
🐕 Generate a preference alignment dataset with response evolution
🦁 Generate a preference alignment dataset with response evolution and critiques | [Link](./notebooks/preference_alignment_dataset.ipynb) | [Colab](https://githubtocolab.com/huggingface/smol-course/tree/main/6_synthetic_datasets/notebooks/preference_alignment_dataset.ipynb) | 29 | 30 | ## Resources 31 | 32 | - [Distilabel Documentation](https://distilabel.argilla.io/latest/) 33 | - [Synthetic Data Generator is UI app](https://huggingface.co/blog/synthetic-data-generator) 34 | - [SmolTalk](https://huggingface.co/datasets/HuggingFaceTB/smoltalk) 35 | - [Self-instruct](https://arxiv.org/abs/2212.10560) 36 | - [Evol-Instruct](https://arxiv.org/abs/2304.12244) 37 | - [Magpie](https://arxiv.org/abs/2406.08464) 38 | - [UltraFeedback](https://arxiv.org/abs/2310.01377) 39 | - [Deita](https://arxiv.org/abs/2312.15685) 40 | -------------------------------------------------------------------------------- /6_synthetic_datasets/images/pipeline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/6_synthetic_datasets/images/pipeline.png -------------------------------------------------------------------------------- /6_synthetic_datasets/images/taxonomy-synthetic-data.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/6_synthetic_datasets/images/taxonomy-synthetic-data.png -------------------------------------------------------------------------------- /7_inference/README.md: -------------------------------------------------------------------------------- 1 | # Inference 2 | 3 | Inference is the process of using a trained language model to generate predictions or responses. While inference might seem straightforward, deploying models efficiently at scale requires careful consideration of various factors like performance, cost, and reliability. Large Language Models (LLMs) present unique challenges due to their size and computational requirements. 4 | 5 | We'll explore both simple and production-ready approaches using the [`transformers`](https://huggingface.co/docs/transformers/index) library and [`text-generation-inference`](https://github.com/huggingface/text-generation-inference), two popular frameworks for LLM inference. For production deployments, we'll focus on Text Generation Inference (TGI), which provides optimized serving capabilities. 6 | 7 | ## Module Overview 8 | 9 | LLM inference can be categorized into two main approaches: simple pipeline-based inference for development and testing, and optimized serving solutions for production deployments. We'll cover both approaches, starting with the simpler pipeline approach and moving to production-ready solutions. 10 | 11 | ## Contents 12 | 13 | ### 1. [Basic Pipeline Inference](./pipeline_inference.md) 14 | 15 | Learn how to use the Hugging Face Transformers pipeline for basic inference. We'll cover setting up pipelines, configuring generation parameters, and best practices for local development. The pipeline approach is perfect for prototyping and small-scale applications. [Start learning](./pipeline_inference.md). 16 | 17 | ### 2. [Production Inference with TGI](./tgi_inference.md) 18 | 19 | Learn how to deploy models for production using Text Generation Inference. We'll explore optimized serving techniques, batching strategies, and monitoring solutions. TGI provides production-ready features like health checks, metrics, and Docker deployment options. [Start learning](./text_generation_inference.md). 20 | 21 | ### Exercise Notebooks 22 | 23 | | Title | Description | Exercise | Link | Colab | 24 | |-------|-------------|----------|------|-------| 25 | | Pipeline Inference | Basic inference with transformers pipeline | 🐢 Set up a basic pipeline
🐕 Configure generation parameters
🦁 Create a simple web server | [Link](./notebooks/basic_pipeline_inference.ipynb) | [Colab](https://githubtocolab.com/huggingface/smol-course/tree/main/7_inference/notebooks/basic_pipeline_inference.ipynb) | 26 | | TGI Deployment | Production deployment with TGI | 🐢 Deploy a model with TGI
🐕 Configure performance optimizations
🦁 Set up monitoring and scaling | [Link](./notebooks/tgi_deployment.ipynb) | [Colab](https://githubtocolab.com/huggingface/smol-course/tree/main/7_inference/notebooks/tgi_deployment.ipynb) | 27 | 28 | ## Resources 29 | 30 | - [Hugging Face Pipeline Tutorial](https://huggingface.co/docs/transformers/en/pipeline_tutorial) 31 | - [Text Generation Inference Documentation](https://huggingface.co/docs/text-generation-inference/en/index) 32 | - [Pipeline WebServer Guide](https://huggingface.co/docs/transformers/en/pipeline_tutorial#using-pipelines-for-a-webserver) 33 | - [TGI GitHub Repository](https://github.com/huggingface/text-generation-inference) 34 | - [Hugging Face Model Deployment Documentation](https://huggingface.co/docs/inference-endpoints/index) 35 | - [vLLM: High-throughput LLM Serving](https://github.com/vllm-project/vllm) 36 | - [Optimizing Transformer Inference](https://huggingface.co/blog/optimize-transformer-inference) 37 | -------------------------------------------------------------------------------- /8_agents/README.md: -------------------------------------------------------------------------------- 1 | # Agents 2 | 3 | AI Agents are autonomous systems that can understand user requests, break them down into steps, and execute actions to accomplish tasks. They combine language models with tools and external functions to interact with their environment. This module covers how to build effective agents using the [`smolagents`](https://github.com/huggingface/smolagents) library, which provides a lightweight framework for creating capable AI agents. 4 | 5 | ## Module Overview 6 | 7 | Building effective agents requires understanding three key components. First, retrieval capabilities allow agents to access and use relevant information from various sources. Second, function calling enables agents to take concrete actions in their environment. Finally, domain-specific knowledge and tooling equip agents for specialized tasks like code manipulation. 8 | 9 | ## Contents 10 | 11 | ### 1️⃣ [Retrieval Agents](./retrieval_agents.md) 12 | 13 | Retrieval agents combine models with knowledge bases. These agents can search and synthesize information from multiple sources, leveraging vector stores for efficient retrieval and implementing RAG (Retrieval Augmented Generation) patterns. They are great at combining web search with custom knowledge bases while maintaining conversation context through memory systems. The module covers implementation strategies including fallback mechanisms for robust information retrieval. 14 | 15 | ### 2️⃣ [Code Agents](./code_agents.md) 16 | 17 | Code agents are specialized autonomous systems designed for software development tasks. These agents excel at analyzing and generating code, performing automated refactoring, and integrating with development tools. The module covers best practices for building code-focused agents that can understand programming languages, work with build systems, and interact with version control while maintaining high code quality standards. 18 | 19 | ### 3️⃣ [Custom Functions](./custom_functions.md) 20 | 21 | Custom function agents extend basic AI capabilities through specialized function calls. This module explores how to design modular and extensible function interfaces that integrate directly with your application's logic. You'll learn to implement proper validation and error handling while creating reliable function-driven workflows. The focus is on building simple systems where agents can predictably interact with external tools and services. 22 | 23 | ### Exercise Notebooks 24 | 25 | | Title | Description | Exercise | Link | Colab | 26 | |-------|-------------|----------|------|-------| 27 | | Building a Research Agent | Create an agent that can perform research tasks using retrieval and custom functions | 🐢 Build a simple RAG agent
🐕 Add custom search functions
🦁 Create a full research assistant | [Notebook](./notebooks/agents.ipynb) | Open In Colab | 28 | 29 | ## Resources 30 | 31 | - [smolagents Documentation](https://huggingface.co/docs/smolagents) - Official docs for the smolagents library 32 | - [Building Effective Agents](https://www.anthropic.com/research/building-effective-agents) - Research paper on agent architectures 33 | - [Agent Guidelines](https://huggingface.co/docs/smolagents/tutorials/building_good_agents) - Best practices for building reliable agents 34 | - [LangChain Agents](https://python.langchain.com/docs/how_to/#agents) - Additional examples of agent implementations 35 | - [Function Calling Guide](https://platform.openai.com/docs/guides/function-calling) - Understanding function calling in LLMs 36 | - [RAG Best Practices](https://www.pinecone.io/learn/retrieval-augmented-generation/) - Guide to implementing effective RAG 37 | -------------------------------------------------------------------------------- /8_agents/code_agents.md: -------------------------------------------------------------------------------- 1 | # Code Agents 2 | 3 | Code agents are specialized autonomous systems that handle coding tasks like analysis, generation, refactoring, and testing. These agents leverage domain knowledge about programming languages, build systems, and version control to enhance software development workflows. 4 | 5 | ## Why Code Agents? 6 | 7 | Code agents accelerate development by automating repetitive tasks while maintaining code quality. They excel at generating boilerplate code, performing systematic refactoring, and identifying potential issues through static analysis. The agents combine retrieval capabilities to access external documentation and repositories with function calling to execute concrete actions like creating files or running tests. 8 | 9 | ## Building Blocks of a Code Agent 10 | 11 | Code agents are built on specialized language models fine-tuned for code understanding. These models are augmented with development tools like linters, formatters, and compilers to interact with real-world environments. Through retrieval techniques, agents maintain contextual awareness by accessing documentation and code histories to align with organizational patterns and standards. Action-oriented functions enable agents to perform concrete tasks such as committing changes or initiating merge requests. 12 | 13 | In the following example, we create a code agent that can search the web using DuckDuckGo much like the retrieval agent we built earlier. 14 | 15 | ```python 16 | from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel 17 | 18 | agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=HfApiModel()) 19 | 20 | agent.run("How many seconds would it take for a leopard at full speed to run through Pont des Arts?") 21 | ``` 22 | 23 | In the following example, we create a code agent that can get the travel time between two locations. Here, we use the `@tool` decorator to define a custom function that can be used as a tool. 24 | 25 | ```python 26 | from smolagents import CodeAgent, HfApiModel, tool 27 | 28 | @tool 29 | def get_travel_duration(start_location: str, destination_location: str, departure_time: Optional[int] = None) -> str: 30 | """Gets the travel time in car between two places. 31 | 32 | Args: 33 | start_location: the place from which you start your ride 34 | destination_location: the place of arrival 35 | departure_time: the departure time, provide only a `datetime.datetime` if you want to specify this 36 | """ 37 | import googlemaps # All imports are placed within the function, to allow for sharing to Hub. 38 | import os 39 | 40 | gmaps = googlemaps.Client(os.getenv("GMAPS_API_KEY")) 41 | 42 | if departure_time is None: 43 | from datetime import datetime 44 | departure_time = datetime(2025, 1, 6, 11, 0) 45 | 46 | directions_result = gmaps.directions( 47 | start_location, 48 | destination_location, 49 | mode="transit", 50 | departure_time=departure_time 51 | ) 52 | return directions_result[0]["legs"][0]["duration"]["text"] 53 | 54 | agent = CodeAgent(tools=[get_travel_duration], model=HfApiModel(), additional_authorized_imports=["datetime"]) 55 | 56 | agent.run("Can you give me a nice one-day trip around Paris with a few locations and the times? Could be in the city or outside, but should fit in one day. I'm travelling only via public transportation.") 57 | 58 | ``` 59 | 60 | These examples are just the beginning of what you can do with code agents. You can learn more about how to build code agents in the [smolagents documentation](https://huggingface.co/docs/smolagents). 61 | 62 | smolagents provides a lightweight framework for building code agents, with a core implementation of approximately 1,000 lines of code. The framework specializes in agents that write and execute Python code snippets, offering sandboxed execution for security. It supports both open-source and proprietary language models, making it adaptable to various development environments. 63 | 64 | ## Further Reading 65 | 66 | - [smolagents Blog](https://huggingface.co/blog/smolagents) - Introduction to smolagents and code interactions 67 | - [smolagents: Building Good Agents](https://huggingface.co/docs/smolagents/tutorials/building_good_agents) - Best practices for reliable agents 68 | - [Building Effective Agents - Anthropic](https://www.anthropic.com/research/building-effective-agents) - Agent design principles 69 | -------------------------------------------------------------------------------- /8_agents/custom_functions.md: -------------------------------------------------------------------------------- 1 | # Custom Function Agents 2 | 3 | Custom Function Agents are AI agents that leverage specialized function calls (or “tools”) to perform tasks. Unlike general-purpose agents, Custom Function Agents focus on powering advanced workflows by integrating directly with your application's logic. For example, you can expose database queries, system commands, or any custom utility as isolated functions for the agent to invoke. 4 | 5 | ## Why Custom Function Agents? 6 | 7 | - **Modular and Extensible**: Instead of building one monolithic agent, you can design individual functions that represent discrete capabilities, making your architecture more extensible. 8 | - **Fine-Grained Control**: Developers can carefully control the agent’s actions by specifying exactly which functions are available and what parameters they accept. 9 | - **Improved Reliability**: By structuring each function with clear schemas and validations, you reduce errors and unexpected behaviors. 10 | 11 | ## Basic Workflow 12 | 13 | 1. **Identify Functions** 14 | Determine which tasks can be transformed into custom functions (e.g., file I/O, database queries, streaming data processing). 15 | 16 | 2. **Define the Interface** 17 | Use a function signature or schema that precisely outlines each function’s inputs, outputs, and expected behavior. This enforces strong contracts between your agent and its environment. 18 | 19 | 3. **Register with the Agent** 20 | Your agent needs to “learn” which functions are available. Typically, you pass metadata describing each function’s interface to the language model or agent framework. 21 | 22 | 4. **Invoke and Validate** 23 | Once the agent selects a function to call, run the function with the provided arguments and validate the results. If valid, feed the results back to the agent for context to drive subsequent decisions. 24 | 25 | ## Example 26 | 27 | Below is a simplified example demonstrating how custom function calls might look in pseudocode. The objective is to perform a user-defined search and retrieve relevant content: 28 | 29 | ```python 30 | # Define a custom function with clear input/output types 31 | def search_database(query: str) -> list: 32 | """ 33 | Search the database for articles matching the query. 34 | 35 | Args: 36 | query (str): The search query string 37 | 38 | Returns: 39 | list: List of matching article results 40 | """ 41 | try: 42 | results = database.search(query) 43 | return results 44 | except DatabaseError as e: 45 | logging.error(f"Database search failed: {e}") 46 | return [] 47 | 48 | # Register the function with the agent 49 | agent.register_function( 50 | name="search_database", 51 | function=search_database, 52 | description="Searches database for articles matching a query" 53 | ) 54 | 55 | # Example usage 56 | def process_search(): 57 | query = "Find recent articles on AI" 58 | results = agent.invoke("search_database", query) 59 | 60 | if results: 61 | agent.process_results(results) 62 | else: 63 | logging.info("No results found for query") 64 | ``` 65 | 66 | ## Further Reading 67 | 68 | - [smolagents Blog](https://huggingface.co/blog/smolagents) - Learn about the latest advancements in AI agents and how they can be applied to custom function agents. 69 | - [Building Good Agents](https://huggingface.co/docs/smolagents/tutorials/building_good_agents) - A comprehensive guide on best practices for developing reliable and effective custom function agents. -------------------------------------------------------------------------------- /banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/banner.png -------------------------------------------------------------------------------- /es/1_instruction_tuning/README.md: -------------------------------------------------------------------------------- 1 | # Ajuste por Instrucciones (Instruction Tuning) 2 | 3 | Este módulo te guiará en el proceso de ajuste por instrucciones de modelos de lenguaje. El ajuste por instrucciones implica adaptar modelos preentrenados a tareas específicas mediante un entrenamiento adicional sobre conjuntos de datos específicos para esas tareas. Este proceso ayuda a los modelos a mejorar su rendimiento en tareas específicas. 4 | 5 | En este módulo, exploraremos dos temas: 1) Plantillas de Chat y 2) Fine-tuning Supervisado 6 | 7 | ## 1️⃣ Plantillas de Chat 8 | 9 | Las plantillas de chat estructuran las interacciones entre los usuarios y los modelos de IA, asegurando respuestas coherentes y contextualmente apropiadas. Estas plantillas incluyen componentes como los mensajes de sistema y mensajes basados en roles. Para más información detallada, consulta la sección de [Plantillas de Chat](./chat_templates.md). 10 | 11 | ## 2️⃣ Fine-tuning Supervisado 12 | 13 | El Fine-tuning supervisado (SFT) es un proceso crítico para adaptar modelos de lenguaje preentrenados a tareas específicas. Implica entrenar el modelo en un conjunto de datos específico para la tarea con ejemplos etiquetados. Para una guía detallada sobre el SFT, incluyendo pasos clave y mejores prácticas, consulta la página de [Fine-tuning Supervisado](./supervised_fine_tuning.md). 14 | 15 | ## Cuadernos de Ejercicio 16 | 17 | | Título | Descripción | Ejercicio | Enlace | Colab | 18 | |--------|-------------|-----------|--------|-------| 19 | | Plantillas de Chat | Aprende a usar plantillas de chat con SmolLM2 y a procesar conjuntos de datos en formato chatml | 🐢 Convierte el conjunto de datos `HuggingFaceTB/smoltalk` al formato chatml
🐕 Convierte el conjunto de datos `openai/gsm8k` al formato chatml | [Cuaderno](./notebooks/chat_templates_example.ipynb) | Abrir en Colab | 20 | | Fine-tuning Supervisado | Aprende a afinar SmolLM2 utilizando el SFTTrainer | 🐢 Usa el conjunto de datos `HuggingFaceTB/smoltalk`
🐕 Prueba el conjunto de datos `bigcode/the-stack-smol`
🦁 Selecciona un conjunto de datos para un caso de uso real | [Cuaderno](./notebooks/sft_finetuning_example.ipynb) | Abrir en Colab | 21 | 22 | ## Referencias 23 | 24 | - [Documentación de Transformers sobre plantillas de chat](https://huggingface.co/docs/transformers/main/en/chat_templating) 25 | - [Script para Fine-Tuning Supervisado en TRL](https://github.com/huggingface/trl/blob/main/examples/scripts/sft.py) 26 | - [`SFTTrainer` en TRL](https://huggingface.co/docs/trl/main/en/sft_trainer) 27 | - [Papel de Optimización Directa de Preferencias](https://arxiv.org/abs/2305.18290) 28 | - [Fine-Tuning Supervisado con TRL](https://huggingface.co/docs/trl/main/en/tutorials/supervised_finetuning) 29 | - [Cómo afinar Google Gemma con ChatML y Hugging Face TRL](https://www.philschmid.de/fine-tune-google-gemma) 30 | - [Fine-Tuning de LLM para generar catálogos de productos persas en formato JSON](https://huggingface.co/learn/cookbook/en/fine_tuning_llm_to_generate_persian_product_catalogs_in_json_format) 31 | -------------------------------------------------------------------------------- /es/1_instruction_tuning/notebooks/.env.example: -------------------------------------------------------------------------------- 1 | # Duplica este archivo con el nombre .env y rellena con tus claves secretas. 2 | HF_TOKEN= 3 | -------------------------------------------------------------------------------- /es/4_evaluation/README.md: -------------------------------------------------------------------------------- 1 | # Evaluación 2 | 3 | La evaluación es un paso crítico en el desarrollo y despliegue de modelos de lenguaje. Nos permite entender qué tan bien funcionan nuestros modelos en diferentes capacidades e identificar áreas de mejora. Este módulo cubre tanto los "becnhmarks" estándares como los enfoques de evaluación específicos para evaluar de manera integral tu modelo **smol**. 4 | 5 | Usaremos [`lighteval`](https://github.com/huggingface/lighteval), una poderosa biblioteca de evaluación desarrollada por Hugging Face que se integra perfectamente con el ecosistema de Hugging Face. Para una explicación más detallada sobre los conceptos y mejores prácticas de evaluación, consulta la [guía de evaluación](https://github.com/huggingface/evaluation-guidebook). 6 | 7 | ## Descripción del Módulo 8 | 9 | Una estrategia de evaluación completa examina múltiples aspectos del rendimiento del modelo. Evaluamos capacidades específicas en tareas como responder preguntas y resumir textos, para entender cómo el modelo maneja diferentes tipos de problemas. Medimos la calidad del "output" mediante factores como coherencia y precisión. A su vez, la evaluación de seguridad ayuda a identificar posibles "outputs" dañinas o sesgos. Finalmente, las pruebas de experticia en áreas especfícios verifican el conocimiento especializado del modelo en tu campo objetivo. 10 | 11 | ## Contenidos 12 | 13 | ### 1️⃣ [Evaluaciones Automáticas](./automatic_benchmarks.md) 14 | Aprende a evaluar tu modelo utilizando "benchmarks" y métricas estandarizadas. Exploraremos "benchmarks" comunes como MMLU y TruthfulQA, entenderemos las métricas clave de evaluación y configuraciones, y cubriremos mejores prácticas para una evaluación reproducible. 15 | 16 | ### 2️⃣ [Evaluación Personalizada en un Dominio](./custom_evaluation.md) 17 | Descubre cómo crear flujos de evaluación adaptados a tus casos de uso específicos. Te guiaremos en el diseño de tareas de evaluación personalizadas, la implementación de métricas especializadas y la construcción de conjuntos de datos de evaluación que se ajusten a tus necesidades. 18 | 19 | ### 3️⃣ [Proyecto de Evaluación en un Dominio](./project/README.md) 20 | Sigue un ejemplo completo de cómo construir un flujo de evaluación específico para un dominio. Aprenderás a generar conjuntos de datos de evaluación, usar Argilla para la anotación de datos, crear conjuntos de datos estandarizados y evaluar modelos utilizando LightEval. 21 | 22 | ### Cuadernos de Ejercicios 23 | 24 | | Título | Descripción | Ejercicio | Enlace | Colab | 25 | |--------|-------------|----------|-------|-------| 26 | | Evalúa y analiza tu LLM | Aprende a usar LightEval para evaluar y comparar modelos en dominios específicos | 🐢 Usa tareas del dominio médico para evaluar un modelo
🐕 Crea una evaluación de dominio con diferentes tareas MMLU
🦁 Diseña una tarea de evaluación personalizada para tu dominio | [Cuaderno](./notebooks/lighteval_evaluate_and_analyse_your_LLM.ipynb) | Open In Colab | 27 | 28 | ## Recursos 29 | 30 | - [Guía de Evaluación](https://github.com/huggingface/evaluation-guidebook) - Guía completa para la evaluación de modelos de lenguaje 31 | - [Documentación de LightEval](https://github.com/huggingface/lighteval) - Documentación oficial de la biblioteca LightEval 32 | - [Documentación de Argilla](https://docs.argilla.io) - Aprende sobre la plataforma de anotación Argilla 33 | - [Paper de MMLU](https://arxiv.org/abs/2009.03300) - Artículo sobre el benchmark MMLU 34 | - [Crear una Tarea Personalizada](https://github.com/huggingface/lighteval/wiki/Adding-a-Custom-Task) 35 | - [Crear una Métrica Personalizada](https://github.com/huggingface/lighteval/wiki/Adding-a-New-Metric) 36 | - [Usar métricas existentes](https://github.com/huggingface/lighteval/wiki/Metric-List) 37 | -------------------------------------------------------------------------------- /es/4_evaluation/project/annotate_dataset.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import json 3 | from random import choices, sample 4 | 5 | import argilla as rg 6 | from distilabel.distiset import Distiset 7 | 8 | ################################################################################ 9 | # Script Parameters 10 | ################################################################################ 11 | 12 | parser = argparse.ArgumentParser( 13 | description="Annotate exam questions dataset using Argilla." 14 | ) 15 | parser.add_argument( 16 | "--argilla_api_key", 17 | type=str, 18 | default="argilla.apikey", 19 | help="API key for Argilla", 20 | ) 21 | parser.add_argument( 22 | "--argilla_api_url", 23 | type=str, 24 | default="http://localhost:6900", 25 | help="API URL for Argilla", 26 | ) 27 | parser.add_argument( 28 | "--dataset_path", 29 | type=str, 30 | default="exam_questions", 31 | help="Path to the exam questions dataset", 32 | ) 33 | parser.add_argument( 34 | "--dataset_config", 35 | type=str, 36 | default="default", 37 | help="Configuration of the dataset", 38 | ) 39 | parser.add_argument( 40 | "--dataset_split", 41 | type=str, 42 | default="train", 43 | help="Split of the dataset to use", 44 | ) 45 | parser.add_argument( 46 | "--output_dataset_name", 47 | type=str, 48 | default="exam_questions", 49 | help="Name of the output Argilla dataset", 50 | ) 51 | 52 | args = parser.parse_args() 53 | 54 | ################################################################################ 55 | # Create Argilla dataset with the feedback task for validation 56 | ################################################################################ 57 | 58 | client = rg.Argilla(api_key=args.argilla_api_key, api_url=args.argilla_api_url) 59 | 60 | if client.datasets(args.output_dataset_name): 61 | print(f"Deleting existing dataset '{args.output_dataset_name}'") 62 | client.datasets(args.output_dataset_name).delete() 63 | 64 | settings = rg.Settings( 65 | fields=[ 66 | rg.TextField("question"), 67 | rg.TextField("answer_a"), 68 | rg.TextField("answer_b"), 69 | rg.TextField("answer_c"), 70 | rg.TextField("answer_d"), 71 | ], 72 | questions=[ 73 | rg.LabelQuestion( 74 | name="correct_answer", 75 | labels=["answer_a", "answer_b", "answer_c", "answer_d"], 76 | ), 77 | rg.TextQuestion( 78 | name="improved_question", 79 | description="Could you improve the question?", 80 | ), 81 | rg.TextQuestion( 82 | name="improved_answer", 83 | description="Could you improve the best answer?", 84 | ), 85 | ], 86 | ) 87 | 88 | dataset = rg.Dataset(settings=settings, name=args.output_dataset_name) 89 | dataset.create() 90 | 91 | ################################################################################ 92 | # Load the Distiset and process and add records to Argilla dataset 93 | # We will validate that questions appear in random order to avoid bias 94 | # but we will show correct answers in the Argilla UI as suggestions. 95 | ################################################################################ 96 | 97 | distiset = Distiset.load_from_disk(args.dataset_path) 98 | answer_names = ["answer_a", "answer_b", "answer_c", "answer_d"] 99 | dataset_records = [] 100 | 101 | for exam in distiset[args.dataset_config][args.dataset_split]: 102 | exam_json = json.loads(exam["generation"])["exam"] 103 | 104 | for question in exam_json: 105 | answer = question["answer"] 106 | distractors = question["distractors"] 107 | distractors = choices(distractors, k=3) 108 | answers = distractors + [answer] 109 | answers = sample(answers, len(answers)) 110 | suggestion_idx = answers.index(answer) 111 | fields = dict(zip(answer_names, answers)) 112 | fields["question"] = question["question"] 113 | 114 | record = rg.Record( 115 | fields=fields, 116 | suggestions=[ 117 | rg.Suggestion( 118 | question_name="correct_answer", 119 | value=answer_names[suggestion_idx], 120 | ) 121 | ], 122 | ) 123 | dataset_records.append(record) 124 | 125 | dataset.records.log(dataset_records) 126 | 127 | print( 128 | f"Dataset '{args.output_dataset_name}' has been created and populated in Argilla." 129 | ) 130 | -------------------------------------------------------------------------------- /es/4_evaluation/project/create_dataset.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | import argilla as rg 4 | from datasets import Dataset 5 | 6 | ################################################################################ 7 | # Script Parameters 8 | ################################################################################ 9 | 10 | parser = argparse.ArgumentParser( 11 | description="Create a Hugging Face dataset from annotated Argilla data." 12 | ) 13 | parser.add_argument( 14 | "--argilla_api_key", 15 | type=str, 16 | default="argilla.apikey", 17 | help="API key for Argilla", 18 | ) 19 | parser.add_argument( 20 | "--argilla_api_url", 21 | type=str, 22 | default="http://localhost:6900", 23 | help="API URL for Argilla", 24 | ) 25 | parser.add_argument( 26 | "--dataset_path", 27 | type=str, 28 | default="exam_questions", 29 | help="Path to the Argilla dataset", 30 | ) 31 | parser.add_argument( 32 | "--dataset_repo_id", 33 | type=str, 34 | default="burtenshaw/exam_questions", 35 | help="Hugging Face dataset repository ID", 36 | ) 37 | 38 | args = parser.parse_args() 39 | 40 | ################################################################################ 41 | # Initialize Argilla client and load dataset 42 | ################################################################################ 43 | 44 | client = rg.Argilla(api_key=args.argilla_api_key, api_url=args.argilla_api_url) 45 | dataset = client.datasets(args.dataset_path) 46 | 47 | ################################################################################ 48 | # Process Argilla records 49 | ################################################################################ 50 | 51 | dataset_rows = [] 52 | 53 | for record in dataset.records(with_suggestions=True, with_responses=True): 54 | row = record.fields 55 | 56 | if len(record.responses) == 0: 57 | answer = record.suggestions["correct_answer"].value 58 | row["correct_answer"] = answer 59 | else: 60 | for response in record.responses: 61 | if response.question_name == "correct_answer": 62 | row["correct_answer"] = response.value 63 | dataset_rows.append(row) 64 | 65 | ################################################################################ 66 | # Create Hugging Face dataset and push to Hub 67 | ################################################################################ 68 | 69 | hf_dataset = Dataset.from_list(dataset_rows) 70 | hf_dataset.push_to_hub(repo_id=args.dataset_repo_id) 71 | 72 | print(f"Dataset has been successfully pushed to {args.dataset_repo_id}") 73 | -------------------------------------------------------------------------------- /es/4_evaluation/project/evaluation_task.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | from lighteval.tasks.lighteval_task import LightevalTaskConfig 4 | from lighteval.tasks.requests import Doc 5 | from lighteval.metrics.utils.metric_utils import ( 6 | SampleLevelMetric, 7 | MetricCategory, 8 | MetricUseCase, 9 | ) 10 | 11 | ################################################################################ 12 | # Define the prompt function based on the structure of the dataset 13 | ################################################################################ 14 | 15 | 16 | def prompt_fn(line, task_name: str = None): 17 | """Converts a dataset line to a Doc object for evaluation.""" 18 | instruction = "Choose the correct answer for the following exam question:" 19 | return Doc( 20 | task_name=task_name, 21 | query=f"{instruction} {line['question']}", 22 | choices=[ 23 | f" {line['answer_a']}", 24 | f" {line['answer_b']}", 25 | f" {line['answer_c']}", 26 | f" {line['answer_d']}", 27 | ], 28 | gold_index=["answer_a", "answer_b", "answer_c", "answer_d"].index( 29 | line["correct_answer"] 30 | ), 31 | instruction=instruction, 32 | ) 33 | 34 | 35 | ################################################################################ 36 | # Define the custom metric based on guide here https://github.com/huggingface/lighteval/wiki/Adding-a-New-Metric 37 | # Or use an existing metric based on the guide here: https://github.com/huggingface/lighteval/wiki/Metric-List 38 | # Existing metrics can be imported from lighteval.metrics.metrics 39 | ################################################################################ 40 | 41 | 42 | def sample_level_fn(formatted_doc: Doc, **kwargs) -> bool: 43 | response = np.argmin(kwargs["choices_logprob"]) 44 | return response == formatted_doc.gold_index 45 | 46 | 47 | custom_metric = SampleLevelMetric( 48 | metric_name="exam_question_accuracy", 49 | higher_is_better=True, 50 | category=MetricCategory.MULTICHOICE, 51 | use_case=MetricUseCase.NONE, 52 | sample_level_fn=sample_level_fn, 53 | corpus_level_fn=np.mean, 54 | ) 55 | 56 | ################################################################################ 57 | # Define the task based on the prompt function and the custom metric 58 | # Based on the guide here: https://github.com/huggingface/lighteval/wiki/Adding-a-Custom-Task 59 | ################################################################################ 60 | 61 | task = LightevalTaskConfig( 62 | name="example", 63 | prompt_function=prompt_fn, 64 | suite=["community"], 65 | hf_repo="burtenshaw/exam_questions", 66 | hf_subset="default", 67 | hf_avail_splits=["train"], 68 | evaluation_splits=["train"], 69 | few_shots_split=None, 70 | few_shots_select=None, 71 | metric=[custom_metric], 72 | ) 73 | 74 | # Add the task to TASKS_TABLE 75 | TASKS_TABLE = [task] 76 | 77 | # MODULE LOGIC 78 | if __name__ == "__main__": 79 | print([t.name for t in TASKS_TABLE]) 80 | print(len(TASKS_TABLE)) 81 | 82 | # lighteval accelerate \ 83 | # "pretrained=HuggingFaceTB/SmolLM2-135M-Instruct" \ 84 | # "community|example|0|0" \ 85 | # --custom-tasks "submitted_tasks/example.py" \ 86 | # --output-dir "results" 87 | -------------------------------------------------------------------------------- /es/4_evaluation/project/images/domain_eval_argilla_view.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/es/4_evaluation/project/images/domain_eval_argilla_view.png -------------------------------------------------------------------------------- /es/4_evaluation/project/images/domain_eval_dataset_viewer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/es/4_evaluation/project/images/domain_eval_dataset_viewer.png -------------------------------------------------------------------------------- /es/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/es/banner.png -------------------------------------------------------------------------------- /ja/1_instruction_tuning/README.md: -------------------------------------------------------------------------------- 1 | # インストラクションチューニング 2 | 3 | このモジュールでは、言語モデルのインストラクションチューニングのプロセスをガイドします。インストラクションチューニングとは、特定のタスクに対してモデルを適応させるために、特定のタスクに関連するデータセットで追加のトレーニングを行うことを指します。このプロセスは、特定のタスクにおけるモデルのパフォーマンスを向上させるのに役立ちます。 4 | 5 | このモジュールでは、2つのトピックを探ります:1) チャットテンプレートと2) 教師あり微調整 6 | 7 | ## 1️⃣ チャットテンプレート 8 | 9 | チャットテンプレートは、ユーザーとAIモデル間のインタラクションを構造化し、一貫性のある文脈に適した応答を保証します。これらのテンプレートには、システムメッセージや役割に基づくメッセージなどのコンポーネントが含まれます。詳細については、[チャットテンプレート](./chat_templates.md)セクションを参照してください。 10 | 11 | ## 2️⃣ 教師あり微調整 12 | 13 | 教師あり微調整(SFT)は、事前トレーニングされた言語モデルを特定のタスクに適応させるための重要なプロセスです。これは、ラベル付きの例を含む特定のタスクのデータセットでモデルをトレーニングすることを含みます。SFTの詳細なガイド、重要なステップ、およびベストプラクティスについては、[教師あり微調整](./supervised_fine_tuning.md)ページを参照してください。 14 | 15 | ## 演習ノートブック 16 | 17 | | タイトル | 説明 | 演習 | リンク | Colab | 18 | |--------|-------------|-----------|--------|-------| 19 | | チャットテンプレート | SmolLM2を使用してチャットテンプレートを使用し、チャットml形式のデータセットを処理する方法を学びます | 🐢 `HuggingFaceTB/smoltalk`データセットをchatml形式に変換
🐕 `openai/gsm8k`データセットをchatml形式に変換 | [ノートブック](./notebooks/chat_templates_example.ipynb) | Open In Colab | 20 | | 教師あり微調整 | SFTTrainerを使用してSmolLM2を微調整する方法を学びます | 🐢 `HuggingFaceTB/smoltalk`データセットを使用
🐕 `bigcode/the-stack-smol`データセットを試す
🦁 実際の使用ケースに関連するデータセットを選択 | [ノートブック](./notebooks/sft_finetuning_example.ipynb) | Open In Colab | 21 | 22 | ## 参考文献 23 | 24 | - [Transformersのチャットテンプレートに関するドキュメント](https://huggingface.co/docs/transformers/main/en/chat_templating) 25 | - [TRLの教師あり微調整スクリプト](https://github.com/huggingface/trl/blob/main/examples/scripts/sft.py) 26 | - [TRLの`SFTTrainer`](https://huggingface.co/docs/trl/main/en/sft_trainer) 27 | - [直接選好最適化に関する論文](https://arxiv.org/abs/2305.18290) 28 | - [TRLを使用した教師あり微調整](https://huggingface.co/docs/trl/main/en/tutorials/supervised_fine_tuning) 29 | - [ChatMLとHugging Face TRLを使用したGoogle Gemmaの微調整方法](https://www.philschmid.de/fine-tune-google-gemma) 30 | - [LLMを微調整してペルシャ語の商品カタログをJSON形式で生成する方法](https://huggingface.co/learn/cookbook/en/fine_tuning_llm_to_generate_persian_product_catalogs_in_json_format) 31 | -------------------------------------------------------------------------------- /ja/1_instruction_tuning/chat_templates.md: -------------------------------------------------------------------------------- 1 | # チャットテンプレート 2 | 3 | チャットテンプレートは、言語モデルとユーザー間のインタラクションを構造化するために不可欠です。これらは会話の一貫した形式を提供し、モデルが各メッセージの文脈と役割を理解し、適切な応答パターンを維持することを保証します。 4 | 5 | ## ベースモデル vs インストラクションモデル 6 | 7 | ベースモデルは次のトークンを予測するために生のテキストデータでトレーニングされる一方、インストラクションモデルは特定の指示に従い会話に参加するように微調整されたモデルです。例えば、`SmolLM2-135M`はベースモデルであり、`SmolLM2-135M-Instruct`はその指示に特化したバリアントです。 8 | 9 | ベースモデルをインストラクションモデルのように動作させるためには、モデルが理解できるようにプロンプトを一貫してフォーマットする必要があります。ここでチャットテンプレートが役立ちます。ChatMLは、システム、ユーザー、アシスタントの役割を明確に示すテンプレート形式で会話を構造化します。 10 | 11 | ベースモデルは異なるチャットテンプレートで微調整される可能性があるため、インストラクションモデルを使用する際には、正しいチャットテンプレートを使用していることを確認する必要があります。 12 | 13 | ## チャットテンプレートの理解 14 | 15 | チャットテンプレートの核心は、言語モデルと通信する際に会話がどのようにフォーマットされるべきかを定義することです。これには、システムレベルの指示、ユーザーメッセージ、およびアシスタントの応答が含まれ、モデルが理解できる構造化された形式で提供されます。この構造は、インタラクションの一貫性を維持し、モデルがさまざまな種類の入力に適切に応答することを保証します。以下はチャットテンプレートの例です: 16 | 17 | ```sh 18 | <|im_end|>ユーザー 19 | こんにちは!<|im_end|> 20 | <|im_end|>アシスタント 21 | はじめまして!<|im_end|> 22 | <|im_end|>ユーザー 23 | 質問してもいいですか?<|im_end|> 24 | <|im_end|>アシスタント 25 | ``` 26 | 27 | `transformers`ライブラリは、モデルのトークナイザーに関連してチャットテンプレートを自動的に処理します。`transformers`でチャットテンプレートがどのように構築されるかについて詳しくは[こちら](https://huggingface.co/docs/transformers/en/chat_templating#how-do-i-use-chat-templates)を参照してください。私たちはメッセージを正しい形式で構造化するだけで、残りはトークナイザーが処理します。以下は基本的な会話の例です: 28 | 29 | ```python 30 | messages = [ 31 | {"role": "system", "content": "あなたは技術的なトピックに焦点を当てた役立つアシスタントです。"}, 32 | {"role": "user", "content": "チャットテンプレートとは何か説明できますか?"}, 33 | {"role": "assistant", "content": "チャットテンプレートは、ユーザーとAIモデル間の会話を構造化します..."} 34 | ] 35 | ``` 36 | 37 | 上記の例を分解して、チャットテンプレート形式にどのようにマッピングされるかを見てみましょう。 38 | 39 | ## システムメッセージ 40 | 41 | システムメッセージは、モデルの動作の基礎を設定します。これらは、以降のすべてのインタラクションに影響を与える持続的な指示として機能します。例えば: 42 | 43 | ```python 44 | system_message = { 45 | "role": "system", 46 | "content": "あなたはプロフェッショナルなカスタマーサービスエージェントです。常に礼儀正しく、明確で、役立つようにしてください。" 47 | } 48 | ``` 49 | 50 | ## 会話 51 | 52 | チャットテンプレートは、ユーザーとアシスタント間の以前のやり取りを保存し、会話の履歴を通じて文脈を維持します。これにより、複数ターンにわたる一貫した会話が可能になります: 53 | 54 | ```python 55 | conversation = [ 56 | {"role": "user", "content": "注文に関して助けが必要です"}, 57 | {"role": "assistant", "content": "お手伝いします。注文番号を教えていただけますか?"}, 58 | {"role": "user", "content": "注文番号はORDER-123です"}, 59 | ] 60 | ``` 61 | 62 | ## Transformersを使用した実装 63 | 64 | `transformers`ライブラリは、チャットテンプレートのための組み込みサポートを提供します。使用方法は以下の通りです: 65 | 66 | ```python 67 | from transformers import AutoTokenizer 68 | 69 | tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct") 70 | 71 | messages = [ 72 | {"role": "system", "content": "あなたは役立つプログラミングアシスタントです。"}, 73 | {"role": "user", "content": "リストをソートするPython関数を書いてください"}, 74 | ] 75 | 76 | # チャットテンプレートを適用 77 | formatted_chat = tokenizer.apply_chat_template( 78 | messages, 79 | tokenize=False, 80 | add_generation_prompt=True 81 | ) 82 | ``` 83 | 84 | ## カスタムフォーマット 85 | 86 | 異なる役割に対して特別なトークンやフォーマットを追加するなど、さまざまなメッセージタイプのフォーマットをカスタマイズできます。例えば: 87 | 88 | ```python 89 | template = """ 90 | <|system|>{system_message} 91 | <|user|>{user_message} 92 | <|assistant|>{assistant_message} 93 | """.lstrip() 94 | ``` 95 | 96 | ## マルチターン会話のサポート 97 | 98 | テンプレートは、文脈を維持しながら複雑なマルチターン会話を処理できます: 99 | 100 | ```python 101 | messages = [ 102 | {"role": "system", "content": "あなたは数学の家庭教師です。"}, 103 | {"role": "user", "content": "微積分とは何ですか?"}, 104 | {"role": "assistant", "content": "微積分は数学の一分野です..."}, 105 | {"role": "user", "content": "例を教えてください。"}, 106 | ] 107 | ``` 108 | 109 | ⏭️ [次へ: Supervised Fine-Tuning](./supervised_fine_tuning.md) 110 | 111 | ## リソース 112 | 113 | - [Hugging Face Chat Templating Guide](https://huggingface.co/docs/transformers/main/en/chat_templating) 114 | - [Transformers Documentation](https://huggingface.co/docs/transformers) 115 | - [Chat Templates Examples Repository](https://github.com/chujiezheng/chat_templates) 116 | -------------------------------------------------------------------------------- /ja/1_instruction_tuning/notebooks/.env.example: -------------------------------------------------------------------------------- 1 | # このファイルを.envにコピーし、シークレット値を記入します 2 | HF_TOKEN= 3 | -------------------------------------------------------------------------------- /ja/1_instruction_tuning/supervised_fine_tuning.md: -------------------------------------------------------------------------------- 1 | # 教師あり微調整 2 | 3 | 教師あり微調整(SFT)は、事前トレーニングされた言語モデルを特定のタスクやドメインに適応させるための重要なプロセスです。事前トレーニングされたモデルは一般的な能力を持っていますが、特定のユースケースで優れたパフォーマンスを発揮するためにはカスタマイズが必要です。SFTは、慎重に選ばれた人間によって検証された例を含むデータセットを使用してモデルをトレーニングすることで、このギャップを埋めます。 4 | 5 | ## 教師あり微調整の理解 6 | 7 | 教師あり微調整の核心は、事前トレーニングされたモデルに特定のタスクを実行する方法を教えることです。これは、入力と出力の例を多数提示し、モデルが特定のユースケースのパターンを学習できるようにすることを含みます。 8 | 9 | SFTは、事前トレーニング中に獲得した基本的な知識を活用しながら、モデルの動作を特定のニーズに合わせて調整するため、効果的です。 10 | 11 | ## 教師あり微調整を使用するタイミング 12 | 13 | SFTを使用するかどうかの決定は、現在のモデルの能力と特定の要件とのギャップに依存します。SFTは、モデルの出力を正確に制御する必要がある場合や、専門的なドメインで作業する場合に特に価値があります。 14 | 15 | 例えば、カスタマーサービスアプリケーションを開発している場合、モデルが一貫して企業のガイドラインに従い、技術的な問い合わせを標準化された方法で処理することを望むかもしれません。同様に、医療や法律のアプリケーションでは、正確さと特定のドメインの用語に従うことが重要です。これらの場合、SFTはモデルの応答を専門的な基準とドメインの専門知識に合わせるのに役立ちます。 16 | 17 | ## 教師あり微調整(SFT)のプロセス 18 | 19 | 教師あり微調整のプロセスは、特定のタスクのデータセットでモデルの重みをトレーニングすることを含みます。 20 | 21 | まず、ターゲットタスクを表すデータセットを準備または選択する必要があります。このデータセットには、モデルが直面するさまざまなシナリオをカバーする多様な例が含まれている必要があります。これらのデータの品質は重要です。各例は、モデルが生成することを望む出力の種類を示している必要があります。次に、微調整のフェーズがあり、ここでは`transformers`やHugging Faceの`trl`などのフレームワークを使用して、データセットでモデルをトレーニングします。 22 | 23 | プロセス全体を通じて、継続的な評価が重要です。モデルが望ましい動作を学習していることを確認するために、検証セットでのパフォーマンスを監視する必要があります。これにより、モデルが一般的な能力を失うことなく、特定のタスクに適応していることを確認できます。[モジュール4](../4_evaluation)では、モデルの評価方法について詳しく説明します。 24 | 25 | ## 教師あり微調整の役割 26 | 27 | SFTは、言語モデルを人間の好みに合わせる上で重要な役割を果たします。人間のフィードバックを使用した強化学習(RLHF)や直接選好最適化(DPO)などの技術は、SFTを使用してタスクの基本的な理解を形成し、その後、モデルの応答を望ましい結果にさらに合わせます。事前トレーニングされたモデルは、一般的な言語能力に優れているにもかかわらず、必ずしも人間の好みに一致する出力を生成するわけではありません。SFTは、特定のドメインのデータとガイダンスを導入することで、このギャップを埋め、モデルが人間の期待により密接に一致する応答を生成する能力を向上させます。 28 | 29 | ## トランスフォーマーの強化学習(TRL)を使用した教師あり微調整 30 | 31 | 教師あり微調整のための主要なソフトウェアパッケージは、トランスフォーマーの強化学習(TRL)です。TRLは、強化学習(RL)を使用してトランスフォーマーモデルをトレーニングするためのツールセットです。 32 | 33 | Hugging FaceのTransformersライブラリに基づいており、ユーザーが事前トレーニングされた言語モデルを直接ロードできるようにし、ほとんどのデコーダーおよびエンコーダーデコーダーアーキテクチャと互換性があります。このライブラリは、教師あり微調整(SFT)、報酬モデリング(RM)、近接ポリシー最適化(PPO)、および直接選好最適化(DPO)など、言語モデリングで使用される主要なRLプロセスを容易にします。このリポジトリ全体で、さまざまなモジュールでTRLを使用します。 34 | 35 | # 次のステップ 36 | 37 | 次のチュートリアルを試して、TRLを使用したSFTの実践的な経験を積んでください: 38 | 39 | ⏭️ [チャットテンプレートのチュートリアル](./notebooks/chat_templates_example.ipynb) 40 | 41 | ⏭️ [教師あり微調整のチュートリアル](./notebooks/supervised_fine_tuning_tutorial.ipynb) 42 | -------------------------------------------------------------------------------- /ja/2_preference_alignment/README.md: -------------------------------------------------------------------------------- 1 | # 選好の整合 2 | 3 | このモジュールでは、言語モデルを人間の選好に合わせるための技術について説明します。教師あり微調整(SFT)がモデルにタスクを学習させるのに役立つ一方で、選好の整合は出力が人間の期待や価値観に一致するようにします。 4 | 5 | ## 概要 6 | 7 | 選好の整合の典型的な方法には、複数のステージが含まれます: 8 | 1. 教師あり微調整(SFT)でモデルを特定のドメインに適応させる。 9 | 2. 選好の整合(RLHFやDPOなど)で応答の質を向上させる。 10 | 11 | ORPOのような代替アプローチは、指示調整と選好の整合を単一のプロセスに統合します。ここでは、DPOとORPOのアルゴリズムに焦点を当てます。 12 | 13 | さまざまな整合技術について詳しく知りたい場合は、[Argillaのブログ](https://argilla.io/blog/mantisnlp-rlhf-part-8)を参照してください。 14 | 15 | ### 1️⃣ 直接選好最適化(DPO) 16 | 17 | 直接選好最適化(DPO)は、選好データを使用してモデルを直接最適化することで、選好の整合を簡素化します。このアプローチは、別個の報酬モデルや複雑な強化学習を必要とせず、従来のRLHFよりも安定して効率的です。詳細については、[直接選好最適化(DPO)のドキュメント](./dpo.md)を参照してください。 18 | 19 | ### 2️⃣ 選好確率比最適化(ORPO) 20 | 21 | ORPOは、指示調整と選好の整合を単一のプロセスに統合する新しいアプローチを導入します。これは、負の対数尤度損失とトークンレベルのオッズ比項を組み合わせて標準的な言語モデリングの目的を修正します。このアプローチは、単一のトレーニングステージ、参照モデル不要のアーキテクチャ、および計算効率の向上を提供します。ORPOは、さまざまなベンチマークで印象的な結果を示しており、従来の方法と比較してAlpacaEvalで優れたパフォーマンスを示しています。詳細については、[選好確率比最適化(ORPO)のドキュメント](./orpo.md)を参照してください。 22 | 23 | ## 実習ノートブック 24 | 25 | | タイトル | 説明 | 実習内容 | リンク | Colab | 26 | |-------|-------------|----------|------|-------| 27 | | DPOトレーニング | 直接選好最適化を使用してモデルを��レーニングする方法を学ぶ | 🐢 AnthropicのHH-RLHFデータセットを使用してモデルをトレーニングする
🐕 独自の選好データセットを使用する
🦁 さまざまな選好データセットとモデルサイズで実験する | [ノートブック](./notebooks/dpo_finetuning_example.ipynb) | Open In Colab | 28 | | ORPOトレーニング | 選好確率比最適化を使用してモデルをトレーニングする方法を学ぶ | 🐢 指示と選好データを使用してモデルをトレーニングする
🐕 損失の重みを変えて実験する
🦁 ORPOとDPOの結果を比較する | [ノートブック](./notebooks/orpo_finetuning_example.ipynb) | Open In Colab | 29 | 30 | ## リソース 31 | 32 | - [TRLのドキュメント](https://huggingface.co/docs/trl/index) - DPOを含むさまざまな整合技術を実装するためのTransformers Reinforcement Learning(TRL)ライブラリのドキュメント。 33 | - [DPO論文](https://arxiv.org/abs/2305.18290) - 人間のフィードバックを用いた強化学習の代替として、選好データを使用して言語モデルを直接最適化するシンプルなアプローチを紹介する論文。 34 | - [ORPO論文](https://arxiv.org/abs/2403.07691) - 指示調整と選好の整合を単一のトレーニングステージに統合する新しいアプローチを紹介する論文。 35 | - [ArgillaのRLHFガイド](https://argilla.io/blog/mantisnlp-rlhf-part-8/) - RLHF、DPOなどのさまざまな整合技術とその実践的な実装について説明するガイド。 36 | - [DPOに関するブログ記事](https://huggingface.co/blog/dpo-trl) - TRLライブラリを使用してDPOを実装する方法についての実践ガイド。コード例とベストプラクティスが含まれています。 37 | - [TRLのDPOスクリプト例](https://github.com/huggingface/trl/blob/main/examples/scripts/dpo.py) - TRLライブラリを使用してDPOトレーニングを実装する方法を示す完全なスクリプト例。 38 | - [TRLのORPOスクリプト例](https://github.com/huggingface/trl/blob/main/examples/scripts/orpo.py) - TRLライブラリを使用してORPOトレーニングを実装するためのリファレンス実装。詳細な設定オプションが含まれています。 39 | - [Hugging Faceの整合ハンドブック](https://github.com/huggingface/alignment-handbook) - SFT、DPO、RLHFなどのさまざまな技術を使用して言語モデルを整合させるためのガイドとコード。 40 | -------------------------------------------------------------------------------- /ja/2_preference_alignment/dpo.md: -------------------------------------------------------------------------------- 1 | **直接選好最適化(DPO)** 2 | 3 | 直接選好最適化(DPO)は、言語モデルを人間の好みに合わせるための簡素化されたアプローチを提供します。従来のRLHF(人間のフィードバックを用いた強化学習)メソッドとは異なり、DPOは別個の報酬モデルや複雑な強化学習アルゴリズムを必要とせず、選好データを使用してモデルを直接最適化します。 4 | 5 | ## DPOの理解 6 | 7 | DPOは、選好の整合を人間の選好データに基づく分類問題として再定義します。従来のRLHFアプローチでは、別個の報酬モデルをトレーニングし、PPO(近接ポリシー最適化)などの複雑なアルゴリズムを使用してモデルの出力を整合させる必要があります。DPOは、好ましい出力と好ましくない出力に基づいてモデルのポリシーを直接最適化する損失関数を定義することで、このプロセスを簡素化します。 8 | 9 | このアプローチは実際に非常に効果的であり、Llamaなどのモデルのトレーニングに使用されています。別個の報酬モデルや強化学習のステージを必要としないため、DPOは選好の整合をよりアクセスしやすく、安定したものにします。 10 | 11 | ## DPOの仕組み 12 | 13 | DPOのプロセスには、ターゲットドメインにモデルを適応させるための教師あり微調整(SFT)が必要です。これにより、標準的な指示追従データセットでトレーニングすることで、選好学習の基盤が形成されます。モデルは基本的なタスクを完了しながら、一般的な能力を維持することを学びます。 14 | 15 | 次に、選好学習が行われ、モデルは好ましい出力と好ましくない出力のペアでトレーニングされます。選好ペアは、モデルがどの応答が人間の価値観や期待に最も一致するかを理解するのに役立ちます。 16 | 17 | DPOの中心的な革新は、その直接最適化アプローチにあります。別個の報酬モデルをトレーニングする代わりに、DPOはバイナリクロスエントロピー損失を使用して、選好データに基づいてモデルの重みを直接更新します。この簡素化されたプロセスにより、トレーニングがより安定し、効率的になり、従来のRLHFメソッドと同等またはそれ以上の結果が得られます。 18 | 19 | ## DPOのデータセット 20 | 21 | DPOのデータセットは、通常、選好または非選好として注釈された応答ペアを含むように作成されます。これは手動で行うか、自動フィルタリング技術を使用して行うことができます。以下は、単一ターンのDPO選好データセットの構造の例です: 22 | 23 | | プロンプト | 選好 | 非選好 | 24 | |--------|---------|-----------| 25 | | ... | ... | ... | 26 | | ... | ... | ... | 27 | | ... | ... | ... | 28 | 29 | `Prompt`列には、`選好`および`非選好`の応答を生成するために使用されたプロンプトが含まれています。`選好`および`非選好`列には、それぞれ好ましい応答と好ましくない応答が含まれています。この構造にはバリエーションがあり、例えば、`system_prompt`や`Input`列に参照資料を含めることができます。`選好`および`非選好`の値は、単一ターンの会話の場合は文字列として、または会話リストとして表現されることがあります。 30 | 31 | Hugging FaceでDPOデータセットのコレクションを[こちら](https://huggingface.co/collections/argilla/preference-datasets-for-dpo-656f0ce6a00ad2dc33069478)で見つけることができます。 32 | 33 | ## TRLを使用した実装 34 | 35 | Transformers Reinforcement Learning(TRL)ライブラリは、DPOの実装を容易にします。`DPOConfig`および`DPOTrainer`クラスは、`transformers`スタイルのAPIに従います。 36 | 37 | 以下は、DPOトレーニングを設定する基本的な例です: 38 | 39 | ```python 40 | from trl import DPOConfig, DPOTrainer 41 | 42 | # 引数を定義 43 | training_args = DPOConfig( 44 | ... 45 | ) 46 | 47 | # トレーナーを初期化 48 | trainer = DPOTrainer( 49 | model, 50 | train_dataset=dataset, 51 | tokenizer=tokenizer, 52 | ... 53 | ) 54 | 55 | # モデルをトレーニング 56 | trainer.train() 57 | ``` 58 | 59 | DPOConfigおよびDPOTrainerクラスの使用方法の詳細については、[DPOチュートリアル](./notebooks/dpo_finetuning_example.ipynb)を参照してください。 60 | 61 | ## ベストプラクティス 62 | 63 | データの品質は、DPOの成功した実装にとって重要です。選好データセットには、望ましい行動のさまざまな側面をカバーする多様な例が含まれている必要があります。明確な注釈ガイドラインは、選好および非選好の応答の一貫したラベル付けを保証します。選好データセットの品質を向上させることで、モデルのパフォーマンスを向上させることができます。例えば、より大きなデータセットをフィルタリングして、高品質の例やユースケースに関連する例のみを含めることができます。 64 | 65 | トレーニング中は、損失の収束を慎重に監視し、保持データでパフォーマンスを検証します。選好学習とモデルの一般的な能力の維持をバランスさせるために、ベータパラメータを調整する必要がある場合があります。多様な例での定期的な評価は、モデルが望ましい選好を学習しながら過剰適合しないことを保証するのに役立ちます。 66 | 67 | モデルの出力を基準モデルと比較して、選好の整合性の向上を確認します。さまざまなプロンプト、特にエッジケースを使用してモデルをテストすることで、さまざまなシナリオでの選好学習の堅牢性を保証します。 68 | 69 | ## 次のステップ 70 | 71 | ⏩ DPOの実践的な経験を得るために、[DPOチュートリアル](./notebooks/dpo_finetuning_example.ipynb)を試してみてください。この実践ガイドでは、データの準備からトレーニングおよび評価まで、選好整合の実装方法を説明します。 72 | 73 | ⏭️ チュートリアルを完了した後、別の選好整合技術について学ぶために[ORPOページ](./orpo.md)を探索してください。 74 | -------------------------------------------------------------------------------- /ja/2_preference_alignment/notebooks/dpo_finetuning_example.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# DPO微調整の例\n", 8 | "\n", 9 | "このノートブックでは、`trl`ライブラリを使用してDPO(直接選好最適化)を実行する方法を示します。DPOは、モデルの出力を人間の選好に合わせるためのシンプルで効果的な方法です。" 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "metadata": {}, 15 | "source": [ 16 | "## 1. 環境の設定\n", 17 | "\n", 18 | "まず、必要なライブラリをインストールし、Hugging Faceにログインします。" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": null, 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "# Google Colabでの要件のインストール\n", 28 | "# !pip install transformers datasets trl huggingface_hub\n", 29 | "\n", 30 | "# Hugging Faceへの認証\n", 31 | "from huggingface_hub import login\n", 32 | "\n", 33 | "login()\n", 34 | "\n", 35 | "# 便利のため、Hugging Faceのトークンを.envファイルのHF_TOKENとして環境変数に設定できます" 36 | ] 37 | }, 38 | { 39 | "cell_type": "markdown", 40 | "metadata": {}, 41 | "source": [ 42 | "## 2. モデルとデータセットのロード\n", 43 | "\n", 44 | "次に、事前学習済みモデルとデータセットをロードします。" 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "execution_count": null, 50 | "metadata": {}, 51 | "outputs": [], 52 | "source": [ 53 | "from transformers import AutoModelForCausalLM, AutoTokenizer\n", 54 | "from datasets import load_dataset\n", 55 | "\n", 56 | "# モデルとトークナイザーをロード\n", 57 | "model_name = \"HuggingFaceTB/SmolLM2-135M\"\n", 58 | "model = AutoModelForCausalLM.from_pretrained(model_name)\n", 59 | "tokenizer = AutoTokenizer.from_pretrained(model_name)\n", 60 | "\n", 61 | "# データセットをロード\n", 62 | "dataset = load_dataset(\"Anthropic/hh-rlhf\")" 63 | ] 64 | }, 65 | { 66 | "cell_type": "markdown", 67 | "metadata": {}, 68 | "source": [ 69 | "## 3. DPOトレーナーの設定\n", 70 | "\n", 71 | "DPOトレーナーを設定し、トレーニングを開始します。" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": null, 77 | "metadata": {}, 78 | "outputs": [], 79 | "source": [ 80 | "from trl import DPOConfig, DPOTrainer\n", 81 | "\n", 82 | "# DPOの設定\n", 83 | "dpo_config = DPOConfig(\n", 84 | " model_name_or_path=model_name,\n", 85 | " learning_rate=5e-5,\n", 86 | " per_device_train_batch_size=4,\n", 87 | " num_train_epochs=3,\n", 88 | " logging_steps=10,\n", 89 | " save_steps=100,\n", 90 | " output_dir=\"./dpo_output\"\n", 91 | ")\n", 92 | "\n", 93 | "# DPOトレーナーを初期化\n", 94 | "trainer = DPOTrainer(\n", 95 | " model=model,\n", 96 | " args=dpo_config,\n", 97 | " train_dataset=dataset[\"train\"],\n", 98 | " eval_dataset=dataset[\"test\"],\n", 99 | " tokenizer=tokenizer\n", 100 | ")\n", 101 | "\n", 102 | "# モデルをトレーニング\n", 103 | "trainer.train()" 104 | ] 105 | }, 106 | { 107 | "cell_type": "markdown", 108 | "metadata": {}, 109 | "source": [ 110 | "## 4. 微調整されたモデルの保存\n", 111 | "\n", 112 | "トレーニングが完了したら、微調整されたモデルを保存します。" 113 | ] 114 | }, 115 | { 116 | "cell_type": "code", 117 | "execution_count": null, 118 | "metadata": {}, 119 | "outputs": [], 120 | "source": [ 121 | "# 微調整されたモデルを保存\n", 122 | "trainer.save_model(\"./dpo_finetuned_model\")" 123 | ] 124 | }, 125 | { 126 | "cell_type": "markdown", 127 | "metadata": {}, 128 | "source": [ 129 | "## 5. 微調整されたモデルの評価\n", 130 | "\n", 131 | "最後に、微調整されたモデルを評価します。" 132 | ] 133 | }, 134 | { 135 | "cell_type": "code", 136 | "execution_count": null, 137 | "metadata": {}, 138 | "outputs": [], 139 | "source": [ 140 | "# 評価の実行\n", 141 | "results = trainer.evaluate()\n", 142 | "print(results)" 143 | ] 144 | } 145 | ], 146 | "metadata": { 147 | "kernelspec": { 148 | "display_name": "Python 3", 149 | "language": "python", 150 | "name": "python3" 151 | }, 152 | "language_info": { 153 | "codemirror_mode": { 154 | "name": "ipython", 155 | "version": 3 156 | }, 157 | "file_extension": ".py", 158 | "mimetype": "text/x-python", 159 | "name": "python", 160 | "nbconvert_exporter": "python", 161 | "pygments_lexer": "ipython3", 162 | "version": "3.8.8" 163 | } 164 | }, 165 | "nbformat": 4, 166 | "nbformat_minor": 5 167 | } 168 | -------------------------------------------------------------------------------- /ja/2_preference_alignment/notebooks/orpo_finetuning_example.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# ORPO微調整の例\n", 8 | "\n", 9 | "このノートブックでは、`trl`ライブラリを使用してORPO(選好確率比最適化)を実行する方法を示します。ORPOは、モデルの出力を人間の選好に合わせるためのシンプルで効果的な方法です。" 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "metadata": {}, 15 | "source": [ 16 | "## 1. 環境の設定\n", 17 | "\n", 18 | "まず、必要なライブラリをインストールし、Hugging Faceにログインします。" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": null, 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "# Google Colabでの要件のインストール\n", 28 | "# !pip install transformers datasets trl huggingface_hub\n", 29 | "\n", 30 | "# Hugging Faceへの認証\n", 31 | "from huggingface_hub import login\n", 32 | "\n", 33 | "login()\n", 34 | "\n", 35 | "# 便利のため、Hugging Faceのトークンを.envファイルのHF_TOKENとして環境変数に設定できます" 36 | ] 37 | }, 38 | { 39 | "cell_type": "markdown", 40 | "metadata": {}, 41 | "source": [ 42 | "## 2. モデルとデータセットのロード\n", 43 | "\n", 44 | "次に、事前学習済みモデルとデータセットをロードします。" 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "execution_count": null, 50 | "metadata": {}, 51 | "outputs": [], 52 | "source": [ 53 | "from transformers import AutoModelForCausalLM, AutoTokenizer\n", 54 | "from datasets import load_dataset\n", 55 | "\n", 56 | "# モデルとトークナイザーをロード\n", 57 | "model_name = \"HuggingFaceTB/SmolLM2-135M\"\n", 58 | "model = AutoModelForCausalLM.from_pretrained(model_name)\n", 59 | "tokenizer = AutoTokenizer.from_pretrained(model_name)\n", 60 | "\n", 61 | "# データセットをロード\n", 62 | "dataset = load_dataset(\"Anthropic/hh-rlhf\")" 63 | ] 64 | }, 65 | { 66 | "cell_type": "markdown", 67 | "metadata": {}, 68 | "source": [ 69 | "## 3. ORPOトレーナーの設定\n", 70 | "\n", 71 | "ORPOトレーナーを設定し、トレーニングを開始します。" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": null, 77 | "metadata": {}, 78 | "outputs": [], 79 | "source": [ 80 | "from trl import ORPOConfig, ORPOTrainer\n", 81 | "\n", 82 | "# ORPOの設定\n", 83 | "orpo_config = ORPOConfig(\n", 84 | " model_name_or_path=model_name,\n", 85 | " learning_rate=5e-5,\n", 86 | " per_device_train_batch_size=4,\n", 87 | " num_train_epochs=3,\n", 88 | " logging_steps=10,\n", 89 | " save_steps=100,\n", 90 | " output_dir=\"./orpo_output\"\n", 91 | ")\n", 92 | "\n", 93 | "# ORPOトレーナーを初期化\n", 94 | "trainer = ORPOTrainer(\n", 95 | " model=model,\n", 96 | " args=orpo_config,\n", 97 | " train_dataset=dataset[\"train\"],\n", 98 | " eval_dataset=dataset[\"test\"],\n", 99 | " tokenizer=tokenizer\n", 100 | ")\n", 101 | "\n", 102 | "# モデルをトレーニング\n", 103 | "trainer.train()" 104 | ] 105 | }, 106 | { 107 | "cell_type": "markdown", 108 | "metadata": {}, 109 | "source": [ 110 | "## 4. 微調整されたモデルの保存\n", 111 | "\n", 112 | "トレーニングが完了したら、微調整されたモデルを保存します。" 113 | ] 114 | }, 115 | { 116 | "cell_type": "code", 117 | "execution_count": null, 118 | "metadata": {}, 119 | "outputs": [], 120 | "source": [ 121 | "# 微調整されたモデルを保存\n", 122 | "trainer.save_model(\"./orpo_finetuned_model\")" 123 | ] 124 | }, 125 | { 126 | "cell_type": "markdown", 127 | "metadata": {}, 128 | "source": [ 129 | "## 5. 微調整されたモデルの評価\n", 130 | "\n", 131 | "最後に、微調整されたモデルを評価します。" 132 | ] 133 | }, 134 | { 135 | "cell_type": "code", 136 | "execution_count": null, 137 | "metadata": {}, 138 | "outputs": [], 139 | "source": [ 140 | "# 評価の実行\n", 141 | "results = trainer.evaluate()\n", 142 | "print(results)" 143 | ] 144 | } 145 | ], 146 | "metadata": { 147 | "kernelspec": { 148 | "display_name": "Python 3", 149 | "language": "python", 150 | "name": "python3" 151 | }, 152 | "language_info": { 153 | "codemirror_mode": { 154 | "name": "ipython", 155 | "version": 3 156 | }, 157 | "file_extension": ".py", 158 | "mimetype": "text/x-python", 159 | "name": "python", 160 | "nbconvert_exporter": "python", 161 | "pygments_lexer": "ipython3", 162 | "version": "3.8.8" 163 | } 164 | }, 165 | "nbformat": 4, 166 | "nbformat_minor": 5 167 | } 168 | -------------------------------------------------------------------------------- /ja/2_preference_alignment/orpo.md: -------------------------------------------------------------------------------- 1 | **選好確率比最適化(ORPO)** 2 | 3 | 選好確率比最適化(ORPO)は、微調整と選好整合を単一の統合プロセスで組み合わせる新しいアプローチです。この統合アプローチは、従来のRLHFやDPOなどの方法と比較して、効率とパフォーマンスの面で利点を提供します。 4 | 5 | ## ORPOの理解 6 | 7 | DPOのような選好整合方法は、通常、微調整と選好整合の2つの別々のステップを含みます。微調整はモデルを特定のドメインや形式に適応させ、選好整合は人間の選好に合わせて出力を調整します。SFT(教師あり微調整)は、モデルをターゲットドメインに適応させるのに効果的ですが、望ましい応答と望ましくない応答の両方の確率を増加させる可能性があります。ORPOは、以下の比較図に示すように、これらのステップを単一のプロセスに統合することで、この制限に対処します。 8 | 9 | ![モデル整合技術の比較](https://argilla.io/images/blog/mantisnlp-rlhf/part-8-alignments.png) 10 | *モデル整合技術の比較* 11 | 12 | ## ORPOの仕組み 13 | 14 | ORPOのトレーニングプロセスは、DPOと同様に、入力プロンプトと2つの応答(1つは選好、もう1つは非選好)を含む選好データセットを使用します。他の整合方法とは異なり、ORPOは選好整合を教師あり微調整プロセスに直接統合します。この統合アプローチにより、参照モデルが不要になり、計算効率とメモリ効率が向上し、FLOP数が減少します。 15 | 16 | ORPOは、次の2つの主要なコンポーネントを組み合わせて新しい目的を作成します: 17 | 18 | 1. **SFT損失**:負の対数尤度損失を使用して、参照トークンの生成確率を最大化します。これにより、モデルの一般的な言語能力が維持されます。 19 | 2. **オッズ比損失**:望ましくない応答をペナルティし、選好される応答を報酬する新しいコンポーネントです。この損失関数は、トークンレベルで選好される応答と非選好の応答を効果的に対比するためにオッズ比を使用します。 20 | 21 | これらのコンポーネントを組み合わせることで、モデルは特定のドメインに対して望ましい生成を適応させながら、非選好の応答を積極的に抑制します。オッズ比メカニズムは、選好された応答と拒否された応答の間のモデルの選好を測定および最適化する自然な方法を提供します。数学的な詳細については、[ORPO論文](https://arxiv.org/abs/2403.07691)を参照してください。実装の観点からORPOについて学びたい場合は、[TRLライブラリ](https://github.com/huggingface/trl/blob/b02189aaa538f3a95f6abb0ab46c0a971bfde57e/trl/trainer/orpo_trainer.py#L660)でORPO損失がどのように計算されるかを確認してください。 22 | 23 | ## パフォーマンスと結果 24 | 25 | ORPOは、さまざまなベンチマークで印象的な結果を示しています。MT-Benchでは、さまざまなカテゴリで競争力のあるスコアを達成しています: 26 | 27 | ![MT-Benchの結果](https://argilla.io/images/blog/mantisnlp-rlhf/part-8-mtbench.png) 28 | *MT-Benchのカテゴリ別結果(Mistral-ORPOモデル)* 29 | 30 | 他の整合方法と比較すると、ORPOはAlpacaEval 2.0で優れたパフォーマンスを示しています: 31 | 32 | ![AlpacaEvalの結果](https://argilla.io/images/blog/mantisnlp-rlhf/part-8-winrate.png) 33 | *さまざまな整合方法におけるAlpacaEval 2.0スコア* 34 | 35 | SFT+DPOと比較して、ORPOは参照モデルが不要であり、バッチごとのフォワードパスの数を半減させることで計算要件を削減します。さらに、トレーニングプロセスは、さまざまなモデルサイズとデータセットでより安定しており、調整するハイパーパラメータが少なくて済みます。パフォーマンスに関しては、ORPOはより大きなモデルと同等のパフォーマンスを示しながら、人間の選好に対する整合性が向上しています。 36 | 37 | ## 実装 38 | 39 | ORPOの成功した実装は、高品質の選好データに大きく依存します。トレーニングデータは明確な注釈ガイドラインに従い、さまざまなシナリオで好ましい応答と拒否された応答のバランスの取れた表現を提供する必要があります。 40 | 41 | ### TRLを使用した実装 42 | 43 | ORPOは、Transformers Reinforcement Learning(TRL)ライブラリを使用して実装できます。以下は基本的な例です: 44 | 45 | ```python 46 | from trl import ORPOConfig, ORPOTrainer 47 | 48 | # ORPOトレーニングの設定 49 | orpo_config = ORPOConfig( 50 | learning_rate=1e-5, 51 | per_device_train_batch_size=4, 52 | gradient_accumulation_steps=4, 53 | max_steps=1000, 54 | orpo_alpha=1.0, # 選好最適化の強度を制御 55 | orpo_beta=0.1, # オッズ比計算の温度パラメータ 56 | ) 57 | 58 | # トレーナーを初期化 59 | trainer = ORPOTrainer( 60 | model=model, 61 | args=orpo_config, 62 | train_dataset=dataset, 63 | tokenizer=tokenizer, 64 | ) 65 | 66 | # トレーニングを開始 67 | trainer.train() 68 | ``` 69 | 70 | 考慮すべき主要なパラメータ: 71 | - `orpo_alpha`:選好最適化の強度を制御 72 | - `orpo_beta`:オッズ比計算の温度パラメータ 73 | - `learning_rate`:忘却のカタストロフィーを避けるために比較的小さく設定 74 | - `gradient_accumulation_steps`:トレーニングの安定性を向上 75 | 76 | ## 次のステップ 77 | 78 | ⏩ この統合された選好整合アプローチを実装するための[ORPOチュートリアル](./notebooks/orpo_tutorial.ipynb)を試してみてください。 79 | 80 | ## リソース 81 | - [ORPO論文](https://arxiv.org/abs/2403.07691) 82 | - [TRLドキュメント](https://huggingface.co/docs/trl/index) 83 | - [ArgillaのRLHFガイド](https://argilla.io/blog/mantisnlp-rlhf-part-8/) 84 | -------------------------------------------------------------------------------- /ja/3_parameter_efficient_finetuning/README.md: -------------------------------------------------------------------------------- 1 | # パラメータ効率の良い微調整 (PEFT) 2 | 3 | 言語モデルが大きくなるにつれて、従来の微調整はますます困難になります。1.7Bパラメータのモデルの完全な微調整には、かなりのGPUメモリが必要であり、別々のモデルコピーを保存することが高価であり、モデルの元の能力を破壊的に忘れるリスクがあります。パラメータ効率の良い微調整(PEFT)メソッドは、モデルパラメータの小さなサブセットのみを変更し、ほとんどのモデルを固定したままにすることで、これらの課題に対処します。 4 | 5 | 従来の微調整は、トレーニング中にすべてのモデルパラメータを更新しますが、これは大規模なモデルには実用的ではありません。PEFTメソッドは、元のモデルサイズの1%未満のパラメータを使用してモデルを適応させるアプローチを導入します。この劇的な学習可能なパラメータの削減により、次のことが可能になります: 6 | 7 | - 限られたGPUメモリを持つ消費者向けハードウェアでの微調整 8 | - 複数のタスク固有の適応を効率的に保存 9 | - 低データシナリオでのより良い一般化 10 | - より速いトレーニングと反復サイクル 11 | 12 | ## 利用可能なメソッド 13 | 14 | このモジュールでは、2つの人気のあるPEFTメソッドを紹介します: 15 | 16 | ### 1️⃣ LoRA (低ランク適応) 17 | 18 | LoRAは、効率的なモデル適応のためのエレガントなソリューションを提供する最も広く採用されているPEFTメソッドとして浮上しました。モデル全体を変更する代わりに、**LoRAはモデルの注意層に学習可能な行列を注入します。**このアプローチは、通常、完全な微調整と比較して約90%の学習可能なパラメータを削減しながら、同等の性能を維持します。[LoRA (低ランク適応)](./lora_adapters.md)セクションでLoRAを詳しく見ていきます。 19 | 20 | ### 2️⃣ プロンプトチューニング 21 | 22 | プロンプトチューニングは、モデルの重みを変更するのではなく、**入力に学習可能なトークンを追加する**さらに軽量なアプローチを提供します。プロンプトチューニングはLoRAほど人気はありませんが、モデルを新しいタスクやドメインに迅速に適応させるための便利な技術です。[プロンプトチューニング](./prompt_tuning.md)セクションでプロンプトチューニングを詳しく見ていきます。 23 | 24 | ## 演習ノートブック 25 | 26 | | タイトル | 説明 | 演習 | リンク | Colab | 27 | |-------|-------------|----------|------|-------| 28 | | LoRA微調整 | LoRAアダプタを使用してモデルを微調整する方法を学ぶ | 🐢 LoRAを使用してモデルをトレーニング
🐕 異なるランク値で実験
🦁 完全な微調整と性能を比較 | [ノートブック](./notebooks/finetune_sft_peft.ipynb) | Open In Colab | 29 | | LoRAアダプタの読み込み | トレーニングされたLoRAアダプタを読み込んで使用する方法を学ぶ | 🐢 事前学習されたアダプタを読み込む
🐕 アダプタをベースモデルと統合
🦁 複数のアダプタ間を切り替える | [ノートブック](./notebooks/load_lora_adapter.ipynb) | Open In Colab | 30 | 31 | 32 | ## リソース 33 | - [PEFTドキュメント](https://huggingface.co/docs/peft) 34 | - [LoRA論文](https://arxiv.org/abs/2106.09685) 35 | - [QLoRA論文](https://arxiv.org/abs/2305.14314) 36 | - [プロンプトチューニング論文](https://arxiv.org/abs/2104.08691) 37 | - [Hugging Face PEFTガイド](https://huggingface.co/blog/peft) 38 | - [2024年にHugging FaceでLLMを微調整する方法](https://www.philschmid.de/fine-tune-llms-in-2024-with-trl) 39 | - [TRL](https://huggingface.co/docs/trl/index) 40 | -------------------------------------------------------------------------------- /ja/3_parameter_efficient_finetuning/images/lora_adapter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/ja/3_parameter_efficient_finetuning/images/lora_adapter.png -------------------------------------------------------------------------------- /ja/3_parameter_efficient_finetuning/prompt_tuning.md: -------------------------------------------------------------------------------- 1 | # プロンプトチューニング 2 | 3 | プロンプトチューニングは、モデルの重みではなく入力表現を変更するパラメータ効率の良いアプローチです。従来の微調整がすべてのモデルパラメータを更新するのに対し、プロンプトチューニングはベースモデルを固定したまま、少数の学習可能なトークンを追加して最適化します。 4 | 5 | ## プロンプトチューニングの理解 6 | 7 | プロンプトチューニングは、学習可能な連続ベクトル(ソフトプロンプト)を入力テキストの前に追加するパラメータ効率の良い微調整方法です。従来の離散テキストプロンプトとは異なり、これらのソフトプロンプトはベースモデルを固定したまま、逆伝播を通じて学習されます。この方法は、["The Power of Scale for Parameter-Efficient Prompt Tuning"](https://arxiv.org/abs/2104.08691)(Lester et al., 2021)で紹介され、モデルサイズが大きくなるにつれてプロンプトチューニングがモデル微調整と競争力を持つようになることが示されました。論文内では、約100億パラメータのモデルで、プロンプトチューニングがモデル微調整の性能に匹敵し、タスクごとに数百のパラメータしか変更しないことが示されています。 8 | 9 | これらのソフトプロンプトは、トレーニング中に最適化されるモデルの埋め込み空間内の連続ベクトルです。従来の自然言語トークンを使用する離散プロンプトとは異なり、ソフトプロンプトは固有の意味を持たず、勾配降下を通じて固定モデルから望ましい動作を引き出すことを学習します。この技術は、各タスクに対して小さなプロンプトベクトル(通常は数百パラメータ)を保存するだけで済むため、マルチタスクシナリオに特に効果的です。このアプローチは、最小限のメモリフットプリントを維持するだけでなく、モデルの再読み込みなしにプロンプトベクトルを交換するだけで迅速なタスク切り替えを可能にします。 10 | 11 | ## トレーニングプロセス 12 | 13 | ソフトプロンプトは通常、8〜32トークンで構成され、ランダムに初期化するか、既存のテキストから初期化されます。初期化方法はトレーニングプロセスにおいて重要な役割を果たし、テキストベースの初期化はランダム初期化よりも優れた性能を発揮することがよくあります。 14 | 15 | トレーニング中は、プロンプトパラメータのみが更新され、ベースモデルは固定されたままです。この集中アプローチは標準的なトレーニング目標を使用しますが、プロンプトトークンの学習率と勾配の挙動に注意を払う必要があります。 16 | 17 | ## PEFTを使用した実装 18 | 19 | PEFTライブラリを使用すると、プロンプトチューニングの実装が簡単になります。以下は基本的な例です: 20 | 21 | ```python 22 | from peft import PromptTuningConfig, TaskType, get_peft_model 23 | from transformers import AutoModelForCausalLM, AutoTokenizer 24 | 25 | # ベースモデルを読み込む 26 | model = AutoModelForCausalLM.from_pretrained("your-base-model") 27 | tokenizer = AutoTokenizer.from_pretrained("your-base-model") 28 | 29 | # プロンプトチューニングを設定 30 | peft_config = PromptTuningConfig( 31 | task_type=TaskType.CAUSAL_LM, 32 | num_virtual_tokens=8, # 学習可能なトークンの数 33 | prompt_tuning_init="TEXT", # テキストから初期化 34 | prompt_tuning_init_text="このテキストがポジティブかネガティブかを分類してください:", 35 | tokenizer_name_or_path="your-base-model", 36 | ) 37 | 38 | # プロンプトチューニング可能なモデルを作成 39 | model = get_peft_model(model, peft_config) 40 | ``` 41 | 42 | ## 他の方法との比較 43 | 44 | 他のPEFTアプローチと比較すると、プロンプトチューニングはその効率性で際立っています。LoRAは低パラメータ数とメモリ使用量を提供しますが、タスク切り替えにはアダプタの読み込みが必要です。プロンプトチューニングはさらに低いリソース使用量を達成し、即時のタスク切り替えを可能にします。対照的に、フルファインチューニングは多くのリソースを必要とし、異なるタスクごとに別々のモデルコピーが必要です。 45 | 46 | | 方法 | パラメータ | メモリ | タスク切り替え | 47 | |--------|------------|---------|----------------| 48 | | プロンプトチューニング | 非常に低い | 最小限 | 簡単 | 49 | | LoRA | 低い | 低い | 読み込みが必要 | 50 | | フルファインチューニング | 高い | 高い | 新しいモデルコピー | 51 | 52 | プロンプトチューニングを実装する際は、最初に少数の仮想トークン(8〜16)を使用し、タスクの複雑さが要求する場合にのみ増やします。タスクに関連するテキストを使用したテキスト初期化は、ランダム初期化よりも優れた結果をもたらすことがよくあります。初期化戦略は、ターゲットタスクの複雑さを反映する必要があります。 53 | 54 | トレーニングには、フルファインチューニングとは異なる考慮事項が必要です。高い学習率が効果的なことが多いですが、プロンプトトークンの勾配を注意深く監視することが重要です。多様な例で定期的に検証することで、さまざまなシナリオでの堅牢な性能を確保します。 55 | 56 | ## 応用 57 | 58 | プロンプトチューニングは、次のようなシナリオで優れた効果を発揮します: 59 | 60 | 1. マルチタスク展開 61 | 2. リソース制約のある環境 62 | 3. 迅速なタスク適応 63 | 4. プライバシーに敏感なアプリケーション 64 | 65 | モデルが小さくなるにつれて、プロンプトチューニングはフルファインチューニングと比較して競争力が低下します。例えば、SmolLM2のようなモデルでは、プロンプトチューニングはフルファインチューニングよりも関連性が低くなります。 66 | 67 | ## 次のステップ 68 | 69 | ⏭️ [LoRAアダプタのチュートリアル](./notebooks/finetune_sft_peft.ipynb)に進み、LoRAアダプタでモデルを微調整する方法を学びましょう。 70 | 71 | ## リソース 72 | - [PEFTドキュメント](https://huggingface.co/docs/peft) 73 | - [プロンプトチューニング論文](https://arxiv.org/abs/2104.08691) 74 | - [Hugging Face Cookbook](https://huggingface.co/learn/cookbook/prompt_tuning_peft) 75 | -------------------------------------------------------------------------------- /ja/4_evaluation/README.md: -------------------------------------------------------------------------------- 1 | # 評価 2 | 3 | 評価は、言語モデルの開発と展開において重要なステップです。評価は、モデルがさまざまな能力にわたってどれだけうまく機能するかを理解し、改善の余地を特定するのに役立ちます。このモジュールでは、標準ベンチマークとドメイン固有の評価アプローチの両方をカバーし、smolモデルを包括的に評価します。 4 | 5 | Hugging Faceが開発した強力な評価ライブラリである[`lighteval`](https://github.com/huggingface/lighteval)を使用します。評価の概念とベストプラクティスについて詳しく知りたい場合は、評価[ガイドブック](https://github.com/huggingface/evaluation-guidebook)を参照してください。 6 | 7 | ## モジュール概要 8 | 9 | 徹底した評価戦略は、モデル性能の複数の側面を検討します。質問応答や要約などのタスク固有の能力を評価し、モデルがさまざまなタイプの問題にどれだけうまく対処できるかを理解します。出力の品質を一貫性や事実の正確性などの要素で測定します。安全性評価は、潜在的な有害な出力やバイアスを特定するのに役立ちます。最後に、ドメインの専門知識テストは、ターゲット分野でのモデルの専門知識を検証します。 10 | 11 | ## コンテンツ 12 | 13 | ### 1️⃣ [自動ベンチマーク](./automatic_benchmarks.md) 14 | 15 | 標準化されたベンチマークとメトリクスを使用してモデルを評価する方法を学びます。MMLUやTruthfulQAなどの一般的なベンチマークを探求し、主要な評価メトリクスと設定を理解し、再現可能な評価のベストプラクティスをカバーします。 16 | 17 | ### 2️⃣ [カスタムドメイン評価](./custom_evaluation.md) 18 | 19 | 特定のユースケースに合わせた評価パイプラインを作成する方法を学びます。カスタム評価タスクの設計、専門的なメトリクスの実装、要件に合った評価データセットの構築について説明します。 20 | 21 | ### 3️⃣ [ドメイン評価プロジェクト](./project/README.md) 22 | 23 | ドメイン固有の評価パイプラインを構築する完全な例を紹介します。評価データセットの生成、データ注釈のためのArgillaの使用、標準化されたデータセットの作成、LightEvalを使用したモデルの評価方法を学びます。 24 | 25 | ### 演習ノートブック 26 | 27 | | タイトル | 説明 | 演習 | リンク | Colab | 28 | |-------|-------------|----------|------|-------| 29 | | LLMの評価と分析 | LightEvalを使用して特定のドメインでモデルを評価および比較する方法を学びます | 🐢 医療ドメインタスクを使用してモデルを評価する
🐕 異なるMMLUタスクで新しいドメイン評価を作成する
🦁 ドメイン固有のカスタム評価タスクを作成する | [ノートブック](./notebooks/lighteval_evaluate_and_analyse_your_LLM.ipynb) | Open In Colab | 30 | 31 | ## リソース 32 | 33 | - [評価ガイドブック](https://github.com/huggingface/evaluation-guidebook) - LLM評価の包括的なガイド 34 | - [LightEvalドキュメント](https://github.com/huggingface/lighteval) - LightEvalライブラリの公式ドキュメント 35 | - [Argillaドキュメント](https://docs.argilla.io) - Argillaアノテーションプラットフォームについて学ぶ 36 | - [MMLU論文](https://arxiv.org/abs/2009.03300) - MMLUベンチマークを説明する論文 37 | - [カスタムタスクの作成](https://github.com/huggingface/lighteval/wiki/Adding-a-Custom-Task) 38 | - [カスタムメトリクスの作成](https://github.com/huggingface/lighteval/wiki/Adding-a-New-Metric) 39 | - [既存のメトリクスの使用](https://github.com/huggingface/lighteval/wiki/Metric-List) 40 | -------------------------------------------------------------------------------- /ja/4_evaluation/automatic_benchmarks.md: -------------------------------------------------------------------------------- 1 | # 自動ベンチマーク 2 | 3 | 自動ベンチマークは、さまざまなタスクや能力にわたって言語モデルを評価するための標準化されたツールとして機能します。これらはモデルの性能を理解するための有用な出発点を提供しますが、包括的な評価戦略の一部に過ぎないことを認識することが重要です。 4 | 5 | ## 自動ベンチマークの理解 6 | 7 | 自動ベンチマークは通常、事前に定義されたタスクと評価指標を持つキュレーションされたデータセットで構成されます。これらのベンチマークは、基本的な言語理解から複雑な推論まで、モデルのさまざまな側面を評価することを目的としています。自動ベンチマークの主な利点はその標準化にあります。これにより、異なるモデル間で一貫した比較が可能となり、再現性のある結果が得られます。 8 | 9 | ただし、ベンチマークの性能が必ずしも実世界での有効性に直結するわけではないことを理解することが重要です。学術的なベンチマークで優れた成績を収めたモデルでも、特定のドメインアプリケーションや実際のユースケースでは苦労することがあります。 10 | 11 | ## ベンチマークとその限界 12 | 13 | ### 一般知識ベンチマーク 14 | 15 | MMLU(Massive Multitask Language Understanding)は、科学から人文科学まで57の科目にわたる知識をテストします。包括的ではありますが、特定のドメインに必要な専門知識の深さを反映しているわけではありません。TruthfulQAは、モデルが一般的な誤解を再現する傾向を評価しますが、すべての形態の誤情報を捉えることはできません。 16 | 17 | ### 推論ベンチマーク 18 | BBH(Big Bench Hard)とGSM8Kは、複雑な推論タスクに焦点を当てています。BBHは論理的思考と計画をテストし、GSM8Kは特に数学的な問題解決を対象としています。これらのベンチマークは分析能力を評価するのに役立ちますが、実世界のシナリオで必要とされる微妙な推論を完全に捉えることはできません。 19 | 20 | ### 言語理解 21 | HELMは包括的な評価フレームワークを提供し、WinoGrandeは代名詞の曖昧性解消を通じて常識をテストします。これらのベンチマークは言語処理能力に関する洞察を提供しますが、自然な会話やドメイン固有の用語の複雑さを完全に表現することはできません。 22 | 23 | ## 代替評価アプローチ 24 | 25 | 多くの組織は、標準ベンチマークの限界に対処するために代替評価方法を開発しています: 26 | 27 | ### LLM-as-Judge 28 | ある言語モデルを使用して別のモデルの出力を評価する方法がますます人気を集めています。このアプローチは、従来の指標よりも微妙なフィードバックを提供することができますが、それ自体のバイアスと限界も伴います。 29 | 30 | ### 評価アリーナ 31 | AnthropicのConstitutional AI Arenaのようなプラットフォームでは、モデルが相互に対話し、制御された環境で互いを評価することができます。これにより、従来のベンチマークでは明らかにならない強みと弱みが明らかになります。 32 | 33 | ### カスタムベンチマークスイート 34 | 組織は、特定のニーズやユースケースに合わせた内部ベンチマークスイートを開発することがよくあります。これには、ドメイン固有の知識テストや実際の展開条件を反映した評価シナリオが含まれることがあります。 35 | 36 | ## 独自の評価戦略の作成 37 | 38 | LightEvalを使用して標準ベンチマークを実行するのは簡単ですが、ユースケースに特化した評価方法の開発にも時間を投資する必要があります。 39 | 40 | 標準ベンチマークは有用なベースラインを提供しますが、それだけが評価方法であってはなりません。より包括的なアプローチを開発する方法は次のとおりです: 41 | 42 | 1. 関連する標準ベンチマークから始めて、ベースラインを確立し、他のモデルとの比較を可能にします。 43 | 44 | 2. ユースケースの特定の要件と課題を特定します。モデルが実際に実行するタスクは何ですか?どのようなエラーが最も問題になりますか? 45 | 46 | 3. 実際のユースケースを反映したカスタム評価データセットを開発します。これには次のようなものが含まれるかもしれません: 47 | - ドメインからの実際のユーザークエリ 48 | - 遭遇した一般的なエッジケース 49 | - 特に挑戦的なシナリオの例 50 | 51 | 4. 多層評価戦略の実装を検討します: 52 | - クイックフィードバックのための自動指標 53 | - 微妙な理解のための人間の評価 54 | - 専門家によるレビュー 55 | - 制御された環境でのA/Bテスト 56 | 57 | ## LightEvalを使用したベンチマーク 58 | 59 | LightEvalタスクは特定の形式を使用して定義されます: 60 | ``` 61 | {suite}|{task}|{num_few_shot}|{auto_reduce} 62 | ``` 63 | 64 | - **suite**: ベンチマークスイート(例:'mmlu', 'truthfulqa') 65 | - **task**: スイート内の特定のタスク(例:'abstract_algebra') 66 | - **num_few_shot**: プロンプトに含める例の数(ゼロショットの場合は0) 67 | - **auto_reduce**: プロンプトが長すぎる場合に少数ショットの例を自動的に削減するかどうか(0または1) 68 | 69 | 例:`"mmlu|abstract_algebra|0|0"`は、ゼロショット推論でMMLUの抽象代数学タスクを評価します。 70 | 71 | ### 評価パイプラインの例 72 | 73 | 特定のドメインに関連する自動ベンチマークの評価を設定して実行する完全な例を次に示します: 74 | 75 | ```python 76 | from lighteval.tasks import Task, Pipeline 77 | from transformers import AutoModelForCausalLM 78 | 79 | # 評価するタスクを定義 80 | domain_tasks = [ 81 | "mmlu|anatomy|0|0", 82 | "mmlu|high_school_biology|0|0", 83 | "mmlu|high_school_chemistry|0|0", 84 | "mmlu|professional_medicine|0|0" 85 | ] 86 | 87 | # パイプラインパラメータを設定 88 | pipeline_params = { 89 | "max_samples": 40, # 評価するサンプル数 90 | "batch_size": 1, # 推論のバッチサイズ 91 | "num_workers": 4 # ワーカープロセスの数 92 | } 93 | 94 | # 評価トラッカーを作成 95 | evaluation_tracker = EvaluationTracker( 96 | output_path="./results", 97 | save_generations=True 98 | ) 99 | 100 | # モデルを読み込み、パイプラインを作成 101 | model = AutoModelForCausalLM.from_pretrained("your-model-name") 102 | pipeline = Pipeline( 103 | tasks=domain_tasks, 104 | pipeline_parameters=pipeline_params, 105 | evaluation_tracker=evaluation_tracker, 106 | model=model 107 | ) 108 | 109 | # 評価を実行 110 | pipeline.evaluate() 111 | 112 | # 結果を取得して表示 113 | results = pipeline.get_results() 114 | pipeline.show_results() 115 | ``` 116 | 117 | 結果は次のような表形式で表示されます: 118 | ``` 119 | | Task |Version|Metric|Value | |Stderr| 120 | |----------------------------------------|------:|------|-----:|---|-----:| 121 | |all | |acc |0.3333|± |0.1169| 122 | |leaderboard:mmlu:_average:5 | |acc |0.3400|± |0.1121| 123 | |leaderboard:mmlu:anatomy:5 | 0|acc |0.4500|± |0.1141| 124 | |leaderboard:mmlu:high_school_biology:5 | 0|acc |0.1500|± |0.0819| 125 | ``` 126 | 127 | 結果をpandas DataFrameで処理し、視覚化や表現を自由に行うこともできます。 128 | 129 | # 次のステップ 130 | 131 | ⏩ [カスタムドメイン評価](./custom_evaluation.md)を探索し、特定のニーズに合わせた評価パイプラインの作成方法を学びましょう 132 | -------------------------------------------------------------------------------- /ja/4_evaluation/project/README.md: -------------------------------------------------------------------------------- 1 | # Argilla、Distilabel、LightEvalを使用したドメイン固有の評価 2 | 3 | ほとんどの人気のあるベンチマークは、一般的な能力(推論、数学、コード)を評価しますが、より具体的な能力を評価する必要がある場合はどうすればよいでしょうか? 4 | 5 | カスタムドメインに関連するモ���ルを評価する必要がある場合はどうすればよいでしょうか?(例えば、金融、法務、医療のユースケース) 6 | 7 | このチュートリアルでは、[Argilla](https://github.com/argilla-io/argilla)、[distilabel](https://github.com/argilla-io/distilabel)、および[LightEval](https://github.com/huggingface/lighteval)を使用して、関連するデータを作成し、サンプルに注釈を付け、モデルを評価するための完全なパイプラインを示します。例として、複数のドキュメントから試験問題を生成することに焦点を当てます。 8 | 9 | ## プロジェクト構造 10 | 11 | このプロセスでは、データセットの生成、注釈の追加、評価のためのサンプルの抽出、実際のモデル評価の4つのステップを実行します。各ステップにはスクリプトがあります。 12 | 13 | | スクリプト名 | 説明 | 14 | |-------------|-------------| 15 | | generate_dataset.py | 指定された言語モデルを使用して複数のテキストドキュメントから試験問題を生成します。 | 16 | | annotate_dataset.py | 生成された試験問題の手動注釈のためのArgillaデータセットを作成します。 | 17 | | create_dataset.py | Argillaから注釈付きデータを処理し、Hugging Faceデータセットを作成します。 | 18 | | evaluation_task.py | 試験問題データセットの評価のためのカスタムLightEvalタスクを定義します。 | 19 | 20 | ## ステップ 21 | 22 | ### 1. データセットの生成 23 | 24 | `generate_dataset.py`スクリプトは、distilabelライブラリを使用して複数のテキストドキュメントに基づいて試験問題を生成します。指定されたモデル(デフォルト:Meta-Llama-3.1-8B-Instruct)を使用して質問、正しい回答、および誤った回答(ディストラクター)を作成します。独自のデータサンプルを追加し、異なるモデルを使用することもできます。 25 | 26 | 生成を実行するには: 27 | 28 | ```sh 29 | python generate_dataset.py --input_dir path/to/your/documents --model_id your_model_id --output_path output_directory 30 | ``` 31 | 32 | これにより、入力ディレクトリ内のすべてのドキュメントに対して生成された試験問題を含む[Distiset](https://distilabel.argilla.io/dev/sections/how_to_guides/advanced/distiset/)が作成されます。 33 | 34 | ### 2. データセットの注釈 35 | 36 | `annotate_dataset.py`スクリプトは、生成された質問を取得し、注釈のためのArgillaデータセットを作成します。データセットの構造を設定し、生成された質問と回答をランダムな順序で入力します。これにより、バイアスを避けることができます。Argillaでは、正しい回答が提案として表示されます。 37 | 38 | LLMからの提案された正しい回答がランダムな順序で表示され、正しい回答を承認するか、別の回答を選択できます。このプロセスの所要時間は、評価データセットの規模、ドメインデータの複雑さ、およびLLMの品質によって異なります。例えば、Llama-3.1-70B-Instructを使用して、転移学習のドメインで150サンプルを1時間以内に作成できました。 39 | 40 | 注釈プロセスを実行するには: 41 | 42 | ```sh 43 | python annotate_dataset.py --dataset_path path/to/distiset --output_dataset_name argilla_dataset_name 44 | ``` 45 | 46 | これにより、手動レビューと注釈のためのArgillaデータセットが作成されます。 47 | 48 | ![argilla_dataset](./images/domain_eval_argilla_view.png) 49 | 50 | Argillaを使用していない場合は、この[クイックスタートガイド](https://docs.argilla.io/latest/getting_started/quickstart/)に従ってローカルまたはスペースにデプロイしてください。 51 | 52 | ### 3. データセットの作成 53 | 54 | `create_dataset.py`スクリプトは、Argillaから注釈付きデータを処理し、Hugging Faceデータセットを作成します。提案された回答と手動で注釈された回答の両方を処理します。このスクリプトは、質問、可能な回答、および正しい回答の列名を含むデータセットを作成します。最終データセットを作成するには: 55 | 56 | ```sh 57 | huggingface_hub login 58 | python create_dataset.py --dataset_path argilla_dataset_name --dataset_repo_id your_hf_repo_id 59 | ``` 60 | 61 | これにより、指定されたリポジトリにデータセットがHugging Face Hubにプッシュされます。サンプルデータセットは[こちら](https://huggingface.co/datasets/burtenshaw/exam_questions/viewer/default/train)で確認できます。データセットのプレビューは次のようになります: 62 | 63 | ![hf_dataset](./images/domain_eval_dataset_viewer.png) 64 | 65 | ### 4. 評価タスク 66 | 67 | `evaluation_task.py`スクリプトは、試験問題データセットの評価のためのカスタムLightEvalタスクを定義します。プロンプト関数、カスタム精度メトリック、およびタスク構成が含まれます。 68 | 69 | カスタム試験問題タスクを使用してlightevalでモデルを評価するには: 70 | 71 | ```sh 72 | lighteval accelerate \ 73 | --model_args "pretrained=HuggingFaceH4/zephyr-7b-beta" \ 74 | --tasks "community|exam_questions|0|0" \ 75 | --custom_tasks domain-eval/evaluation_task.py \ 76 | --output_dir "./evals" 77 | ``` 78 | 79 | 詳細なガイドはlighteval wikiで確認できます: 80 | 81 | - [カスタムタスクの作成](https://github.com/huggingface/lighteval/wiki/Adding-a-Custom-Task) 82 | - [カスタムメトリックの作成](https://github.com/huggingface/lighteval/wiki/Adding-a-New-Metric) 83 | - [既存のメトリックの使用](https://github.com/huggingface/lighteval/wiki/Metric-List) 84 | -------------------------------------------------------------------------------- /ja/4_evaluation/project/annotate_dataset.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import json 3 | from random import choices, sample 4 | 5 | import argilla as rg 6 | from distilabel.distiset import Distiset 7 | 8 | ################################################################################ 9 | # スクリプトのパラメータ 10 | ################################################################################ 11 | 12 | parser = argparse.ArgumentParser( 13 | description="Argillaを使用して試験問題データセットに注釈を付けます。" 14 | ) 15 | parser.add_argument( 16 | "--argilla_api_key", 17 | type=str, 18 | default="argilla.apikey", 19 | help="ArgillaのAPIキー", 20 | ) 21 | parser.add_argument( 22 | "--argilla_api_url", 23 | type=str, 24 | default="http://localhost:6900", 25 | help="ArgillaのAPI URL", 26 | ) 27 | parser.add_argument( 28 | "--dataset_path", 29 | type=str, 30 | default="exam_questions", 31 | help="試験問題データセットのパス", 32 | ) 33 | parser.add_argument( 34 | "--dataset_config", 35 | type=str, 36 | default="default", 37 | help="データセットの構成", 38 | ) 39 | parser.add_argument( 40 | "--dataset_split", 41 | type=str, 42 | default="train", 43 | help="使用するデータセットの分割", 44 | ) 45 | parser.add_argument( 46 | "--output_dataset_name", 47 | type=str, 48 | default="exam_questions", 49 | help="出力Argillaデータセットの名前", 50 | ) 51 | 52 | args = parser.parse_args() 53 | 54 | ################################################################################ 55 | # 検証のためのフィードバックタスクを使用してArgillaデータセットを作成 56 | ################################################################################ 57 | 58 | client = rg.Argilla(api_key=args.argilla_api_key, api_url=args.argilla_api_url) 59 | 60 | if client.datasets(args.output_dataset_name): 61 | print(f"既存のデータセット '{args.output_dataset_name}' を削除します") 62 | client.datasets(args.output_dataset_name).delete() 63 | 64 | settings = rg.Settings( 65 | fields=[ 66 | rg.TextField("question"), 67 | rg.TextField("answer_a"), 68 | rg.TextField("answer_b"), 69 | rg.TextField("answer_c"), 70 | rg.TextField("answer_d"), 71 | ], 72 | questions=[ 73 | rg.LabelQuestion( 74 | name="correct_answer", 75 | labels=["answer_a", "answer_b", "answer_c", "answer_d"], 76 | ), 77 | rg.TextQuestion( 78 | name="improved_question", 79 | description="質問を改善できますか?", 80 | ), 81 | rg.TextQuestion( 82 | name="improved_answer", 83 | description="最良の回答を改善できますか?", 84 | ), 85 | ], 86 | ) 87 | 88 | dataset = rg.Dataset(settings=settings, name=args.output_dataset_name) 89 | dataset.create() 90 | 91 | ################################################################################ 92 | # Distisetを読み込み、Argillaデータセットにレコードを処理して追加 93 | # バイアスを避けるために質問がランダムな順序で表示されることを確認します 94 | # ただし、Argilla UIでは正しい回答を提案として表示します。 95 | ################################################################################ 96 | 97 | distiset = Distiset.load_from_disk(args.dataset_path) 98 | answer_names = ["answer_a", "answer_b", "answer_c", "answer_d"] 99 | dataset_records = [] 100 | 101 | for exam in distiset[args.dataset_config][args.dataset_split]: 102 | exam_json = json.loads(exam["generation"])["exam"] 103 | 104 | for question in exam_json: 105 | answer = question["answer"] 106 | distractors = question["distractors"] 107 | distractors = choices(distractors, k=3) 108 | answers = distractors + [answer] 109 | answers = sample(answers, len(answers)) 110 | suggestion_idx = answers.index(answer) 111 | fields = dict(zip(answer_names, answers)) 112 | fields["question"] = question["question"] 113 | 114 | record = rg.Record( 115 | fields=fields, 116 | suggestions=[ 117 | rg.Suggestion( 118 | question_name="correct_answer", 119 | value=answer_names[suggestion_idx], 120 | ) 121 | ], 122 | ) 123 | dataset_records.append(record) 124 | 125 | dataset.records.log(dataset_records) 126 | 127 | print( 128 | f"データセット '{args.output_dataset_name}' がArgillaに作成され、入力されました。" 129 | ) 130 | -------------------------------------------------------------------------------- /ja/4_evaluation/project/create_dataset.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | import argilla as rg 4 | from datasets import Dataset 5 | 6 | ################################################################################ 7 | # スクリプトのパラメータ 8 | ################################################################################ 9 | 10 | parser = argparse.ArgumentParser( 11 | description="注釈付きArgillaデータからHugging Faceデータセットを作成します。" 12 | ) 13 | parser.add_argument( 14 | "--argilla_api_key", 15 | type=str, 16 | default="argilla.apikey", 17 | help="ArgillaのAPIキー", 18 | ) 19 | parser.add_argument( 20 | "--argilla_api_url", 21 | type=str, 22 | default="http://localhost:6900", 23 | help="ArgillaのAPI URL", 24 | ) 25 | parser.add_argument( 26 | "--dataset_path", 27 | type=str, 28 | default="exam_questions", 29 | help="Argillaデータセットのパス", 30 | ) 31 | parser.add_argument( 32 | "--dataset_repo_id", 33 | type=str, 34 | default="burtenshaw/exam_questions", 35 | help="Hugging FaceデータセットリポジトリID", 36 | ) 37 | 38 | args = parser.parse_args() 39 | 40 | ################################################################################ 41 | # Argillaクライアントを初期化し、データセットを読み込む 42 | ################################################################################ 43 | 44 | client = rg.Argilla(api_key=args.argilla_api_key, api_url=args.argilla_api_url) 45 | dataset = client.datasets(args.dataset_path) 46 | 47 | ################################################################################ 48 | # Argillaレコードを処理 49 | ################################################################################ 50 | 51 | dataset_rows = [] 52 | 53 | for record in dataset.records(with_suggestions=True, with_responses=True): 54 | row = record.fields 55 | 56 | if len(record.responses) == 0: 57 | answer = record.suggestions["correct_answer"].value 58 | row["correct_answer"] = answer 59 | else: 60 | for response in record.responses: 61 | if response.question_name == "correct_answer": 62 | row["correct_answer"] = response.value 63 | dataset_rows.append(row) 64 | 65 | ################################################################################ 66 | # Hugging Faceデータセットを作成し、Hubにプッシュ 67 | ################################################################################ 68 | 69 | hf_dataset = Dataset.from_list(dataset_rows) 70 | hf_dataset.push_to_hub(repo_id=args.dataset_repo_id) 71 | 72 | print(f"データセットが{args.dataset_repo_id}に正常にプッシュされました") 73 | -------------------------------------------------------------------------------- /ja/4_evaluation/project/evaluation_task.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | from lighteval.tasks.lighteval_task import LightevalTaskConfig 4 | from lighteval.tasks.requests import Doc 5 | from lighteval.metrics.utils.metric_utils import ( 6 | SampleLevelMetric, 7 | MetricCategory, 8 | MetricUseCase, 9 | ) 10 | 11 | ################################################################################ 12 | # データセットの構造に基づいてプロンプト関数を定義 13 | ################################################################################ 14 | 15 | 16 | def prompt_fn(line, task_name: str = None): 17 | """データセットの行を評価用のDocオブジェクトに変換します。""" 18 | instruction = "次の試験問題に対して正しい答えを選んでください:" 19 | return Doc( 20 | task_name=task_name, 21 | query=f"{instruction} {line['question']}", 22 | choices=[ 23 | f" {line['answer_a']}", 24 | f" {line['answer_b']}", 25 | f" {line['answer_c']}", 26 | f" {line['answer_d']}", 27 | ], 28 | gold_index=["answer_a", "answer_b", "answer_c", "answer_d"].index( 29 | line["correct_answer"] 30 | ), 31 | instruction=instruction, 32 | ) 33 | 34 | 35 | ################################################################################ 36 | # カスタムメトリックを定義 37 | # ガイドに基づいて https://github.com/huggingface/lighteval/wiki/Adding-a-New-Metric 38 | # または既存のメトリックを使用 https://github.com/huggingface/lighteval/wiki/Metric-List 39 | # 既存のメトリックは lighteval.metrics.metrics からインポート可能 40 | ################################################################################ 41 | 42 | 43 | def sample_level_fn(formatted_doc: Doc, **kwargs) -> bool: 44 | response = np.argmin(kwargs["choices_logprob"]) 45 | return response == formatted_doc.gold_index 46 | 47 | 48 | custom_metric = SampleLevelMetric( 49 | metric_name="exam_question_accuracy", 50 | higher_is_better=True, 51 | category=MetricCategory.MULTICHOICE, 52 | use_case=MetricUseCase.NONE, 53 | sample_level_fn=sample_level_fn, 54 | corpus_level_fn=np.mean, 55 | ) 56 | 57 | ################################################################################ 58 | # プロンプト関数とカスタムメトリックに基づいてタスクを定義 59 | # ガイドに基づいて https://github.com/huggingface/lighteval/wiki/Adding-a-Custom-Task 60 | ################################################################################ 61 | 62 | task = LightevalTaskConfig( 63 | name="example", 64 | prompt_function=prompt_fn, 65 | suite=["community"], 66 | hf_repo="burtenshaw/exam_questions", 67 | hf_subset="default", 68 | hf_avail_splits=["train"], 69 | evaluation_splits=["train"], 70 | few_shots_split=None, 71 | few_shots_select=None, 72 | metric=[custom_metric], 73 | ) 74 | 75 | # TASKS_TABLEにタスクを追加 76 | TASKS_TABLE = [task] 77 | 78 | # モジュールロジック 79 | if __name__ == "__main__": 80 | print([t.name for t in TASKS_TABLE]) 81 | print(len(TASKS_TABLE)) 82 | 83 | # lighteval accelerate \ 84 | # "pretrained=HuggingFaceTB/SmolLM2-135M-Instruct" \ 85 | # "community|example|0|0" \ 86 | # --custom-tasks "submitted_tasks/example.py" \ 87 | # --output-dir "results" 88 | -------------------------------------------------------------------------------- /ja/5_vision_language_models/README.md: -------------------------------------------------------------------------------- 1 | # ビジョン言語モデル 2 | 3 | ## 1. VLMの使用 4 | 5 | ビジョン言語モデル(VLM)は、画像キャプション生成、視覚質問応答、マルチモーダル推論などのタスクを可能にするために、テキストと並行して画像入力を処理します。 6 | 7 | 典型的なVLMアーキテクチャは、視覚的特徴を抽出する画像エンコーダ、視覚的およびテキスト表現を整列させるプロジェクション層、およびテキストを処理または生成する言語モデルで構成されます。これにより、モデルは視覚要素と言語概念の間の接続を確立できます。 8 | 9 | VLMは、使用ケースに応じてさまざまな構成で使用できます。ベースモデルは一般的なビジョン言語タスクを処理し、チャット最適化されたバリアントは会話型インタラクションをサポートします。一部のモデルには、視覚的証拠に基づいて予測を行うための追加コンポーネントや、物体検出などの特定のタスクに特化したコンポーネントが含まれています。 10 | 11 | VLMの技術的な詳細と使用方法については、[VLMの使用](./vlm_usage.md)ページを参照してください。 12 | 13 | ## 2. VLMのファインチューニング 14 | 15 | VLMのファインチューニングは、特定のタスクを実行するため、または特定のデータセットで効果的に動作するように、事前トレーニングされたモデルを適応させるプロセスです。このプロセスは、モジュール1および2で紹介されたように、教師ありファインチューニング、好みの最適化、またはその両方を組み合わせたハイブリッドアプローチなどの方法論に従うことができます。 16 | 17 | コアツールと技術はLLMで使用されるものと似ていますが、VLMのファインチューニングには、画像のデータ表現と準備に特に注意を払う必要があります。これにより、モデルが視覚データとテキストデータの両方を効果的に統合および処理し、最適なパフォーマンスを発揮できるようになります。デモモデルであるSmolVLMは、前のモジュールで使用された言語モデルよりも大幅に大きいため、効率的なファインチューニング方法を探ることが重要です。量子化やPEFTなどの技術を使用することで、プロセスをよりアクセスしやすく、コスト効果の高いものにし、より多くのユーザーがモデルを試すことができます。 18 | 19 | VLMのファインチューニングに関する詳細なガイダンスについては、[VLMのファインチューニング](./vlm_finetuning.md)ページを参照してください。 20 | 21 | ## 演習ノートブック 22 | 23 | | タイトル | 説明 | 演習 | リンク | Colab | 24 | |-------|-------------|----------|------|-------| 25 | | VLMの使用 | 事前トレーニングされたVLMをさまざまなタスクに使用する方法を学ぶ | 🐢 画像を処理する
🐕 バッチ処理で複数の画像を処理する
🦁 ビデオ全体を処理する | [ノートブック](./notebooks/vlm_usage_sample.ipynb) | Open In Colab | 26 | | VLMのファインチューニング | タスク固有のデータセットに対して事前トレーニングされたVLMをファインチューニングする方法を学ぶ | 🐢 基本的なデータセットを使用してファインチューニングする
🐕 新しいデータセットを試す
🦁 代替のファインチューニング方法を試す | [ノートブック](./notebooks/vlm_sft_sample.ipynb) | Open In Colab | 27 | 28 | ## 参考文献 29 | - [Hugging Face Learn: Supervised Fine-Tuning VLMs](https://huggingface.co/learn/cookbook/fine_tuning_vlm_trl) 30 | - [Hugging Face Learn: Supervised Fine-Tuning SmolVLM](https://huggingface.co/learn/cookbook/fine_tuning_smol_vlm_sft_trl) 31 | - [Hugging Face Learn: Preference Optimization Fine-Tuning SmolVLM](https://huggingface.co/learn/cookbook/fine_tuning_vlm_dpo_smolvlm_instruct) 32 | - [Hugging Face Blog: Preference Optimization for VLMs](https://huggingface.co/blog/dpo_vlm) 33 | - [Hugging Face Blog: Vision Language Models](https://huggingface.co/blog/vlms) 34 | - [Hugging Face Blog: SmolVLM](https://huggingface.co/blog/smolvlm) 35 | - [Hugging Face Model: SmolVLM-Instruct](https://huggingface.co/HuggingFaceTB/SmolVLM-Instruct) 36 | - [CLIP: Learning Transferable Visual Models from Natural Language Supervision](https://arxiv.org/abs/2103.00020) 37 | - [Align Before Fuse: Vision and Language Representation Learning with Momentum Distillation](https://arxiv.org/abs/2107.07651) 38 | -------------------------------------------------------------------------------- /ja/5_vision_language_models/images/VLM_Architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/ja/5_vision_language_models/images/VLM_Architecture.png -------------------------------------------------------------------------------- /ja/5_vision_language_models/images/VLM_Process.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/ja/5_vision_language_models/images/VLM_Process.png -------------------------------------------------------------------------------- /ja/5_vision_language_models/images/VLM_Usage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/ja/5_vision_language_models/images/VLM_Usage.png -------------------------------------------------------------------------------- /ja/5_vision_language_models/vlm_usage.md: -------------------------------------------------------------------------------- 1 | # ビジュアル言語モデル 2 | 3 | ビジュアル言語モデル(VLM)は、画像とテキストの間のギャップを埋め、画像キャプションの生成、視覚に基づく質問への回答、テキストと視覚データの関係の理解などの高度なタスクを可能にします。そのアーキテクチャは、両方のモダリティをシームレスに処理するように設計されています。 4 | 5 | ### アーキテクチャ 6 | 7 | VLMは、画像処理コンポーネントとテキスト生成モデルを組み合わせて、統一された理解を実現します。主な要素は次のとおりです: 8 | 9 | ![VLMアーキテクチャ](./images/VLM_Architecture.png) 10 | 11 | - **画像エンコーダ**:生の画像をコンパクトな数値表現に変換します。CLIPやビジョントランスフォーマー(ViT)などの事前トレーニングされたエンコーダが一般的に使用されます。 12 | - **埋め込みプロジェクタ**:画像特徴をテキスト埋め込みと互換性のある空間にマッピングします。通常、密な層や線形変換を使用します。 13 | - **テキストデコーダ**:マルチモーダル情報を翻訳して一貫したテキストを生成する言語生成コンポーネントです。LlamaやVicunaなどの生成モデルが例として挙げられます。 14 | - **マルチモーダルプロジェクタ**:画像とテキストの表現をブレンドするための追加の層を提供します。LLaVAのようなモデルでは、2つのモダリティ間の強力な接続を確立するために重要です。 15 | 16 | ほとんどのVLMは、事前トレーニングされた画像エンコーダとテキストデコーダを活用し、ペアになった画像テキストデータセットで追加のファインチューニングを行います。このアプローチにより、効率的なトレーニングが可能になり、モデルが効果的に一般化できるようになります。 17 | 18 | ### 使用方法 19 | 20 | ![VLMプロセス](./images/VLM_Process.png) 21 | 22 | VLMは、さまざまなマルチモーダルタスクに適用されます。その適応性により、さまざまなドメインで異なるレベルのファインチューニングを行うことができます: 23 | 24 | - **画像キャプション生成**:画像の説明を生成します。 25 | - **視覚質問応答(VQA)**:画像の内容に関する質問に答えます。 26 | - **クロスモーダル検索**:特定の画像に対応するテキストを見つける、またはその逆を行います。 27 | - **クリエイティブなアプリケーション**:デザイン支援、アート生成、魅力的なマルチメディアコンテンツの作成などに役立ちます。 28 | 29 | ![VLMの使用](./images/VLM_Usage.png) 30 | 31 | VLMのトレーニングとファインチューニングには、画像とテキストの注釈がペアになった高品質なデータセットが必要です。Hugging Faceの`transformers`ライブラリなどのツールを使用すると、事前トレーニングされたVLMに簡単にアクセスでき、カスタムファインチューニングのワークフローが簡素化されます。 32 | 33 | ### チャット形式 34 | 35 | 多くのVLMは、使いやすさを向上させるためにチャットボットのような形式で構造化されています。この形式には次の要素が含まれます: 36 | 37 | - モデルの役割やコンテキストを設定する**システムメッセージ**(例:「あなたは視覚データを分析するアシスタントです」)。 38 | - テキスト入力と関連する画像を組み合わせた**ユーザークエリ**。 39 | - マルチモーダル分析から得られたテキスト出力を提供する**アシスタントの応答**。 40 | 41 | この会話形式は直感的であり、特にカスタマーサービスや教育ツールなどのインタラクティブなアプリケーションにおいて、ユーザーの期待に沿ったものです。 42 | 43 | フォーマットされた入力の例を次に示します: 44 | 45 | ```json 46 | [ 47 | { 48 | "role": "system", 49 | "content": [{"type": "text", "text": "あなたはチャート画像の視覚データを解釈する専門のビジュアル言語モデルです..."}] 50 | }, 51 | { 52 | "role": "user", 53 | "content": [ 54 | {"type": "image", "image": ""}, 55 | {"type": "text", "text": "棒グラフの最高値は何ですか?"} 56 | ] 57 | }, 58 | { 59 | "role": "assistant", 60 | "content": [{"type": "text", "text": "42"}] 61 | } 62 | ] 63 | ``` 64 | 65 | **複数の画像やビデオの処理** 66 | 67 | VLMは、入力構造を適応させることで、複数の画像やビデオを処理することもできます。ビデオの場合、フレームを抽出して個々の画像として処理し、時間順序を維持します。 68 | 69 | ## リソース 70 | 71 | - [Hugging Face Blog: Vision Language Models](https://huggingface.co/blog/vlms) 72 | - [Hugging Face Blog: SmolVLM](https://huggingface.co/blog/smolvlm) 73 | 74 | ## 次のステップ 75 | 76 | ⏩ SMOLVLMのさまざまな使用方法を試すには、[vlm_usage_sample.ipynb](./notebooks/vlm_usage_sample.ipynb)を試してください。 77 | -------------------------------------------------------------------------------- /ja/6_synthetic_datasets/README.md: -------------------------------------------------------------------------------- 1 | # 合成データセット 2 | 3 | 合成データは、実際の使用状況を模倣する人工的に生成されたデータです。データセットを拡張または強化することで、データの制限を克服することができます。合成データはすでにいくつかのユースケースで使用されていましたが、大規模な言語モデルは、言語モデルの事前および事後トレーニング、および評価のための合成データセットをより一般的にしました。 4 | 5 | 私たちは、検証済みの研究論文に基づいた迅速で信頼性が高くスケーラブルなパイプラインを必要とするエンジニアのための合成データとAIフィードバックのフレームワークである[`distilabel`](https://distilabel.argilla.io/latest/)を使用します。パッケージとベストプラクティスの詳細については、[ドキュメント](https://distilabel.argilla.io/latest/)を参照してください。 6 | 7 | ## モジュール概要 8 | 9 | 言語モデルの合成データは、インストラクション、嗜好、批評の3つの分類に分類できます。私たちは、インストラクションチューニングと嗜好調整のためのデータセットの生成に焦点を当てます。両方のカテゴリでは、既存のデータをモデルの批評とリライトで改善するための第3のカテゴリの側面もカバーします。 10 | 11 | ![合成データの分類](./images/taxonomy-synthetic-data.png) 12 | 13 | ## コンテンツ 14 | 15 | ### 1. [インストラクションデータセット](./instruction_datasets.md) 16 | 17 | インストラクションチューニングのためのインストラクションデータセットの生成方法を学びます。基本的なプロンプトを使用してインストラクションチューニングデータセットを作成する方法や、論文から得られたより洗練された技術を使用する方法を探ります。SelfInstructやMagpieのような方法を使用して、インコンテキスト学習のためのシードデータを使用してインストラクションチューニングデータセットを作成できます。さらに、EvolInstructを通じたインストラクションの進化についても探ります。[学び始める](./instruction_datasets.md)。 18 | 19 | ### 2. [嗜好データセット](./preference_datasets.md) 20 | 21 | 嗜好調整のための嗜好データセットの生成方法を学びます。セクション1で紹介した方法と技術を基に構築し、追加の応答を生成します。次に、EvolQualityプロンプトを使用して応答を改善する方法を学びます。最後に、スコアと批評を生成するUltraFeedbackプロンプトを探り、嗜好ペアを作成します。[学び始める](./preference_datasets.md)。 22 | 23 | ### 演習ノートブック 24 | 25 | | タイトル | 説明 | 演習 | リンク | Colab | 26 | |-------|-------------|----------|------|-------| 27 | | インストラクションデータセット | インストラクションチューニングのためのデータセットを生成する | 🐢 インストラクションチューニングデータセットを生成する
🐕 シードデータを使用してインストラクションチューニングのためのデータセットを生成する
🦁 シードデータとインストラクションの進化を使用してインストラクションチューニングのためのデータセットを生成する | [リンク](./notebooks/instruction_sft_dataset.ipynb) | [Colab](https://githubtocolab.com/huggingface/smol-course/tree/main/6_synthetic_datasets/notebooks/instruction_sft_dataset.ipynb) | 28 | | 嗜好データセット | 嗜好調整のためのデータセットを生成する | 🐢 嗜好調整データセットを生成する
🐕 応答の進化を使用して嗜好調整のためのデータセットを生成する
🦁 応答の進化と批評を使用して嗜好調整のためのデータセットを生成する | [リンク](./notebooks/preference_alignment_dataset.ipynb) | [Colab](https://githubtocolab.com/huggingface/smol-course/tree/main/6_synthetic_datasets/notebooks/preference_alignment_dataset.ipynb) | 29 | 30 | ## リソース 31 | 32 | - [Distilabel Documentation](https://distilabel.argilla.io/latest/) 33 | - [Synthetic Data Generator is UI app](https://huggingface.co/blog/synthetic-data-generator) 34 | - [SmolTalk](https://huggingface.co/datasets/HuggingFaceTB/smoltalk) 35 | - [Self-instruct](https://arxiv.org/abs/2212.10560) 36 | - [Evol-Instruct](https://arxiv.org/abs/2304.12244) 37 | - [Magpie](https://arxiv.org/abs/2406.08464) 38 | - [UltraFeedback](https://arxiv.org/abs/2310.01377) 39 | - [Deita](https://arxiv.org/abs/2312.15685) 40 | -------------------------------------------------------------------------------- /ja/6_synthetic_datasets/images/pipeline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/ja/6_synthetic_datasets/images/pipeline.png -------------------------------------------------------------------------------- /ja/6_synthetic_datasets/images/taxonomy-synthetic-data.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/ja/6_synthetic_datasets/images/taxonomy-synthetic-data.png -------------------------------------------------------------------------------- /ja/6_synthetic_datasets/notebooks/instruction_sft_dataset.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# インストラクションチューニングのためのデータセットを生成する\n", 8 | "\n", 9 | "このノートブックでは、インストラクションチューニングのためのデータセットを生成するプロセスを案内します。`distilabel`パッケージを使用してインストラクションチューニングのためのデータセットを生成します。\n", 10 | "\n", 11 | "それでは、インストラクションチューニングデータセットを見てみましょう。\n", 12 | "\n", 13 | "
\n", 14 | "

演習: インストラクションチューニングのためのデータセットを生成する

\n", 15 | "

インストラクションチューニングのためのデータセットを生成する方法を見たので、実際にインストラクションチューニングのためのデータセットを生成してみましょう。

\n", 16 | "

難易度レベル

\n", 17 | "

🐢 インストラクションチューニングデータセットを生成する

\n", 18 | "

🐕 シードデータを使用してインストラクションチューニングのためのデータセットを生成する

\n", 19 | "

🦁 シードデータとインストラクションの進化を使用してインストラクションチューニングのためのデータセットを生成する

\n", 20 | "
" 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "metadata": { 26 | "vscode": { 27 | "languageId": "plaintext" 28 | } 29 | }, 30 | "source": [ 31 | "## 依存関係のインストール\n", 32 | "\n", 33 | "transformersの代わりに、`vllm`や`hf-inference-endpoints`をインストールすることもできます。" 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": null, 39 | "metadata": {}, 40 | "outputs": [], 41 | "source": [ 42 | "!pip install \"distilabel[hf-transformers,outlines,instructor]\"" 43 | ] 44 | }, 45 | { 46 | "cell_type": "markdown", 47 | "metadata": {}, 48 | "source": [ 49 | "## 合成の開始\n", 50 | "\n", 51 | "前のコース内容で見たように、インストラクションデータセット生成のためのdistilabelパイプラインを作成できます。最低限のパイプラインはすでに提供されています。このパイプラインをスケールアップして、インストラクションチューニングのための大規模なデータセットを生成してください。モデル、モデルプロバイダー、生成引数を入れ替えて、データセットの品質にどのように影響するかを確認してください。小規模に実験し、後でスケールアップしましょう。\n", 52 | "\n", 53 | "[distilabelコンポーネントギャラリー](https://distilabel.argilla.io/latest/components-gallery/)で、処理クラスの情報とその使用方法を確認してください。\n", 54 | "\n", 55 | "辞書からデータをロードする代わりに、Hubからデータをロードする例を以下に示します。\n", 56 | "\n", 57 | "```python\n", 58 | "from datasets import load_dataset\n", 59 | "\n", 60 | "with Pipeline(...) as pipeline:\n", 61 | " ...\n", 62 | "\n", 63 | "if __name__ == \"__main__:\n", 64 | " dataset = load_dataset(\"my-dataset\", split=\"train\")\n", 65 | " distiset = pipeline.run(dataset=dataset)\n", 66 | "```\n", 67 | "\n", 68 | "パイプラインを実行した後、データセットをHubにプッシュするのを忘れないでください!" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "execution_count": null, 74 | "metadata": {}, 75 | "outputs": [], 76 | "source": [ 77 | "from distilabel.llms import TransformersLLM\n", 78 | "from distilabel.pipeline import Pipeline\n", 79 | "from distilabel.steps import LoadDataFromDicts\n", 80 | "from distilabel.steps.tasks import TextGeneration\n", 81 | "\n", 82 | "with Pipeline() as pipeline:\n", 83 | " data = LoadDataFromDicts(data=[{\"instruction\": \"Hugging Faceの小規模AIモデルに関するSmol-Courseについての短い質問を生成してください。\"}])\n", 84 | " llm = TransformersLLM(model=\"HuggingFaceTB/SmolLM2-1.7B-Instruct\")\n", 85 | " gen_a = TextGeneration(llm=llm, output_mappings={\"generation\": \"instruction\"})\n", 86 | " gen_b = TextGeneration(llm=llm, output_mappings={\"generation\": \"response\"})\n", 87 | " data >> gen_a >> gen_b\n", 88 | "\n", 89 | "if __name__ == \"__main__\":\n", 90 | " distiset = pipeline.run(use_cache=False)\n", 91 | " distiset.push_to_hub(\"huggingface-smol-course-instruction-tuning-dataset\")" 92 | ] 93 | }, 94 | { 95 | "cell_type": "markdown", 96 | "metadata": {}, 97 | "source": [ 98 | "## 🌯 まとめ\n", 99 | "\n", 100 | "インストラクションチューニングのためのデータセットを生成する方法を見てきました。これを使用して次のことができます:\n", 101 | "\n", 102 | "- インストラクションチューニングのためのデータセットを生成する。\n", 103 | "- インストラクションチューニングのための評価データセットを作成する。\n", 104 | "\n", 105 | "次に\n", 106 | "\n", 107 | "🧑‍🏫 学ぶ - [preference datasetsの生成](./preference_datasets.md)について学ぶ\n", 108 | "🏋️‍♂️ 合成データセットに基づいて[インストラクションチューニングの章](../../1_instruction_tuning/README.md)でモデルを微調整する\n" 109 | ] 110 | } 111 | ], 112 | "metadata": { 113 | "language_info": { 114 | "name": "python" 115 | } 116 | }, 117 | "nbformat": 4, 118 | "nbformat_minor": 2 119 | } 120 | -------------------------------------------------------------------------------- /ja/6_synthetic_datasets/notebooks/preference_dpo_dataset.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 嗜好調整のためのデータセットを生成する\n", 8 | "\n", 9 | "このノートブックでは、嗜好調整のためのデータセットを生成するプロセスを案内します。`distilabel`パッケージを使用して嗜好調整のためのデータセットを生成します。\n", 10 | "\n", 11 | "それでは、嗜好調整データセットを見てみましょう。\n", 12 | "\n", 13 | "
\n", 14 | "

演習: 嗜好調整のためのデータセットを生成する

\n", 15 | "

嗜好調整のためのデータセットを生成する方法を見たので、実際に嗜好調整のためのデータセットを生成してみましょう。

\n", 16 | "

難易度レベル

\n", 17 | "

🐢 嗜好調整のためのデータセットを生成する

\n", 18 | "

🐕 応答の進化を使用して嗜好調整のためのデータセットを生成する

\n", 19 | "

🦁 応答の進化とモデルプーリングを使用して嗜好調整のためのデータセットを生成する

\n", 20 | "
" 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "metadata": { 26 | "vscode": { 27 | "languageId": "plaintext" 28 | } 29 | }, 30 | "source": [ 31 | "## 依存関係のインストール\n", 32 | "\n", 33 | "transformersの代わりに、`vllm`や`hf-inference-endpoints`をインストールすることもできます。" 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": null, 39 | "metadata": {}, 40 | "outputs": [], 41 | "source": [ 42 | "!pip install \"distilabel[hf-transformers,outlines,instructor]\"" 43 | ] 44 | }, 45 | { 46 | "cell_type": "markdown", 47 | "metadata": {}, 48 | "source": [ 49 | "## 合成の開始\n", 50 | "\n", 51 | "前のノートブックで見たように、嗜好データセット生成のためのdistilabelパイプラインを作成できます。最低限のパイプラインはすでに提供されています。このパイプラインをスケールアップして、嗜好調整のための大規模なデータセットを生成してください。モデル、モデルプロバイダー、生成引数を入れ替えて、データセットの品質にどのように影響するかを確認してください。小規模に実験し、後でスケールアップしましょう。\n", 52 | "\n", 53 | "[distilabelコンポーネントギャラリー](https://distilabel.argilla.io/latest/components-gallery/)で、処理クラスの情報とその使用方法を確認してください。\n", 54 | "\n", 55 | "辞書からデータをロードする代わりに、Hubからデータをロードする例を以下に示します。\n", 56 | "\n", 57 | "```python\n", 58 | "from datasets import load_dataset\n", 59 | "\n", 60 | "with Pipeline(...) as pipeline:\n", 61 | " ...\n", 62 | "\n", 63 | "if __name__ == \"__main__:\n", 64 | " dataset = load_dataset(\"my-dataset\", split=\"train\")\n", 65 | " distiset = pipeline.run(dataset=dataset)\n", 66 | "```\n", 67 | "\n", 68 | "パイプラインを実行した後、データセットをHubにプッシュするのを忘れないでください!" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "execution_count": null, 74 | "metadata": {}, 75 | "outputs": [], 76 | "source": [ 77 | "from distilabel.llms import TransformersLLM\n", 78 | "from distilabel.pipeline import Pipeline\n", 79 | "from distilabel.steps import GroupColumns, LoadDataFromDicts\n", 80 | "from distilabel.steps.tasks import TextGeneration\n", 81 | "\n", 82 | "with Pipeline() as pipeline:\n", 83 | " data = LoadDataFromDicts(data=[{\"instruction\": \"合成データとは何ですか?\"}])\n", 84 | " llm_a = TransformersLLM(model=\"HuggingFaceTB/SmolLM2-1.7B-Instruct\")\n", 85 | " gen_a = TextGeneration(llm=llm_a)\n", 86 | " llm_b = TransformersLLM(model=\"Qwen/Qwen2.5-1.5B-Instruct\")\n", 87 | " gen_b = TextGeneration(llm=llm_b)\n", 88 | " group = GroupColumns(columns=[\"generation\"])\n", 89 | " data >> [gen_a, gen_b] >> group\n", 90 | "\n", 91 | "if __name__ == \"__main__\":\n", 92 | " distiset = pipeline.run()\n", 93 | " distiset.push_to_hub(\"huggingface-smol-course-preference-tuning-dataset\")" 94 | ] 95 | }, 96 | { 97 | "cell_type": "markdown", 98 | "metadata": {}, 99 | "source": [ 100 | "## 🌯 まとめ\n", 101 | "\n", 102 | "嗜好調整のためのデータセットを生成する方法を見てきました。これを使用して次のことができます:\n", 103 | "\n", 104 | "- 嗜好調整のためのデータセットを生成する。\n", 105 | "- 嗜好調整のための評価データセットを作成する。\n", 106 | "\n", 107 | "次に\n", 108 | "\n", 109 | "🏋️‍♂️ 合成データセットに基づいて[嗜好調整の章](../../2_preference_alignment/README.md)でモデルを微調整する\n" 110 | ] 111 | } 112 | ], 113 | "metadata": { 114 | "language_info": { 115 | "name": "python" 116 | } 117 | }, 118 | "nbformat": 4, 119 | "nbformat_minor": 2 120 | } 121 | -------------------------------------------------------------------------------- /ja/README.md: -------------------------------------------------------------------------------- 1 | ![smolcourse image](../banner.png) 2 | 3 | # スモールコース 4 | 5 | これは、特定のユースケースに合わせて言語モデルを調整するための実践的なコースです。ほとんどのローカルマシンで実行できるため、言語モデルの調整を始めるのに便利です。GPUの要件は最小限で、有料サービスは必要ありません。このコースは[SmolLM2](https://github.com/huggingface/smollm/tree/main)シリーズのモデルに基づいていますが、ここで学んだスキルを大規模なモデルや他の小型言語モデルに転用することができます。 6 | 7 | 8 | 9 | 10 | 11 |
12 |

参加は無料で、今すぐ始められます!

13 |

このコースはオープンでピアレビューされています。コースに参加するには、プルリクエストを開くことで、あなたの作業をレビューに提出してください。以下の手順に従ってください:

14 |
    15 |
  1. リポジトリをフォークします こちら
  2. 16 |
  3. 資料を読み、変更を加え、演習を行い、自分の例を追加します。
  4. 17 |
  5. december_2024ブランチでプルリクエストを開きます
  6. 18 |
  7. レビューを受けてマージされます
  8. 19 |
20 |

これにより、学習を助け、常に改善されるコミュニティ主導のコースを構築することができます。

21 |
22 | 23 | このプロセスについては、この[ディスカッションスレッド](https://github.com/huggingface/smol-course/discussions/2#discussion-7602932)で議論できます。 24 | 25 | ## コース概要 26 | 27 | このコースは、小型言語モデルを使用した実践的なアプローチを提供し、初期のトレーニングから本番展開までをカバーします。 28 | 29 | | モジュール | 説明 | ステータス | リリース日 | 30 | |--------|-------------|---------|--------------| 31 | | [インストラクションチューニング](./1_instruction_tuning) | 教師あり微調整、チャットテンプレート、および基本的な指示に従う方法を学びます | ✅ 準備完了 | 2024年12月3日 | 32 | | [選好整合](./2_preference_alignment) | DPOおよびORPO技術を探求し、人間の選好にモデルを整合させる方法を学びます | ✅ 準備完了 | 2024年12月6日 | 33 | | [パラメータ効率の良い微調整](./3_parameter_efficient_finetuning) | LoRA、プロンプトチューニング、および効率的な適応方法を学びます | ✅ 準備完了 | 2024年12月9日 | 34 | | [評価](./4_evaluation) | 自動ベンチマークを使用し、カスタムドメイン評価を作成する方法を学びます | ✅ 準備完了 | 2024年12月13日 | 35 | | [ビジョン言語モデル](./5_vision_language_models) | マルチモーダルモデルをビジョン言語タスクに適応させる方法を学びます | ✅ 準備完了 | 2024年12月16日 | 36 | | [合成データセット](./6_synthetic_datasets) | トレーニング用の合成データセットを作成し、検証する方法を学びます | ✅ 準備完了 | 2024年12月20日 | 37 | | [推論](./7_inference) | モデルを効率的に推論する方法を学びます | [🚧 作業中](https://github.com/huggingface/smol-course/pull/150) | 2025年1月8日 | 38 | | [エージェント](./8_agents) | 自分のエージェントAIを構築する方法を学びます | ✅ 準備完了 | 2025年1月13日 || 39 | | キャップストーンプロジェクト | 学んだことを使ってリーダーボードを登りましょう! | [🚧 作業中](https://github.com/huggingface/smol-course/pull/97) | 2025年1月10日 | 40 | 41 | ## なぜ小型言語モデルなのか? 42 | 43 | 大規模な言語モデルは印象的な能力を示していますが、しばしば多くの計算リソースを必要とし、特定のアプリケーションには過剰な場合があります。小型言語モデルは、ドメイン固有のアプリケーションに対していくつかの利点を提供します: 44 | 45 | - **効率性**:トレーニングと展開に必要な計算リソースが大幅に少ない 46 | - **カスタマイズ**:特定のドメインに簡単に微調整および適応可能 47 | - **制御**:モデルの動作をよりよく理解し、制御できる 48 | - **コスト**:トレーニングと推論の運用コストが低い 49 | - **プライバシー**:データを外部APIに送信せずにローカルで実行可能 50 | - **グリーンテクノロジー**:リソースの効率的な使用を推進し、炭素排出量を削減 51 | - **学術研究の容易さ**:最先端のLLMを使用した学術研究のための簡単なスターターを提供し、物流の制約を減らす 52 | 53 | ## 前提条件 54 | 55 | 開始する前に、以下を確認してください: 56 | - 機械学習と自然言語処理の基本的な理解 57 | - Python、PyTorch、および`transformers`ライブラリに精通していること 58 | - 事前学習された言語モデルとラベル付きデータセットへのアクセス 59 | 60 | ## インストール 61 | 62 | コースをパッケージとして維持しているため、パッケージマネージャーを使用して依存関係を簡単にインストールできます。`uv`をお勧めしますが、`pip`や`pdm`などの代替手段も使用できます。 63 | 64 | ### `uv`を使用する場合 65 | 66 | `uv`がインストールされている場合、次のようにしてコースをインストールできます: 67 | 68 | ```bash 69 | uv venv --python 3.11.0 70 | uv sync 71 | ``` 72 | 73 | ### `pip`を使用する場合 74 | 75 | すべての例は**python 3.11**環境で実行されるため、次のように環境を作成し、依存関係をインストールします: 76 | 77 | ```bash 78 | # python -m venv .venv 79 | # source .venv/bin/activate 80 | pip install -r requirements.txt 81 | ``` 82 | 83 | ### Google Colab 84 | 85 | **Google Colabから**は、使用するハードウェアに基づいて柔軟に依存関係をインストールする必要があります。次のようにします: 86 | 87 | ```bash 88 | pip install transformers trl datasets huggingface_hub 89 | ``` 90 | 91 | -------------------------------------------------------------------------------- /ko/1_instruction_tuning/README.md: -------------------------------------------------------------------------------- 1 | # 지시 조정(Instruction Tuning) 2 | 3 | 이 모듈에서는 언어 모델의 지시 조정(instruction tuning) 방법을 설명합니다. 지시 조정이란, 사전 학습된 모델을 특정 태스크에 맞게 조정하기 위해 해당 태스크와 관련된 데이터셋으로 추가 학습시키는 과정을 의미합니다. 이를 통해 목표로 하는 작업에서 모델이 더 나은 성능을 발휘할 수 있습니다. 4 | 5 | 이 모듈에서는 다음 두 가지 주제를 다룰 예정입니다: 1) 대화 템플릿(Chat Templates) 2) 지도 학습 기반 미세 조정(Supervised Fine-Tuning) 6 | 7 | ## 1️⃣ 대화 템플릿 8 | 9 | 채팅 템플릿(Chat Templates)은 사용자와 AI 모델 간의 상호작용을 구조화하여 모델의 일관되고 적절한 맥락의 응답을 보장합니다. 템플릿에는 시스템 프롬프트와 역할 기반 메시지와 같은 구성 요소가 포함됩니다. 더 자세한 내용은 [대화 템플릿](./chat_templates.md) 섹션을 참고하세요. 10 | 11 | ## 2️⃣ 지도 학습 기반 미세 조정 12 | 13 | 지도 학습 기반 미세 조정(SFT)은 사전 학습된 언어 모델이 특정 작업에 적합하도록 조정하는 데 핵심적인 과정입니다. 이 과정에서는 레이블이 포함된 태스크별 데이터셋을 사용해 모델을 학습시킵니다. SFT의 주요 단계와 모범 사례를 포함한 자세한 가이드는 [지도 학습 기반 미세 조정](./supervised_fine_tuning.md) 섹션을 참고하세요. 14 | 15 | ## 실습 노트북 16 | | 파일명 | 설명 | 실습 내용 | 링크 | Colab | 17 | |-------|-------------|----------|------|-------| 18 | | Chat Templates | SmolLM2를 활용한 대화 템플릿 사용법과 데이터셋을 ChatML 형식으로 변환하는 과정 학습 | 🐢 `HuggingFaceTB/smoltalk` 데이터셋을 chatml 형식으로 변환해보기
🐕 `openai/gsm8k` 데이터셋을 chatml 형식으로 변환해보기 | [Notebook](./notebooks/chat_templates_example.ipynb) | Open In Colab | 19 | | Supervised Fine-Tuning | SFTTrainer를 이용해 SmolLM2를 파인튜닝하는 방법 학습 | 🐢 `HuggingFaceTB/smoltalk` 데이터셋 활용해보기
🐕 `bigcode/the-stack-smol` 데이터셋 활용해보기
🦁 실제 사용 사례에 맞는 데이터셋 선택해보기 | [Notebook](./notebooks/sft_finetuning_example.ipynb) | Open In Colab | 20 | ## 참고 21 | 22 | - [Transformers documentation on chat templates](https://huggingface.co/docs/transformers/main/en/chat_templating) 23 | - [Script for Supervised Fine-Tuning in TRL](https://github.com/huggingface/trl/blob/main/examples/scripts/sft.py) 24 | - [`SFTTrainer` in TRL](https://huggingface.co/docs/trl/main/en/sft_trainer) 25 | - [Direct Preference Optimization Paper](https://arxiv.org/abs/2305.18290) 26 | - [Supervised Fine-Tuning with TRL](https://huggingface.co/docs/trl/main/en/tutorials/supervised_finetuning) 27 | - [How to fine-tune Google Gemma with ChatML and Hugging Face TRL](https://www.philschmid.de/fine-tune-google-gemma) 28 | - [Fine-tuning LLM to Generate Persian Product Catalogs in JSON Format](https://huggingface.co/learn/cookbook/en/fine_tuning_llm_to_generate_persian_product_catalogs_in_json_format) -------------------------------------------------------------------------------- /ko/1_instruction_tuning/chat_templates.md: -------------------------------------------------------------------------------- 1 | # 대화 템플릿(Chat Templates) 2 | 3 | 대화 템플릿은 언어 모델과 사용자 간 상호작용을 구조화하는 데 필수적입니다. 이 템플릿은 대화에 일관된 형식을 제공하여, 모델이 각 메시지의 맥락과 역할을 이해하고 적절한 응답 패턴을 유지할 수 있도록 합니다. 4 | 5 | ## 기본 모델 vs 지시 모델 6 | 7 | 기본 모델은 다음 토큰을 예측하기 위해 대량의 원시 텍스트 데이터로 학습되는 반면, 지시 모델은 특정 지시를 따르고 대화를 나눌 수 있도록 미세 조정된 모델입니다. 예를 들어, `SmolLM2-135M`은 기본 모델이고, `SmolLM2-135M-Instruct`는 이를 지시 조정한 변형 모델입니다. 8 | 9 | 기본 모델이 지시 모델처럼 동작하도록 만들기 위해서는 모델이 이해할 수 있는 방식으로 프롬프트를 일관되게 만들어야 합니다. 이때 대화 템플릿이 유용합니다. ChatML은 이러한 템플릿 형식 중 하나로 대화를 구조화하고 명확한 역할 지시자(시스템, 사용자, 어시스턴트)를 제공합니다. 10 | 11 | 기본 모델은 서로 다른 대화 템플릿으로 미세 조정될 수 있으므로, 지시 모델을 사용할 때는 반드시 해당 모델에 적합한 대화 템플릿을 사용하는 것이 중요합니다. 12 | 13 | ## 대화 템플릿 이해하기 14 | 15 | 대화 템플릿의 핵심은 언어 모델과 소통할 때 대화가 어떤 형식으로 이루어져야 하는지 정의하는 것입니다. 템플릿에는 시스템 수준의 지침, 사용자 메시지, 어시스턴트의 응답이 포함되어 있으며, 모델이 이해할 수 있는 구조화된 형식을 제공합니다. 이러한 구조는 상호작용의 일관성을 유지하고, 모델이 다양한 유형의 입력에 적절히 응답하도록 돕습니다. 아래는 채팅 템플릿의 예시입니다: 16 | 17 | ```sh 18 | <|im_start|>user 19 | 안녕하세요!<|im_end|> 20 | <|im_start|>assistant 21 | 만나서 반갑습니다!<|im_end|> 22 | <|im_start|>user 23 | 질문을 해도 될까요?<|im_end|> 24 | <|im_start|>assistant 25 | ``` 26 | 27 | `transformers` 라이브러리는 모델의 토크나이저와 관련하여 대화 템플릿을 자동으로 처리해줍니다. 대화 템플릿이 transformers에서 어떻게 구성되는지 자세히 알아보려면 [여기](https://huggingface.co/docs/transformers/en/chat_templating#how-do-i-use-chat-templates)를 참고하세요. 우리가 메시지를 올바른 형식으로 구조화하기만 하면 나머지는 토크나이저가 처리합니다. 아래는 기본적인 대화 예시입니다: 28 | ```python 29 | messages = [ 30 | {"role": "system", "content": "You are a helpful assistant focused on technical topics."}, 31 | {"role": "user", "content": "Can you explain what a chat template is?"}, 32 | {"role": "assistant", "content": "A chat template structures conversations between users and AI models..."} 33 | ] 34 | ``` 35 | 36 | 위 예시를 자세히 보면서 대화 템플릿 형식에 어떻게 매핑되는지 살펴봅시다. 37 | 38 | ## 시스템 메시지 39 | 40 | 시스템 메시지는 모델의 기본 동작 방식을 설정합니다. 이는 이후 모든 상호작용에 영향을 미치는 지속적인 지침이 됩니다. 41 | 42 | ```python 43 | system_message = { 44 | "role": "system", 45 | "content": "You are a professional customer service agent. Always be polite, clear, and helpful." 46 | } 47 | ``` 48 | 49 | ## 대화 50 | 51 | 대화 템플릿은 대화 기록을 통해 맥락을 유지하며, 사용자와 어시스턴트 간의 이전 대화를 저장합니다. 이를 통해 더욱 일관된 멀티 턴 대화가 가능해집니다: 52 | 53 | ```python 54 | conversation = [ 55 | {"role": "user", "content": "I need help with my order"}, 56 | {"role": "assistant", "content": "I'd be happy to help. Could you provide your order number?"}, 57 | {"role": "user", "content": "It's ORDER-123"}, 58 | ] 59 | ``` 60 | 61 | ## Transformers 기반 구현 62 | 63 | transformers 라이브러리는 대화 템플릿을 위한 내장 기능을 지원합니다.사용 방법은 다음과 같습니다: 64 | 65 | ```python 66 | from transformers import AutoTokenizer 67 | 68 | tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct") 69 | 70 | messages = [ 71 | {"role": "system", "content": "You are a helpful coding assistant."}, 72 | {"role": "user", "content": "Write a Python function to sort a list"}, 73 | ] 74 | 75 | # 대화 템플릿 적용 76 | formatted_chat = tokenizer.apply_chat_template( 77 | messages, 78 | tokenize=False, 79 | add_generation_prompt=True 80 | ) 81 | ``` 82 | 83 | ## 사용자 정의 형식 84 | 85 | 메시지 유형별로 원하는 형식을 설정할 수 있습니다. 예를 들어, 역할에 따라 특수 토큰을 추가하거나 형식을 지정할 수 있습니다: 86 | 87 | ```python 88 | template = """ 89 | <|system|>{system_message} 90 | <|user|>{user_message} 91 | <|assistant|>{assistant_message} 92 | """.lstrip() 93 | ``` 94 | 95 | ## 멀티 턴 지원 96 | 97 | 템플릿은 문맥을 유지하면서 복잡한 멀티 턴 대화도 처리할 수 있습니다: 98 | 99 | ```python 100 | messages = [ 101 | {"role": "system", "content": "You are a math tutor."}, 102 | {"role": "user", "content": "What is calculus?"}, 103 | {"role": "assistant", "content": "Calculus is a branch of mathematics..."}, 104 | {"role": "user", "content": "Can you give me an example?"}, 105 | ] 106 | ``` 107 | 108 | ⏭️ [다음: Supervised Fine-Tuning](./supervised_fine_tuning.md) 109 | 110 | ## 참고 111 | 112 | - [Hugging Face Chat Templating Guide](https://huggingface.co/docs/transformers/main/en/chat_templating) 113 | - [Transformers Documentation](https://huggingface.co/docs/transformers) 114 | - [Chat Templates Examples Repository](https://github.com/chujiezheng/chat_templates) 115 | -------------------------------------------------------------------------------- /ko/1_instruction_tuning/notebooks/.env.example: -------------------------------------------------------------------------------- 1 | # Duplicate this file to .env and fill in secret values 2 | HF_TOKEN= 3 | -------------------------------------------------------------------------------- /ko/1_instruction_tuning/supervised_fine_tuning.md: -------------------------------------------------------------------------------- 1 | # 지도 학습 기반 미세 조정(Supervised Fine-Tuning) 2 | 3 | 지도 학습 기반 미세 조정(SFT)은 사전 학습된 언어 모델을 특정 작업이나 도메인에 맞게 조정하는 데 핵심적인 과정입니다. 사전 학습된 모델의 능력은 일반적으로 뛰어나지만, 특정 사용 사례에서 우수한 성능을 발휘하려면 맞춤화가 필요할 때가 많습니다. SFT는 사람이 검증한 예제를 포함하여 신중하게 선별된 데이터셋으로 모델을 추가 학습시켜 이러한 격차를 해소합니다. 4 | 5 | ## SFT 이해하기 6 | 7 | SFT의 핵심은 레이블이 있는 토큰을 통해 사전 학습된 모델이 특정 작업을 수행하도록 학습시키는 것입니다. 이 과정에서 원하는 입력-출력 동작 예제를 모델에 많이 보여줌으로써, 해당 사용 사례에 특화된 패턴을 학습하도록 합니다. 8 | 9 | SFT가 효과적인 이유는 사전 학습 과정에서 습득한 기초 지식을 활용하면서도 사용자의 특정 요구에 맞게 모델의 동작을 조정할 수 있기 때문입니다. 10 | 11 | ## SFT를 언제 사용해야 하나요? 12 | 13 | SFT 사용 여부는 주로 모델이 현재 가지고 있는 능력과 특정 요구 사항 간의 차이에 따라 결정됩니다. SFT는 특히 모델 출력에 대한 정교한 제어가 필요하거나 전문적인 도메인에서 작업할 때 매우 유용합니다. 14 | 15 | 예를 들어, 고객 서비스 애플리케이션을 개발하는 경우 모델이 회사 지침을 일관되게 따르고 기술적인 질문을 표준화된 방식으로 처리하도록 만들고 싶을 것입니다. 마찬가지로 의료나 법률 애플리케이션에서는 정확성과 도메인 특화 용어를 사용하는 것이 중요합니다. SFT는 이러한 경우에서 모델의 응답이 전문적인 표준을 따르고 모델 응답을 도메인 전문 지식에 맞게 조정하는 데 도움을 줄 수 있습니다. 16 | 17 | ## 미세 조정 과정 18 | 19 | 지도 학습 기반 미세 조정은 특정 태스크에 맞춘 데이터셋으로 모델 가중치를 학습시키는 과정을 포함합니다. 20 | 21 | 먼저, 목표 태스크를 대표할 수 있는 데이터셋을 준비하거나 선택해야 합니다. 이 데이터셋은 모델이 마주하게 될 다양한 시나리오를 포괄할 수 있는 예제를 포함하고 있어야 합니다. 데이터 품질이 매우 중요하며 각 예제는 모델이 생성하길 원하는 출력 유형을 명확히 보여줘야 합니다. 이후 Hugging Face의 `transformers` 및 `trl`과 같은 프레임워크를 사용하여 데이터셋을 기반으로 모델을 학습시키는 실제 미세 조정 단계가 이어집니다. 22 | 23 | 이 과정 전반에서 지속적인 평가가 필수적입니다. 모델이 원하는 동작을 학습하면서도 일반적인 능력을 잃지 않도록 검증 데이터셋을 사용해 성능을 모니터링해야 합니다. 모델을 평가하는 방법에 대해서는 [모듈 4](../4_evaluation)에서 다룰 예정입니다. 24 | 25 | ## 선호도 조정에서 SFT의 역할 26 | 27 | SFT는 언어 모델을 인간의 선호도에 맞추는 데 기본적인 역할을 합니다. 인간 피드백을 통한 강화 학습(Reinforcement Learning from Human Feedback, RLHF) 및 직접 선호도 최적화(Direct Preference Optimization, DPO)와 같은 기술은 SFT를 사용하여 기본적인 수준으로 태스크를 이해하게 한 후 모델의 응답을 원하는 결과에 맞게 조정합니다. 사전 학습된 모델은 일반적인 언어 능력을 가지고 있음에도 불구하고 항상 사람의 선호도와 일치하는 결과를 생성하지 못할 수 있습니다. SFT는 도메인별 데이터와 지침을 도입하여 이러한 격차를 해소함으로써 모델이 인간의 기대에 부합하는 응답을 생성할 수 있도록 합니다. 28 | 29 | ## TRL을 활용한 SFT 30 | 31 | 지도 학습 기반 미세 조정에서 중요한 소프트웨어 패키지 중 하나는 Transformer 강화 학습(Transformer Reinforcement Learning, TRL)입니다. TRL은 강화 학습(Reinforcement Learning, RL)을 사용하여 트랜스포머 언어 모델을 학습시키기 위한 도구입니다. 32 | 33 | Hugging Face Transformers 라이브러리를 기반으로 구축된 TRL은 사용자가 사전 학습된 언어 모델을 직접 로드할 수 있게 하며, 대부분의 디코더 및 인코더-디코더 아키텍처를 지원합니다. 이 라이브러리는 언어 모델링에 사용되는 주요 RL 프로세스를 지원하고 지도 학습 기반 미세 조정(SFT), 보상 모델링(Reward Modeling, RM), 근접 정책 최적화(Proximal Policy Optimization, PPO), 직접 선호 최적화(Direct Preference Optimization, DPO)와 같은 과정을 용이하게 만듭니다. 34 | 35 | 이 레포지토리의 여러 모듈에서 TRL을 활용할 예정입니다. 36 | 37 | # 다음 단계 38 | 39 | 다음 튜토리얼을 통해 TRL을 활용한 SFT 실습 경험을 쌓아 보세요: 40 | 41 | ⏭️ [Chat Templates 튜토리얼](./notebooks/chat_templates_example.ipynb) 42 | 43 | ⏭️ [Supervised Fine-Tuning 튜토리얼](./notebooks/supervised_fine_tuning_tutorial.ipynb) -------------------------------------------------------------------------------- /ko/3_parameter_efficient_finetuning/README.md: -------------------------------------------------------------------------------- 1 | # Parameter-Efficient Fine-Tuning, PEFT 2 | 3 | 언어 모델이 커지면서 전통적인 미세 조정 방식을 적용하는 것이 점점 어려워지고 있습니다. 1.7B 모델조차도 전체 미세 조정을 수행하려면 상당한 GPU 메모리가 필요하며, 모델 사본을 별도로 저장하기 위한 비용이 많이 들고, 모델의 원래 능력을 상실하는 위험이 존재합니다. Parmeter-Efficient Fine-Tuning(PEFT) 방법은 대부분의 모델 파라미터가 고정된 상태에서 모델 파라미터의 일부만 수정하여 전체 미세 조정 과정에서 발생하는 문제를 해결헙니다. 4 | 5 | 학습 과정에서 모델의 모든 파라미터를 업데이트하는 전통적인 미세 조정 방법을 대형 언어 모델에 적용하는 것은 현실적으로 어렵습니다. PEFT는 원래 모델 크기의 1% 미만에 해당하는 파라미터만 학습시켜 모델을 조정하는 방법입니다. 학습 가능한 파라미터를 크게 줄이는 것은 다음과 같은 이점을 제공합니다: 6 | 7 | - 제한된 GPU 메모리를 가진 하드웨어에서도 미세 조정 가능 8 | - 효율적인 태스크별 적응 모델 저장 9 | - 데이터가 적은 상황에서도 뛰어난 일반화 성능 제공 10 | - 더 빠른 학습 및 반복 가능 11 | 12 | ## 사용 가능한 방법 13 | 14 | 이 모듈에서는 많이 사용되는 두 가지 PEFT 방법을 다룹니다: 15 | 16 | ### 1️⃣ LoRA (Low-Rank Adaptation) 17 | 18 | LoRA는 효율적인 모델 적응을 위한 멋진 솔루션을 제공하면서 가장 많이 사용되는 PEFT 방법으로 자리 잡았습니다. LoRA는 전체 모델을 수정하는 대신 **학습 가능한 파라미터를 모델의 어텐션 레이어에 주입**합니다. 이 접근법은 전체 미세 조정과 비슷한 성능을 유지하면서 학습 가능한 파라미터를 약 90%까지 줄입니다. [LoRA (Low-Rank Adaptation)](./lora_adapters.md) 섹션에서 LoRA에 대해 자세히 알아보겠습니다. 19 | 20 | ### 2️⃣ 프롬프트 튜닝 21 | 22 | 프롬프트 튜닝은 모델 가중치를 수정하는 대신 **입력에 학습 가능한 토큰을 추가**하여 **더 경량화된** 접근법을 제공합니다. 프롬프트 튜닝은 LoRA만큼 유명하지는 않지만, 모델을 새로운 태스크나 도메인에 빠르게 적용할 때 유용하게 쓰일 수 있는 기술입니다. [프롬프트 튜닝](./prompt_tuning.md) 섹션에서 프롬프트 튜닝에 대해 탐구해볼 예정입니다. 23 | 24 | ## 실습 노트북 25 | 26 | | 파일명 | 설명 | 실습 내용 | 링크 | Colab | 27 | |-------|-------------|----------|------|-------| 28 | | LoRA Fine-tuning | LoRA 어댑터를 사용해 모델을 미세 조정하는 방법 학습 | 🐢 LoRA를 사용해 모델 학습해보기
🐕 다양한 랭크 값으로 실험해보기
🦁 전체 미세 조정과 성능 비교해보기 | [Notebook](./notebooks/finetune_sft_peft.ipynb) | Open In Colab | 29 | | Load LoRA Adapters | LoRA 어댑터를 불러오고 학습시키는 방법 배우기 | 🐢 사전 학습된 어댑터 불러오기
🐕 기본 모델과 어댑터 합치기
🦁 여러 어댑터 간 전환해보기 | [Notebook](./notebooks/load_lora_adapter_example.ipynb) | Open In Colab | 30 | 31 | 32 | ## 참고 33 | - [Hugging Face PEFT 문서](https://huggingface.co/docs/peft) 34 | - [LoRA 논문](https://arxiv.org/abs/2106.09685) 35 | - [QLoRA 논문](https://arxiv.org/abs/2305.14314) 36 | - [프롬프트 튜닝 논문](https://arxiv.org/abs/2104.08691) 37 | - [Hugging Face PEFT 가이드](https://huggingface.co/blog/peft) 38 | - [How to Fine-Tune LLMs in 2024 with Hugging Face](https://www.philschmid.de/fine-tune-llms-in-2024-with-trl) 39 | - [TRL](https://huggingface.co/docs/trl/index) -------------------------------------------------------------------------------- /ko/3_parameter_efficient_finetuning/images/lora_adapter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/ko/3_parameter_efficient_finetuning/images/lora_adapter.png -------------------------------------------------------------------------------- /ko/3_parameter_efficient_finetuning/prompt_tuning.md: -------------------------------------------------------------------------------- 1 | # 프롬프트 튜닝 2 | 3 | 프롬프트 튜닝은 모델 가중치 대신 입력 표현을 변경하는 파라미터 효율적인 접근법입니다. 모델의 모든 파라미터를 업데이트하는 전통적인 미세 조정과 다르게, 프롬프트 튜닝은 기본 모델의 파라미터가 고정된 상태를 유지하면서 소수의 학습 가능한 토큰을 추가하고 최적화합니다. 4 | 5 | ## 프롬프트 튜닝 이해하기 6 | 7 | 프롬프트 튜닝은 모델 미세 조정의 대안으로, 학습 가능한 연속 벡터(소프트 프롬프트)를 입력 텍스트에 추가하는 파라미터 효율적인 방식입니다. 소프트 프롬프트는 이산적인 텍스트 프롬프트와 다르게 모델 파라미터가 고정된 상태에서 역전파를 통해 학습됩니다. 이 방식은 ["The Power of Scale for Parameter-Efficient Prompt Tuning"](https://arxiv.org/abs/2104.08691) (Lester et al., 2021)에서 처음 소개되었으며, 이 논문은 모델 크기가 커질수록 미세 조정과 비교했을 때 프롬프트 튜닝이 경쟁력을 가진다는 것을 보였습니다. 논문에 따르면, 약 100억 개의 파라미터를 가진 모델에서 프롬프트 튜닝의 성능은 태스크당 수백 개의 매개변수 수정만으로 모델 미세 조정의 성능과 일치하는 것으로 나타났습니다. 8 | 9 | 모델의 임베딩 공간에 존재하는 연속적인 벡터인 소프트 프롬프트는 학습 과정에서 최적화됩니다. 자연어 토큰을 사용하는 전통적인 이산 프롬프트와 달리 소프트 프롬프트는 고유한 의미를 가지고 있지는 않지만 경사 하강법을 통해 파라미터가 고정된 모델에서 원하는 동작을 이끌어내는 방법을 학습합니다. 이 기법은 모델 전체를 복사하지 않고 적은 수(일반적으로 몇백 개의 파라미터)에 해당하는 프롬프트 벡터만을 저장하기 때문에 멀티 태스크 시나리오에 더욱 효과적입니다. 이 접근 방식은 최소한의 메모리 사용량을 유지할 뿐만 아니라, 프롬프트 벡터만 교체하여 모델을 다시 로드하지 않고도 신속하게 작업을 전환할 수 있게 합니다. 10 | 11 | ## 학습 과정 12 | 13 | 소프트 프롬프트는 일반적으로 8~32개의 토큰으로 구성되며 무작위 또는 기존 텍스트로 초기화할 수 있습니다. 초기화 방법은 학습 과정에서 중요한 역할을 하며 텍스트 기반 초기화가 무작위 초기화보다 좋은 성능을 보이는 경우가 많습니다. 14 | 15 | 학습이 진행되는 동안 기본 모델의 파라미터는 고정되어 있고 프롬프트 파라미터만 업데이트 됩니다. 프롬프트 파라미터에 초점을 맞춘 이 접근 방식은 일반적인 학습 목표를 따르지만 학습률과 프롬프트 토큰의 경사 동작에 세심한 주의가 필요합니다. 16 | 17 | ## PEFT 라이브러리를 활용한 프롬프트 튜닝 구현 18 | 19 | PEFT 라이브러리를 이용해 프롬프트 튜닝을 직관적으로 구현할 수 있습니다. 기본적인 예제는 다음과 같습니다: 20 | 21 | ```python 22 | from peft import PromptTuningConfig, TaskType, get_peft_model 23 | from transformers import AutoModelForCausalLM, AutoTokenizer 24 | 25 | # 기본 모델 불러오기 26 | model = AutoModelForCausalLM.from_pretrained("your-base-model") 27 | tokenizer = AutoTokenizer.from_pretrained("your-base-model") 28 | 29 | # 프롬프트 튜닝 configuration 설정 30 | peft_config = PromptTuningConfig( 31 | task_type=TaskType.CAUSAL_LM, 32 | num_virtual_tokens=8, # 학습 가능한 토큰 수 33 | prompt_tuning_init="TEXT", # 텍스트 기반 초기화 34 | prompt_tuning_init_text="Classify if this text is positive or negative:", 35 | tokenizer_name_or_path="your-base-model", 36 | ) 37 | 38 | # 프롬프트 튜닝 가능한 모델 생성 39 | model = get_peft_model(model, peft_config) 40 | ``` 41 | 42 | ## 프롬프트 튜닝과 다른 PEFT 방법 비교 43 | 44 | 다른 PEFT 접근 방식과 비교했을 때 프롬프트 튜닝은 효율성이 뛰어납니다. LoRA는 파라미터 수와 메모리 사용량이 적지만 태스크 전환을 위해 어댑터를 불러와야 하는 반면 프롬프트 튜닝은 자원을 더 적게 사용하면서 즉각적인 태스크 전환이 가능합니다. 반면에 전체 미세 조정은 상당한 양의 자원을 필요로 하고 서로 다른 태스크를 수행하기 위해 태스크에 맞는 각각의 모델을 필요로 합니다. 45 | 46 | | 방법 | 파라미터 수 | 메모리 사용량 | 태스크 전환 | 47 | |--------|------------|---------|----------------| 48 | | 프롬프트 튜닝 | 매우 적음 | 메모리 사용량 최소화 | 쉬움 | 49 | | LoRA | 적음 | 적음 | 모델을 다시 불러와야 함 | 50 | | 전체 미세 조정 | 많음 | 많음 | 새로운 모델 복사 필요 | 51 | 52 | 프롬프트 튜닝을 구현할 때는 적은 수(8~16개)의 가상 토큰으로 시작한 후 태스크의 복잡성에 따라 토큰 수를 점차 늘려가세요. 태스크와 관련된 텍스트로 초기화를 수행하는 것이 무작위 초기화보다 일반적으로 더 나은 결과를 가져옵니다. 초기화 전략은 목표 태스크의 복잡성을 반영해야 합니다. 53 | 54 | 학습 과정은 전체 미세 조정과 약간의 차이가 있습니다. 보통 높은 학습률이 효과적이지만 프롬프트 토큰 경사를 신중하게 모니터링해야 합니다. 다양한 예제를 활용한 주기적인 검증은 서로 다른 시나리오에서 강력한 성능을 보장하는 데 도움이 됩니다. 55 | 56 | ## 응용 57 | 58 | 프롬프트 튜닝은 다음과 같은 시나리오에서 특히 뛰어납니다: 59 | 60 | 1. 멀티 태스크 배포 61 | 2. 자원이 제한적인 환경 62 | 3. 신속한 태스크 적응 63 | 4. 프라이버시에 민감한 애플리케이션 64 | 65 | 그러나 모델 크기가 작아질수록 전체 미세 조정과 비교했을 때 프롬프트 튜닝의 경쟁력이 떨어집니다. 예를 들어, SmolLM2 크기의 모델은 프롬프트 튜닝보다 전체 미세 조정를 수행하는 것이 좀 더 의미있습니다. 66 | 67 | ## 다음 단계 68 | 69 | ⏭️ [LoRA 어댑터 튜토리얼](./notebooks/finetune_sft_peft.ipynb)에서 LoRA 어댑터를 활용해 모델을 미세 조정하는 법을 배워봅시다. 70 | 71 | ## 참고 72 | - [Hugging Face PEFT 문서](https://huggingface.co/docs/peft) 73 | - [프롬프트 튜닝 논문](https://arxiv.org/abs/2104.08691) 74 | - [Hugging Face Cookbook](https://huggingface.co/learn/cookbook/prompt_tuning_peft) 75 | -------------------------------------------------------------------------------- /ko/README.md: -------------------------------------------------------------------------------- 1 | ![smolcourse image](../banner.png) 2 | 3 | # 소형 언어 모델 과정 4 | 5 | 이 과정에서는 특정 사용 사례에 맞게 언어 모델을 정렬하는 법을 다룹니다. 모든 자료는 대부분의 로컬 컴퓨터에서 실행되므로 간편하게 언어 모델 정렬을 시작해볼 수 있습니다. 이 과정을 위해 필요한 최소한의 GPU 요구 사항이나 유료 서비스가 없습니다. [SmolLM2](https://github.com/huggingface/smollm/tree/main) 시리즈 모델을 기반으로 하는 과정이지만, 여기서 배운 기술을 더 큰 모델이나 다른 작은 언어 모델로 옮길 수 있습니다. 6 | 7 | 8 | 9 | 10 | 11 |
12 |

지금 바로 참여하세요!

13 |

이 과정은 열려 있으며 다른 사용자와의 상호 검토를 진행할 수 있습니다. 이 과정에 참여하려면 pull request(PR)를 열고 검토 받을 수 있도록 결과물을 제출하세요. 다음 단계를 따르면 됩니다:

14 |
    15 |
  1. 여기에서 레포지토리를 fork하세요.
  2. 16 |
  3. 자료를 읽고, 바꿔 보고, 실습해보고, 나만의 예제를 추가해보세요.
  4. 17 |
  5. december-2024 브랜치에 PR을 보내세요.
  6. 18 |
  7. 검토가 끝나면 december-2024 브랜치에 병합됩니다.
  8. 19 |
20 |

이 과정은 학습에 도움이 될 뿐만 아니라 지속적으로 발전하는 커뮤니티 기반 코스를 형성하는 데에도 기여할 것입니다.

21 |
22 | 23 | [discussion thread](https://github.com/huggingface/smol-course/discussions/2#discussion-7602932)에서 과정에 대해 토론할 수도 있습니다. 24 | 25 | ## 과정 개요 26 | 27 | 이 과정은 소형 언어 모델의 초기 학습부터 결과물 배포까지 실습할 수 있는 실용적인 내용을 제공합니다. 28 | 29 | | 모듈 | 설명 | 상태 | 공개일 | 30 | |--------|-------------|---------|--------------| 31 | | [Instruction Tuning](./1_instruction_tuning) | 지도 학습 기반 미세 조정, 대화 템플릿 작성, 기본적인 지시를 따르게 하는 방법 학습 | ✅ 학습 가능 | 2024. 12. 3 | 32 | | [Preference Alignment](./2_preference_alignment) | 모델을 인간 선호도에 맞게 정렬하기 위한 DPO와 ORPO 기법 학습 | ✅ 학습 가능 | 2024. 12. 6 | 33 | | [Parameter-efficient Fine-tuning](./3_parameter_efficient_finetuning) | LoRA, 프롬프트 튜닝을 포함한 효율적인 적응 방법 학습 | ✅ 학습 가능 | 2024. 12. 9 | 34 | | [Evaluation](./4_evaluation) | 자동 벤치마크 사용법 및 사용자 정의 도메인 평가 수행 방법 학습 | ✅ 학습 가능 | 2024. 12. 13 | 35 | | [Vision-language Models](./5_vision_language_models) | 비전-언어 태스크를 위한 멀티모달 모델 적용 방법 학습 | [🚧 준비중](https://github.com/huggingface/smol-course/issues/49) | 2024. 12. 16 | 36 | | [Synthetic Datasets](./6_synthetic_datasets) | 모델 학습을 위한 합성 데이터셋 생성 및 검증 | [🚧 준비중](https://github.com/huggingface/smol-course/issues/83) | 2024. 12. 20 | 37 | | [Inference](./7_inference) | 모델의 효율적인 추론 방법 학습 | 📝 작성 예정 | 2024. 12. 23 | 38 | 39 | ## 왜 소형 언어 모델을 사용하나요? 40 | 41 | 대형 언어 모델은 뛰어난 능력을 보여주지만, 상당한 연산 자원을 필요로 하며 특정 기능에 초점을 맞춘 애플리케이션에 대해서는 대형 언어 모델이 과한 경우도 있습니다. 소형 언어 모델은 도메인 특화 애플리케이션에 있어서 몇 가지 이점을 제공합니다: 42 | 43 | - **효율성**: 대형 언어 모델보다 훨씬 적은 연산 자원으로 학습 및 배포 가능 44 | - **맞춤화**: 특정 도메인에 대한 미세 조정 및 적응 용이 45 | - **제어**: 모델 동작 과정을 잘 이해할 수 있고 모델의 동작을 쉽게 제어 가능 46 | - **비용**: 학습과 추론 과정에서 필요한 비용 감소 47 | - **프라이버시**: 데이터를 외부 API로 보내지 않고 로컬에서 실행 가능 48 | - **친환경**: 탄소 발자국을 줄이는 효율적인 자원 사용 49 | - **쉬운 학술 연구 및 개발**: 최신 LLM을 활용해 물리적 제약 없이 학술 연구를 쉽게 시작할 수 있도록 지원 50 | 51 | ## 사전 준비 사항 52 | 53 | 시작하기 전에 아래 사항이 준비되어 있는지 확인하세요: 54 | - 머신러닝과 자연어처리에 대한 기본적인 이해가 필요합니다. 55 | - Python, PyTorch 및 `transformers` 라이브러리에 익숙해야 합니다. 56 | - 사전 학습된 언어 모델과 레이블이 있는 액세스할 수 있어야 합니다. 57 | 58 | ## 설치 59 | 60 | 이 과정은 패키지 형태로 관리되기 때문에 패키지 매니저를 이용해 의존성 설치를 쉽게 진행할 수 있습니다. 이를 위해 [uv](https://github.com/astral-sh/uv) 사용을 권장하지만 `pip`나 `pdm`을 사용할 수도 있습니다. 61 | 62 | ### `uv` 사용 63 | 64 | `uv`를 설치한 후, 아래 명령어로 소형 언어 모델 과정을 설치할 수 있습니다: 65 | 66 | ```bash 67 | uv venv --python 3.11.0 68 | uv sync 69 | ``` 70 | 71 | ### `pip` 사용 72 | 73 | 모든 예제는 동일한 **python 3.11** 환경에서 실행되기 때문에 아래처럼 환경을 생성하고 의존성을 설치해야 합니다: 74 | 75 | ```bash 76 | # python -m venv .venv 77 | # source .venv/bin/activate 78 | pip install -r requirements.txt 79 | ``` 80 | 81 | ### Google Colab 82 | 83 | **Google Colab**에서는 사용하는 하드웨어에 따라 유연하게 의존성을 설치해야 합니다. 아래와 같이 진행하세요: 84 | 85 | ```bash 86 | pip install transformers trl datasets huggingface_hub 87 | ``` 88 | 89 | ## 참여 90 | 91 | 많은 사람이 고가의 장비 없이 LLM을 미세 조정하는 법을 배울 수 있도록 이 자료를 공유해 봅시다! 92 | 93 | [![Star History Chart](https://api.star-history.com/svg?repos=huggingface/smol-course&type=Date)](https://star-history.com/#huggingface/smol-course&Date) 94 | -------------------------------------------------------------------------------- /pt-br/1_instruction_tuning/README.md: -------------------------------------------------------------------------------- 1 | # Instruction Tuning (Ajuste de Instrução) 2 | 3 | Este módulo o guiará através de modelos de linguagem de ajuste de instrução. O ajuste de instrução envolve a adaptação de modelos pré-treinados a tarefas específicas, treinando-os ainda mais em conjuntos de dados específicos de tarefas. Esse processo ajuda os modelos a melhorar seu desempenho em certas tarefas específicas. 4 | 5 | Neste módulo, exploraremos dois tópicos: 1) Modelos de bate-papo e 2) Ajuste fino supervisionado. 6 | 7 | ## 1️⃣ Modelos de Bate-Papo 8 | 9 | Modelos de bate-papo estruturam interações entre usuários e modelos de IA, garantindo respostas consistentes e contextualmente apropriadas. Eles incluem componentes como avisos de sistema e mensagens baseadas em funções. Para informações mais detalhadas, Consulte a seção [Chat Templates (Modelos de Bate-Papo)](./chat_templates.md). 10 | 11 | ## 2️⃣ Ajuste Fino Supervisionado 12 | 13 | Ajuste fino supervisionado (em inglês, SFT - Supervised Fine-Tuning) é um processo crítico para adaptar modelos de linguagem pré-treinados a tarefas específicas. O ajuste envolve treinar o modelo em um conjunto de dados de uma tarefa específica com exemplos rotulados. Para um guia detalhado sobre SFT, incluindo etapas importantes e práticas recomendadas, veja a página [Supervised Fine-Tuning (Ajuste Fino Supervisionado)](./supervised_fine_tuning.md). 14 | 15 | ## Cadernos de Exercícios 16 | 17 | | Título | Descrição | Exercício | Link | Colab | 18 | |-------|-------------|----------|------|-------| 19 | | Modelos de Bate-Papo | Aprenda a usar modelos de bate-papo com SmolLM2 and a processar conjunto de dados para o formato chatml | 🐢 Converta o conjunto de dados `HuggingFaceTB/smoltalk` para o formato chatml
🐕 Converta o conjunto de dados `openai/gsm8k` para o formato chatml | [Exercício](./notebooks/chat_templates_example.ipynb) | Open In Colab | 20 | | Ajuste Fino Supervisionado | Aprenda como fazer o ajuste fino no modelo SmolLM2 usando o SFTTrainer | 🐢 Use o conjunto de dados `HuggingFaceTB/smoltalk`
🐕 Experimente o conjunto de dados `bigcode/the-stack-smol`
🦁 Selecione um conjunto de dados para um caso de uso do mundo real | [Exercício](./notebooks/sft_finetuning_example.ipynb) | Open In Colab | 21 | 22 | ## Referências 23 | 24 | - [Documentação dos transformadores em modelos de bate-papo](https://huggingface.co/docs/transformers/main/en/chat_templating) 25 | - [Script para ajuste fino supervisionado em TRL](https://github.com/huggingface/trl/blob/main/examples/scripts/sft.py) 26 | - [`SFTTrainer` em TRL](https://huggingface.co/docs/trl/main/en/sft_trainer) 27 | - [Artigo de otimização de preferência direta](https://arxiv.org/abs/2305.18290) 28 | - [Ajuste fino supervisionado com TRL](https://huggingface.co/docs/trl/main/en/tutorials/supervised_finetuning) 29 | - [Como ajustar o Google Gemma com ChatML e Hugging Face TRL](https://www.philschmid.de/fine-tune-google-gemma) 30 | - [Fazendo o ajuste fino em uma LLM para gerar catálogos de produtos persas em formato JSON](https://huggingface.co/learn/cookbook/en/fine_tuning_llm_to_generate_persian_product_catalogs_in_json_format) 31 | -------------------------------------------------------------------------------- /pt-br/1_instruction_tuning/notebooks/.env.example: -------------------------------------------------------------------------------- 1 | # Duplicate this file to .env and fill in secret values 2 | HF_TOKEN= 3 | -------------------------------------------------------------------------------- /pt-br/3_parameter_efficient_finetuning/README.md: -------------------------------------------------------------------------------- 1 | # Parameter-Efficient Fine-Tuning (PEFT) (Ajuste Fino com Eficiência de Parâmetro) 2 | 3 | À medida que os modelos de linguagem aumentam, o ajuste fino tradicional torna-se cada vez mais desafiador. O ajuste fino completo de um modelo com 1,7 bilhão de parâmetros requer uma quantidade considerável de memória da GPU, torna caro o armazenamento de cópias separadas do modelo e apresenta o risco de um esquecimento catastrófico das capacidades originais do modelo. Os métodos de ajuste fino com eficiência de parâmetros (PEFT) abordam esses desafios modificando apenas um pequeno subconjunto de parâmetros do modelo e mantendo a maior parte do modelo congelada. 4 | 5 | O ajuste fino tradicional atualiza todos os parâmetros do modelo durante o treinamento, o que se torna impraticável para modelos grandes. Os métodos PEFT introduzem abordagens para adaptar modelos usando menos parâmetros treináveis, geralmente menos de 1% do tamanho do modelo original. Essa redução drástica nos parâmetros treináveis permite: 6 | 7 | - Ajuste fino no hardware do consumidor com memória de GPU limitada 8 | - Armazenamento eficiente de várias adaptações de tarefas específicas 9 | - Melhor generalização em cenários com poucos dados 10 | - Ciclos de treinamento e iteração mais rápidos 11 | 12 | ## Métodos Disponíveis 13 | 14 | Neste módulo, abordaremos dois métodos populares de PEFT: 15 | 16 | ### 1️⃣ LoRA (Low-Rank Adaptation - Adaptação de Baixa Classificação) 17 | 18 | O LoRA surgiu como o método PEFT mais amplamente adotado, oferecendo uma solução elegante para a adaptação eficiente do modelo. Em vez de modificar o modelo inteiro, o **LoRA injeta matrizes treináveis nas camadas de atenção do modelo.** Essa abordagem normalmente reduz os parâmetros treináveis em cerca de 90%, mantendo um desempenho comparável ao ajuste fino completo. Exploraremos o LoRA na seção [LoRA (Adaptação de Baixa Classificação)](./lora_adapters.md). 19 | 20 | ### 2️⃣ Ajuste de Prompts 21 | 22 | O ajuste de prompts oferece uma abordagem **ainda mais leve** ao **adicionar tokens treináveis à entrada** em vez de modificar os pesos do modelo. O ajuste de prompt é menos popular que o LoRA, mas pode ser uma técnica útil para adaptar rapidamente um modelo a novas tarefas ou domínios. Exploraremos o ajuste de prompt na seção [Ajuste de Prompt](./prompt_tuning.md). 23 | 24 | ## Cadernos de Exercícios 25 | 26 | | Título | Descrição | Exercício | Link | Colab | 27 | |-------|-------------|----------|------|-------| 28 | | Ajuste fino do LoRA | Aprenda a fazer o ajuste fino de modelos usando adaptadores do LoRA | 🐢 Treine um modelo usando o LoRA< br>🐕 Experimente com diferentes valores de classificação
🦁 Compare o desempenho com o ajuste fino completo | [Exercício](./notebooks/finetune_sft_peft.ipynb) | Open In Colab | | 29 | | Carregue adaptadores LoRA | Aprenda como carregar e usar adaptadores LoRA treinados | 🐢 Carregar adaptadores pré-treinados< br>🐕 Mesclar adaptadores com o modelo de base
🦁 Alternar entre vários adaptadores | [Exercício](./notebooks/load_lora_adapter.ipynb) | Open In Colab | 30 | 31 | 32 | ## Referências 33 | 34 | - [Documentação PEFT](https://huggingface.co/docs/peft) 35 | - [Artigo sobre LoRA](https://arxiv.org/abs/2106.09685) 36 | - [Artigo sobre QLoRA](https://arxiv.org/abs/2305.14314) 37 | - [Artigo sobre Ajuste de Prompts](https://arxiv.org/abs/2104.08691) 38 | - [Guia PEFT do Hugging Face](https://huggingface.co/blog/peft) 39 | - [Como ajustar os LLMs em 2024 com o Hugging Face](https://www.philschmid.de/fine-tune-llms-in-2024-with-trl) 40 | - [TRL](https://huggingface.co/docs/trl/index) -------------------------------------------------------------------------------- /pt-br/3_parameter_efficient_finetuning/images/lora_adapter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/pt-br/3_parameter_efficient_finetuning/images/lora_adapter.png -------------------------------------------------------------------------------- /pt-br/4_evaluation/README.md: -------------------------------------------------------------------------------- 1 | # Evaluation (Avaliação) 2 | 3 | A avaliação é uma etapa crítica no desenvolvimento e implantação de modelos de linguagem. Ela nos ajuda a entender quão bem nossos modelos desempenham em diferentes capacidades e a identificar áreas para melhorias. Este módulo aborda benchmarks padrão e abordagens de avaliação específicas de domínio para avaliar de forma abrangente o seu modelo smol (miudinho). 4 | 5 | Usaremos o [`lighteval`](https://github.com/huggingface/lighteval), uma poderosa biblioteca de avaliação desenvolvida pelo Hugging Face que se integra perfeitamente ao ecossistema Hugging Face. Para um aprendizado mais profundo nos conceitos e práticas recomendadas de avaliação, confira o [guia](https://github.com/huggingface/evaluation-guidebook). 6 | 7 | ## Visão Geral do Módulo 8 | 9 | Uma estratégia de avaliação completa examina múltiplos aspectos do desempenho do modelo. Avaliamos capacidades específicas de tarefas, como responder a perguntas e sumarização, para entender como o modelo lida com diferentes tipos de problemas. Medimos a qualidade do output através de fatores como coerência e precisão factual. A avaliação de segurança ajuda a identificar outputs potencialmente prejudiciais ou biases. Por fim, os testes de especialização de domínio verificam o conhecimento especializado do modelo no campo-alvo. 10 | 11 | ## Conteúdo 12 | 13 | ### 1️⃣ [Benchmarks Automáticos](./automatic_benchmarks.md) 14 | 15 | Aprenda a avaliar seu modelo usando benchmarks e métricas padronizados. Exploraremos benchmarks comuns, como MMLU e TruthfulQA, entenderemos as principais métricas e configurações de avaliação e abordaremos as melhores práticas para avaliações reproduzíveis. 16 | 17 | ### 2️⃣ [Avaliação de Domnínio Personalizado](./custom_evaluation.md) 18 | 19 | Descubra como criar pipelines de avaliação adaptados ao seu caso de uso específico. Veremos o design de tarefas de avaliação personalizadas, implementação de métricas especializadas e construção de conjuntos de dados de avaliação que atendam às suas necessidades. 20 | 21 | ### 3️⃣ [Projeto de Avaliação de Domínio](./project/README.md) 22 | 23 | Siga um exemplo completo de construção de um pipeline de avaliação de domínio específico. Você aprenderá a gerar conjuntos de dados de avaliação, usar o Argilla para anotação de dados, criar conjuntos de dados padronizados e avaliar modelos usando o LightEval. 24 | 25 | ### Cadernos de Exercício 26 | 27 | | Título | Descrição | Exercício | Link | Colab | 28 | |-------|-------------|----------|------|-------| 29 | | Avalie e Analise Seu LLM | Aprenda a usar o LightEval para avaliar e comparar modelos em domínios específicos | 🐢 Use tarefas do domínio da medicina para avaliar um modelo
🐕 Crie uma nova avaliação de domínio com diferentes tarefas do MMLU
🦁 Crie uma tarefa de avaliação personalizada para o seu domínio | [Notebook](./notebooks/lighteval_evaluate_and_analyse_your_LLM.ipynb) | Open In Colab | 30 | 31 | 32 | ## Referências 33 | 34 | - [Guia de Avaliação](https://github.com/huggingface/evaluation-guidebook) - Guia abrangente de avaliação de LLMs 35 | - [Documentação do LightEval](https://github.com/huggingface/lighteval) - Documentação oficial do módulo LightEval 36 | - [Documentação do Argilla](https://docs.argilla.io) - Saiba mais sobre a plataforma de anotação Argilla 37 | - [Artigo do MMLU](https://arxiv.org/abs/2009.03300) - Artigo que descreve o benchmark MMLU 38 | - [Criando uma Tarefa Personalizada](https://github.com/huggingface/lighteval/wiki/Adding-a-Custom-Task) 39 | - [Criando uma Métrica Personalizada](https://github.com/huggingface/lighteval/wiki/Adding-a-New-Metric) 40 | - [Usando Métricas Existentes](https://github.com/huggingface/lighteval/wiki/Metric-List) -------------------------------------------------------------------------------- /pt-br/4_evaluation/project/create_dataset.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | import argilla as rg 4 | from datasets import Dataset 5 | 6 | ################################################################################ 7 | # Script Parameters 8 | ################################################################################ 9 | 10 | parser = argparse.ArgumentParser( 11 | description="Create a Hugging Face dataset from annotated Argilla data." 12 | ) 13 | parser.add_argument( 14 | "--argilla_api_key", 15 | type=str, 16 | default="argilla.apikey", 17 | help="API key for Argilla", 18 | ) 19 | parser.add_argument( 20 | "--argilla_api_url", 21 | type=str, 22 | default="http://localhost:6900", 23 | help="API URL for Argilla", 24 | ) 25 | parser.add_argument( 26 | "--dataset_path", 27 | type=str, 28 | default="exam_questions", 29 | help="Path to the Argilla dataset", 30 | ) 31 | parser.add_argument( 32 | "--dataset_repo_id", 33 | type=str, 34 | default="burtenshaw/exam_questions", 35 | help="Hugging Face dataset repository ID", 36 | ) 37 | 38 | args = parser.parse_args() 39 | 40 | ################################################################################ 41 | # Initialize Argilla client and load dataset 42 | ################################################################################ 43 | 44 | client = rg.Argilla(api_key=args.argilla_api_key, api_url=args.argilla_api_url) 45 | dataset = client.datasets(args.dataset_path) 46 | 47 | ################################################################################ 48 | # Process Argilla records 49 | ################################################################################ 50 | 51 | dataset_rows = [] 52 | 53 | for record in dataset.records(with_suggestions=True, with_responses=True): 54 | row = record.fields 55 | 56 | if len(record.responses) == 0: 57 | answer = record.suggestions["correct_answer"].value 58 | row["correct_answer"] = answer 59 | else: 60 | for response in record.responses: 61 | if response.question_name == "correct_answer": 62 | row["correct_answer"] = response.value 63 | dataset_rows.append(row) 64 | 65 | ################################################################################ 66 | # Create Hugging Face dataset and push to Hub 67 | ################################################################################ 68 | 69 | hf_dataset = Dataset.from_list(dataset_rows) 70 | hf_dataset.push_to_hub(repo_id=args.dataset_repo_id) 71 | 72 | print(f"Dataset has been successfully pushed to {args.dataset_repo_id}") 73 | -------------------------------------------------------------------------------- /pt-br/4_evaluation/project/evaluation_task.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | from lighteval.tasks.lighteval_task import LightevalTaskConfig 4 | from lighteval.tasks.requests import Doc 5 | from lighteval.metrics.utils.metric_utils import ( 6 | SampleLevelMetric, 7 | MetricCategory, 8 | MetricUseCase, 9 | ) 10 | 11 | ################################################################################ 12 | # Define the prompt function based on the structure of the dataset 13 | ################################################################################ 14 | 15 | 16 | def prompt_fn(line, task_name: str = None): 17 | """Converts a dataset line to a Doc object for evaluation.""" 18 | instruction = "Choose the correct answer for the following exam question:" 19 | return Doc( 20 | task_name=task_name, 21 | query=f"{instruction} {line['question']}", 22 | choices=[ 23 | f" {line['answer_a']}", 24 | f" {line['answer_b']}", 25 | f" {line['answer_c']}", 26 | f" {line['answer_d']}", 27 | ], 28 | gold_index=["answer_a", "answer_b", "answer_c", "answer_d"].index( 29 | line["correct_answer"] 30 | ), 31 | instruction=instruction, 32 | ) 33 | 34 | 35 | ################################################################################ 36 | # Define the custom metric based on guide here https://github.com/huggingface/lighteval/wiki/Adding-a-New-Metric 37 | # Or use an existing metric based on the guide here: https://github.com/huggingface/lighteval/wiki/Metric-List 38 | # Existing metrics can be imported from lighteval.metrics.metrics 39 | ################################################################################ 40 | 41 | 42 | def sample_level_fn(formatted_doc: Doc, **kwargs) -> bool: 43 | response = np.argmin(kwargs["choices_logprob"]) 44 | return response == formatted_doc.gold_index 45 | 46 | 47 | custom_metric = SampleLevelMetric( 48 | metric_name="exam_question_accuracy", 49 | higher_is_better=True, 50 | category=MetricCategory.MULTICHOICE, 51 | use_case=MetricUseCase.NONE, 52 | sample_level_fn=sample_level_fn, 53 | corpus_level_fn=np.mean, 54 | ) 55 | 56 | ################################################################################ 57 | # Define the task based on the prompt function and the custom metric 58 | # Based on the guide here: https://github.com/huggingface/lighteval/wiki/Adding-a-Custom-Task 59 | ################################################################################ 60 | 61 | task = LightevalTaskConfig( 62 | name="example", 63 | prompt_function=prompt_fn, 64 | suite=["community"], 65 | hf_repo="burtenshaw/exam_questions", 66 | hf_subset="default", 67 | hf_avail_splits=["train"], 68 | evaluation_splits=["train"], 69 | few_shots_split=None, 70 | few_shots_select=None, 71 | metric=[custom_metric], 72 | ) 73 | 74 | # Add the task to TASKS_TABLE 75 | TASKS_TABLE = [task] 76 | 77 | # MODULE LOGIC 78 | if __name__ == "__main__": 79 | print([t.name for t in TASKS_TABLE]) 80 | print(len(TASKS_TABLE)) 81 | 82 | # lighteval accelerate \ 83 | # "pretrained=HuggingFaceTB/SmolLM2-135M-Instruct" \ 84 | # "community|example|0|0" \ 85 | # --custom-tasks "submitted_tasks/example.py" \ 86 | # --output-dir "results" 87 | -------------------------------------------------------------------------------- /pt-br/4_evaluation/project/images/domain_eval_argilla_view.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/pt-br/4_evaluation/project/images/domain_eval_argilla_view.png -------------------------------------------------------------------------------- /pt-br/4_evaluation/project/images/domain_eval_dataset_viewer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/pt-br/4_evaluation/project/images/domain_eval_dataset_viewer.png -------------------------------------------------------------------------------- /pull_request_template.md: -------------------------------------------------------------------------------- 1 | # December 2024 Student Submission 2 | 3 | ## Module Completed 4 | - [ ] Module 1: Instruction Tuning 5 | - [ ] Module 2: Preference Alignment 6 | - [ ] Module 3: Parameter-efficient Fine-tuning 7 | - [ ] Module 4: Evaluation 8 | - [ ] Module 5: Vision-language Models 9 | - [ ] Module 6: Synthetic Datasets 10 | - [ ] Module 7: Inference 11 | - [ ] Module 8: Deployment 12 | 13 | ## Changes Made 14 | Describe what you've done in this PR: 15 | 1. What concepts did you learn? 16 | 2. What changes or additions did you make? 17 | 3. Any challenges you faced? 18 | 19 | ## Notebooks Added/Modified 20 | List any notebooks you've added or modified: 21 | - [ ] Added new example in `module_name/student_examples/my_example.ipynb` 22 | - [ ] Modified existing notebook with additional examples 23 | - [ ] Added documentation or comments 24 | 25 | ## Checklist 26 | 27 | - [ ] I have read the module materials 28 | - [ ] My code runs without errors 29 | - [ ] I have pushed models and datasets to the huggingface hub 30 | - [ ] My PR is based on the `december-2024` branch 31 | 32 | ## Questions or Discussion Points 33 | Add any questions you have or points you'd like to discuss: 34 | 1. 35 | 2. 36 | 37 | ## Additional Notes 38 | Any other information that might be helpful for reviewers: 39 | 40 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "smol-course" 3 | version = "0.1.0" 4 | description = "a smol course on llms" 5 | readme = "README.md" 6 | requires-python = ">=3.11" 7 | dependencies = [ 8 | "datasets>=3.1.0", 9 | "huggingface-hub>=0.26.3", 10 | "lighteval>=0.6.2", 11 | "ipywidgets>=8.1.5", 12 | "transformers>=4.46.3", 13 | "trl>=0.12.1", 14 | "bitsandbytes>=0.45.0", 15 | ] 16 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # This file was autogenerated by uv via the following command: 2 | # uv export --format requirements-txt --no-hashes 3 | accelerate==1.1.1 4 | aiohappyeyeballs==2.4.4 5 | aiohttp==3.11.9 6 | aiosignal==1.3.1 7 | attrs==24.2.0 8 | certifi==2024.8.30 9 | charset-normalizer==3.4.0 10 | colorama==0.4.6 ; platform_system == 'Windows' 11 | datasets==3.1.0 12 | dill==0.3.8 13 | filelock==3.16.1 14 | frozenlist==1.5.0 15 | fsspec==2024.9.0 16 | huggingface-hub==0.26.3 17 | idna==3.10 18 | jinja2==3.1.4 19 | markdown-it-py==3.0.0 20 | markupsafe==3.0.2 21 | mdurl==0.1.2 22 | mpmath==1.3.0 23 | multidict==6.1.0 24 | multiprocess==0.70.16 25 | networkx==3.4.2 26 | numpy==2.1.3 27 | nvidia-cublas-cu12==12.4.5.8 ; platform_machine == 'x86_64' and platform_system == 'Linux' 28 | nvidia-cuda-cupti-cu12==12.4.127 ; platform_machine == 'x86_64' and platform_system == 'Linux' 29 | nvidia-cuda-nvrtc-cu12==12.4.127 ; platform_machine == 'x86_64' and platform_system == 'Linux' 30 | nvidia-cuda-runtime-cu12==12.4.127 ; platform_machine == 'x86_64' and platform_system == 'Linux' 31 | nvidia-cudnn-cu12==9.1.0.70 ; platform_machine == 'x86_64' and platform_system == 'Linux' 32 | nvidia-cufft-cu12==11.2.1.3 ; platform_machine == 'x86_64' and platform_system == 'Linux' 33 | nvidia-curand-cu12==10.3.5.147 ; platform_machine == 'x86_64' and platform_system == 'Linux' 34 | nvidia-cusolver-cu12==11.6.1.9 ; platform_machine == 'x86_64' and platform_system == 'Linux' 35 | nvidia-cusparse-cu12==12.3.1.170 ; platform_machine == 'x86_64' and platform_system == 'Linux' 36 | nvidia-nccl-cu12==2.21.5 ; platform_machine == 'x86_64' and platform_system == 'Linux' 37 | nvidia-nvjitlink-cu12==12.4.127 ; platform_machine == 'x86_64' and platform_system == 'Linux' 38 | nvidia-nvtx-cu12==12.4.127 ; platform_machine == 'x86_64' and platform_system == 'Linux' 39 | packaging==24.2 40 | pandas==2.2.3 41 | propcache==0.2.1 42 | psutil==6.1.0 43 | pyarrow==18.1.0 44 | pygments==2.18.0 45 | python-dateutil==2.9.0.post0 46 | pytz==2024.2 47 | pyyaml==6.0.2 48 | regex==2024.11.6 49 | requests==2.32.3 50 | rich==13.9.4 51 | safetensors==0.4.5 52 | setuptools==75.6.0 ; python_full_version >= '3.12' 53 | six==1.17.0 54 | sympy==1.13.1 55 | tokenizers==0.20.3 56 | torch==2.5.1 57 | tqdm==4.67.1 58 | transformers==4.46.3 59 | triton==3.1.0 ; python_full_version < '3.13' and platform_machine == 'x86_64' and platform_system == 'Linux' 60 | trl==0.12.1 61 | typing-extensions==4.12.2 62 | tzdata==2024.2 63 | urllib3==2.2.3 64 | xxhash==3.5.0 65 | yarl==1.18.3 66 | -------------------------------------------------------------------------------- /vi/1_instruction_tuning/README.md: -------------------------------------------------------------------------------- 1 | # Tinh chỉnh theo chỉ thị (Instruction Tuning) 2 | 3 | Trong chương này chúng ta sẽ học về quá trình tinh chỉnh mô hình ngôn ngữ theo chỉ thị. Tinh chỉnh theo chỉ thị là quá trình điều chỉnh *pre-trained models* cho các tác vụ cụ thể bằng cách tiếp tục huấn luyện chúng trên các tập dữ liệu đặc thù cho tác vụ. Quá trình này giúp các mô hình cải thiện hiệu suất trên những tác vụ đó. 4 | 5 | Chúng ta sẽ cùng khám phá hai chủ đề chính: 1) Định dạng Chat (Chat Templates) và 2) Tinh chỉnh có giám sát (Supervised Fine-Tuning). 6 | 7 | ## 1️⃣ Định dạng Chat (Chat Templates) 8 | 9 | Định dạng Chat là cấu trúc giữa các tương tác giữa người dùng và mô hình ngôn ngữ, đảm bảo các phản hồi nhất quán và phù hợp với từng ngữ cảnh. Chúng bao gồm các thành phần như `system prompts` và các `message` theo vai trò (người dùng - `user` hoặc trợ lý - `assistant`). Để biết thêm thông tin chi tiết, hãy tham khảo phần [Chat Templates](./chat_templates.md). 10 | 11 | ## 2️⃣ Huấn luyện có giám sát (Supervised Fine-Tuning) 12 | 13 | Huấn luyện có giám sát (SFT) là một quá trình cốt lõi để điều chỉnh các mô hình ngôn ngữ đã *pre-trained* cho các tác vụ cụ thể. Quá trình này bao gồm việc huấn luyện mô hình trên tập dữ liệu có gán nhãn theo tác vụ cụ thể. Để đọc hướng dẫn chi tiết về SFT, bao gồm các bước quan trọng và các phương pháp thực hành tốt nhất, hãy xem tại trang [Supervised Fine-Tuning](./supervised_fine_tuning.md). 14 | 15 | ## Bài tập 16 | 17 | | Tiêu đề | Mô tả | Bài tập | Đường dẫn | Google Colab | 18 | |-------|-------------|----------|------|-------| 19 | | Định dạng Chat | Học cách sử dụng *định dạng chat* với SmolLM2 và xử lý dữ liệu thành định dạng *chatml* | 🐢 Chuyển đổi tập dữ liệu `HuggingFaceTB/smoltalk` sang định dạng *chatml*
🐕 Chuyển đổi tập dữ liệu `openai/gsm8k` sang định dạng *chatml* | [Notebook](./notebooks/chat_templates_example.ipynb) | Sử dụng Colab | 20 | | Tinh chỉnh có giám sát | Học cách tinh chỉnh SmolLM2 sử dụng SFTTrainer | 🐢 Sử dụng tập dữ liệu `HuggingFaceTB/smoltalk`
🐕 Thử nghiệm với tập dữ liệu `bigcode/the-stack-smol`
🦁 Chọn một tập dữ liệu cho trường hợp sử dụng thực tế | [Notebook](./notebooks/sft_finetuning_example.ipynb) | Sử dụng Colab | 21 | 22 | ## Tài liệu tham khảo 23 | 24 | - [Tài liệu Transformers về định dạng chat](https://huggingface.co/docs/transformers/main/en/chat_templating) 25 | - [Script cho huấn luyện có giám sát bằng thư viện TRL](https://github.com/huggingface/trl/blob/main/examples/scripts/sft.py) 26 | - [`SFTTrainer` trong thư viện TRL](https://huggingface.co/docs/trl/main/en/sft_trainer) 27 | - [Bài báo Direct Preference Optimization (DPO)](https://arxiv.org/abs/2305.18290) 28 | - [Huấn luyện có giám sát bằng thư viện TRL](https://huggingface.co/docs/trl/main/en/tutorials/supervised_finetuning) 29 | - [Cách fine-tune Google Gemma với ChatML và Hugging Face TRL](https://www.philschmid.de/fine-tune-google-gemma) 30 | - [Huấn luyện LLM để tạo danh mục sản phẩm tiếng Ba Tư ở định dạng JSON](https://huggingface.co/learn/cookbook/en/fine_tuning_llm_to_generate_persian_product_catalogs_in_json_format) 31 | -------------------------------------------------------------------------------- /vi/1_instruction_tuning/notebooks/.env.example: -------------------------------------------------------------------------------- 1 | # Sao chép file này thành .env và điền các API key 2 | HF_TOKEN= -------------------------------------------------------------------------------- /vi/3_parameter_efficient_finetuning/README.md: -------------------------------------------------------------------------------- 1 | # Tinh chỉnh hiệu quả tham số (Parameter-Efficient Fine-Tuning - PEFT) 2 | 3 | Khi các mô hình ngôn ngữ ngày càng lớn hơn, việc tinh chỉnh truyền thống trở nên ngày càng thách thức. Việc tinh chỉnh đầy đủ một mô hình với 1.7B tham số đòi hỏi bộ nhớ GPU lớn, việc lưu trữ các bản sao mô hình riêng biệt tốn kém, và có nguy cơ làm mất đi các khả năng ban đầu của mô hình. Các phương pháp tinh chỉnh hiệu quả tham số (PEFT) giải quyết những thách thức này bằng cách chỉ điều chỉnh một tập nhỏ các tham số mô hình trong khi giữ nguyên phần lớn mô hình. 4 | 5 | Tinh chỉnh truyền thống cập nhật tất cả các tham số mô hình trong quá trình huấn luyện, điều này trở nên không khả thi với các mô hình lớn. Các phương pháp PEFT giới thiệu cách tiếp cận để điều chỉnh mô hình sử dụng ít tham số có thể huấn luyện hơn - thường ít hơn 1% kích thước mô hình gốc. Việc giảm đáng kể số lượng tham số có thể huấn luyện cho phép: 6 | 7 | - Tinh chỉnh trên phần cứng tiêu dùng với bộ nhớ GPU hạn chế 8 | - Lưu trữ nhiều phiên bản điều chỉnh (adapters) cho từng tác vụ một cách hiệu quả 9 | - Khả năng tổng quát hóa tốt hơn trong các trường hợp dữ liệu ít 10 | - Chu kỳ huấn luyện và thử nghiệm nhanh hơn 11 | 12 | ## Các phương pháp hiện có 13 | 14 | Trong chương này, chúng ta sẽ tìm hiểu hai phương pháp PEFT phổ biến: 15 | 16 | ### 1️⃣ Phương Pháp LoRA (Low-Rank Adaptation) 17 | 18 | LoRA đã nổi lên như phương pháp PEFT được áp dụng rộng rãi nhất, cung cấp giải pháp hoàn hảo cho việc điều chỉnh mô hình hiệu quả mà không tốn nhiều tài nguyên tính toán. Thay vì sửa đổi toàn bộ mô hình, **LoRA đưa các ma trận có thể huấn luyện vào các lớp attention của mô hình.** Cách tiếp cận này thường giảm các tham số có thể huấn luyện khoảng 90% trong khi vẫn duy trì hiệu suất tương đương với tinh chỉnh đầy đủ. Chúng ta sẽ khám phá LoRA trong phần [LoRA (Low-Rank Adaptation)](./lora_adapters.md). 19 | 20 | ### 2️⃣ Phương Pháp Điều Chỉnh Chỉ Thị (Prompt Tuning) 21 | 22 | Prompt tuning cung cấp cách tiếp cận **thậm chí nhẹ hơn** bằng cách **thêm các token có thể huấn luyện vào đầu vào** thay vì sửa đổi trọng số mô hình. Prompt tuning ít phổ biến hơn LoRA, nhưng có thể là kỹ thuật hữu ích để nhanh chóng điều chỉnh mô hình cho các tác vụ hoặc lĩnh vực mới. Chúng ta sẽ khám phá prompt tuning trong phần [Prompt Tuning](./prompt_tuning.md). 23 | 24 | ## Notebooks bài tập 25 | 26 | | Tiêu đề | Mô tả | Bài tập | Link | Colab | 27 | |---------|--------|---------|------|-------| 28 | | Tinh chỉnh LoRA | Học cách tinh chỉnh mô hình sử dụng LoRA adapters | 🐢 Huấn luyện mô hình sử dụng LoRA
🐕 Thử nghiệm với các giá trị rank khác nhau
🦁 So sánh hiệu suất với tinh chỉnh đầy đủ | [Notebook](./notebooks/finetune_sft_peft.ipynb) | Open In Colab | 29 | | Tải LoRA Adapters | Học cách tải và sử dụng LoRA adapters đã huấn luyện | 🐢 Tải adapters đã huấn luyện trước
🐕 Gộp adapters với mô hình cơ sở
🦁 Chuyển đổi giữa nhiều adapters | [Notebook](./notebooks/load_lora_adapter.ipynb) | Open In Colab | 30 | 31 | ## Tài liệu tham khảo 32 | - [Tài liệu PEFT](https://huggingface.co/docs/peft) 33 | - [Bài báo nghiên cứu LoRA](https://arxiv.org/abs/2106.09685) 34 | - [Bài báo nghiên cứu QLoRA](https://arxiv.org/abs/2305.14314) 35 | - [Bài báo nghiên cứu Prompt Tuning](https://arxiv.org/abs/2104.08691) 36 | - [Hướng dẫn sử dụng PEFT của Hugging Face](https://huggingface.co/blog/peft) 37 | - [Cách Tinh chỉnh LLM với Hugging Face](https://www.philschmid.de/fine-tune-llms-in-2024-with-trl) 38 | - [Thư viện TRL](https://huggingface.co/docs/trl/index) -------------------------------------------------------------------------------- /vi/3_parameter_efficient_finetuning/images/lora_adapter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/vi/3_parameter_efficient_finetuning/images/lora_adapter.png -------------------------------------------------------------------------------- /vi/3_parameter_efficient_finetuning/images/prompt_tuning.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/vi/3_parameter_efficient_finetuning/images/prompt_tuning.png -------------------------------------------------------------------------------- /vi/4_evaluation/README.md: -------------------------------------------------------------------------------- 1 | # Đánh giá mô hình 2 | 3 | Đánh giá là bước quan trọng trong việc phát triển và triển khai các mô hình ngôn ngữ. Nó giúp chúng ta hiểu được mô hình hoạt động tốt như thế nào qua các khả năng khác nhau và xác định những lĩnh vực cần cải thiện. Chương này bao gồm các phương pháp đánh giá (benchmark) tiêu chuẩn và các phương pháp đánh giá theo lĩnh vực cụ thể để đánh giá toàn diện mô hình của bạn. 4 | 5 | Chúng ta sẽ sử dụng [`lighteval`](https://github.com/huggingface/lighteval), một thư viện chuyên được sử dụng để đánh giá mô hình ngôn ngữ được phát triển bởi Hugging Face. Thư viện này được thiết kế tối giản giúp người sử dụng dễ dàng tiếp cận và được tích hợp để phù hợp với hệ sinh thái của Hugging Face. Để tìm hiểu sâu hơn về các khái niệm và thực hành về đánh giá mô hình ngôn ngữ, hãy tham khảo [hướng dẫn](https://github.com/huggingface/evaluation-guidebook) về đánh giá. 6 | 7 | ## Tổng quan chương học 8 | 9 | Một quy trình đánh giá mô hình thường bao gồm nhiều khía cạnh về hiệu năng của mô hình. Chúng ta đánh giá các khả năng theo tác vụ cụ thể như *trả lời câu hỏi* và *tóm tắt* để hiểu mô hình xử lý các loại vấn đề khác nhau tốt đến đâu. Chúng ta đo lường chất lượng đầu ra thông qua các yếu tố như *tính mạch lạc* và *độ chính xác*. Đánh giá về *độ an toàn* giúp xác định các đầu ra của mô hình có chứa các hành vi khuyển khích thực hiện hành đông độc hại hoặc định kiến tiềm ẩn. Cuối cùng, kiểm tra *chuyên môn* về lĩnh vực xác minh kiến thức chuyên biệt của mô hình trong lĩnh vực mục tiêu của bạn. 10 | 11 | ## Nội dung 12 | 13 | ### 1️⃣ [Đánh giá mô hình tự động](./automatic_benchmarks.md) 14 | 15 | Học cách đánh giá mô hình của bạn bằng các phương pháp đánh giá và số liệu chuẩn hoá. Chúng ta sẽ khám phá các phương pháp đánh giá phổ biến như `MMLU` và `TruthfulQA`, hiểu các chỉ số đánh giá và cài đặt quan trọng, đồng thời đề cập đến các thực hành tốt nhất cho việc đánh giá có thể tái tạo lại. 16 | 17 | ### 2️⃣ [Đánh giá theo yêu cầu đặc biệt](./custom_evaluation.md) 18 | Khám phá cách tạo quy trình (pipeline) đánh giá phù hợp với trường hợp sử dụng cụ thể của bạn. Chúng ta sẽ hướng dẫn thiết kế các tác vụ đánh giá theo yêu cầu (custom), triển khai các số liệu chuyên biệt và xây dựng tập dữ liệu đánh giá phù hợp với yêu cầu của bạn. 19 | 20 | ### 3️⃣ [Dự án đánh giá theo lĩnh vực cụ thể](./project/README.md) 21 | Theo dõi một ví dụ hoàn chỉnh về việc xây dựng quy trình đánh giá cho lĩnh vực cụ thể. Bạn sẽ học cách tạo tập dữ liệu đánh giá, sử dụng `Argilla` để gán nhãn dữ liệu, tạo tập dữ liệu chuẩn hoá và đánh giá mô hình bằng `LightEval`. 22 | 23 | ### Các notebook bài tập 24 | 25 | | Tiêu đề | Mô tả | Bài tập | Link | Colab | 26 | |---------|-------|---------|------|-------| 27 | | Đánh giá và phân tích mô hình LLM của bạn | Học cách sử dụng `LightEval` để đánh giá và so sánh các mô hình trên các lĩnh vực cụ thể | 🐢 Sử dụng các tác vụ trong **lĩnh vực y tế** để đánh giá mô hình
🐕 Tạo đánh giá lĩnh vực mới với các tác vụ MMLU khác nhau
🦁 Tạo tác vụ đánh giá cho lĩnh vực của bạn | [Notebook](./notebooks/lighteval_evaluate_and_analyse_your_LLM.ipynb) | Open In Colab | 28 | 29 | ## Tài liệu tham khảo 30 | 31 | - [Hướng dẫn đánh giá](https://github.com/huggingface/evaluation-guidebook) - Hướng dẫn toàn diện về đánh giá LLM 32 | - [Tài liệu LightEval](https://github.com/huggingface/lighteval) - Tài liệu chính thức cho thư viện LightEval 33 | - [Tài liệu Argilla](https://docs.argilla.io) - Tìm hiểu về nền tảng gán nhãn Argilla 34 | - [Paper MMLU](https://arxiv.org/abs/2009.03300) - Paper mô tả benchmark MMLU 35 | - [Tạo tác vụ theo yêu cầu](https://github.com/huggingface/lighteval/wiki/Adding-a-Custom-Task) 36 | - [Tạo tiêu chuẩn đánh giá theo yêu cầu](https://github.com/huggingface/lighteval/wiki/Adding-a-New-Metric) 37 | - [Sử dụng số liệu có sẵn](https://github.com/huggingface/lighteval/wiki/Metric-List) -------------------------------------------------------------------------------- /vi/4_evaluation/project/create_dataset.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | import argilla as rg 4 | from datasets import Dataset 5 | 6 | ################################################################################ 7 | # Script Parameters 8 | ################################################################################ 9 | 10 | parser = argparse.ArgumentParser( 11 | description="Create a Hugging Face dataset from annotated Argilla data." 12 | ) 13 | parser.add_argument( 14 | "--argilla_api_key", 15 | type=str, 16 | default="argilla.apikey", 17 | help="API key for Argilla", 18 | ) 19 | parser.add_argument( 20 | "--argilla_api_url", 21 | type=str, 22 | default="http://localhost:6900", 23 | help="API URL for Argilla", 24 | ) 25 | parser.add_argument( 26 | "--dataset_path", 27 | type=str, 28 | default="exam_questions", 29 | help="Path to the Argilla dataset", 30 | ) 31 | parser.add_argument( 32 | "--dataset_repo_id", 33 | type=str, 34 | default="burtenshaw/exam_questions", 35 | help="Hugging Face dataset repository ID", 36 | ) 37 | 38 | args = parser.parse_args() 39 | 40 | ################################################################################ 41 | # Initialize Argilla client and load dataset 42 | ################################################################################ 43 | 44 | client = rg.Argilla(api_key=args.argilla_api_key, api_url=args.argilla_api_url) 45 | dataset = client.datasets(args.dataset_path) 46 | 47 | ################################################################################ 48 | # Process Argilla records 49 | ################################################################################ 50 | 51 | dataset_rows = [] 52 | 53 | for record in dataset.records(with_suggestions=True, with_responses=True): 54 | row = record.fields 55 | 56 | if len(record.responses) == 0: 57 | answer = record.suggestions["correct_answer"].value 58 | row["correct_answer"] = answer 59 | else: 60 | for response in record.responses: 61 | if response.question_name == "correct_answer": 62 | row["correct_answer"] = response.value 63 | dataset_rows.append(row) 64 | 65 | ################################################################################ 66 | # Create Hugging Face dataset and push to Hub 67 | ################################################################################ 68 | 69 | hf_dataset = Dataset.from_list(dataset_rows) 70 | hf_dataset.push_to_hub(repo_id=args.dataset_repo_id) 71 | 72 | print(f"Dataset has been successfully pushed to {args.dataset_repo_id}") 73 | -------------------------------------------------------------------------------- /vi/4_evaluation/project/evaluation_task.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | from lighteval.tasks.lighteval_task import LightevalTaskConfig 4 | from lighteval.tasks.requests import Doc 5 | from lighteval.metrics.utils.metric_utils import ( 6 | SampleLevelMetric, 7 | MetricCategory, 8 | MetricUseCase, 9 | ) 10 | 11 | ################################################################################ 12 | # Define the prompt function based on the structure of the dataset 13 | ################################################################################ 14 | 15 | 16 | def prompt_fn(line, task_name: str = None): 17 | """Converts a dataset line to a Doc object for evaluation.""" 18 | instruction = "Choose the correct answer for the following exam question:" 19 | return Doc( 20 | task_name=task_name, 21 | query=f"{instruction} {line['question']}", 22 | choices=[ 23 | f" {line['answer_a']}", 24 | f" {line['answer_b']}", 25 | f" {line['answer_c']}", 26 | f" {line['answer_d']}", 27 | ], 28 | gold_index=["answer_a", "answer_b", "answer_c", "answer_d"].index( 29 | line["correct_answer"] 30 | ), 31 | instruction=instruction, 32 | ) 33 | 34 | 35 | ################################################################################ 36 | # Define the custom metric based on guide here https://github.com/huggingface/lighteval/wiki/Adding-a-New-Metric 37 | # Or use an existing metric based on the guide here: https://github.com/huggingface/lighteval/wiki/Metric-List 38 | # Existing metrics can be imported from lighteval.metrics.metrics 39 | ################################################################################ 40 | 41 | 42 | def sample_level_fn(formatted_doc: Doc, **kwargs) -> bool: 43 | response = np.argmin(kwargs["choices_logprob"]) 44 | return response == formatted_doc.gold_index 45 | 46 | 47 | custom_metric = SampleLevelMetric( 48 | metric_name="exam_question_accuracy", 49 | higher_is_better=True, 50 | category=MetricCategory.MULTICHOICE, 51 | use_case=MetricUseCase.NONE, 52 | sample_level_fn=sample_level_fn, 53 | corpus_level_fn=np.mean, 54 | ) 55 | 56 | ################################################################################ 57 | # Define the task based on the prompt function and the custom metric 58 | # Based on the guide here: https://github.com/huggingface/lighteval/wiki/Adding-a-Custom-Task 59 | ################################################################################ 60 | 61 | task = LightevalTaskConfig( 62 | name="example", 63 | prompt_function=prompt_fn, 64 | suite=["community"], 65 | hf_repo="burtenshaw/exam_questions", 66 | hf_subset="default", 67 | hf_avail_splits=["train"], 68 | evaluation_splits=["train"], 69 | few_shots_split=None, 70 | few_shots_select=None, 71 | metric=[custom_metric], 72 | ) 73 | 74 | # Add the task to TASKS_TABLE 75 | TASKS_TABLE = [task] 76 | 77 | # MODULE LOGIC 78 | if __name__ == "__main__": 79 | print([t.name for t in TASKS_TABLE]) 80 | print(len(TASKS_TABLE)) 81 | 82 | # lighteval accelerate \ 83 | # "pretrained=HuggingFaceTB/SmolLM2-135M-Instruct" \ 84 | # "community|example|0|0" \ 85 | # --custom-tasks "submitted_tasks/example.py" \ 86 | # --output-dir "results" 87 | -------------------------------------------------------------------------------- /vi/4_evaluation/project/images/domain_eval_argilla_view.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/vi/4_evaluation/project/images/domain_eval_argilla_view.png -------------------------------------------------------------------------------- /vi/4_evaluation/project/images/domain_eval_dataset_viewer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/vi/4_evaluation/project/images/domain_eval_dataset_viewer.png -------------------------------------------------------------------------------- /vi/5_vision_language_models/images/VLM_Architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/vi/5_vision_language_models/images/VLM_Architecture.png -------------------------------------------------------------------------------- /vi/5_vision_language_models/images/VLM_Process.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/vi/5_vision_language_models/images/VLM_Process.png -------------------------------------------------------------------------------- /vi/5_vision_language_models/images/VLM_Usage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/vi/5_vision_language_models/images/VLM_Usage.png -------------------------------------------------------------------------------- /vi/6_synthetic_datasets/README.md: -------------------------------------------------------------------------------- 1 | # Tạo tập dữ liệu giả lập (Synthetic Datasets) 2 | 3 | Dữ liệu giả lập (synthetic data) là dữ liệu được tạo ra nhân tạo mô phỏng việc sử dụng trong thế giới thực. Nó cho phép khắc phục các hạn chế về dữ liệu bằng cách mở rộng hoặc nâng cao các tập dữ liệu. Mặc dù dữ liệu giả lập đã được sử dụng cho một số trường hợp, các mô hình ngôn ngữ lớn đã làm cho các tập dữ liệu giả lập trở nên phổ biến hơn cho việc huấn luyện trước, huấn luyện sau và đánh giá các mô hình ngôn ngữ. 4 | 5 | Chúng ta sẽ sử dụng [`distilabel`](https://distilabel.argilla.io/latest/), một thư viện (framework) tạo dữ liệu giả lập và phản hồi AI cho các kỹ sư, những người cần các quy trình (pipeline) nhanh, đáng tin cậy và có thể mở rộng dựa trên các bài báo nghiên cứu đã được xác minh. Để tìm hiểu sâu hơn về package và các phương pháp hay nhất, hãy xem [tài liệu](https://distilabel.argilla.io/latest/). 6 | 7 | ## Tổng quan về Mô-đun 8 | 9 | Dữ liệu giả lập cho các mô hình ngôn ngữ có thể được phân loại thành ba loại: hướng dẫn (instructions), sở thích (preferences) và phê bình (critiques). Chúng ta sẽ tập trung vào hai loại đầu tiên, tập trung vào việc tạo ra các tập dữ liệu để tinh chỉnh hướng dẫn (instruction tuning) và điều chỉnh sở thích (preference alignment). Trong cả hai loại, chúng ta sẽ đề cập đến các khía cạnh của loại thứ ba, tập trung vào việc cải thiện dữ liệu hiện có bằng các phê bình và viết lại của mô hình. 10 | 11 | ![Phân loại dữ liệu giả lập](./images/taxonomy-synthetic-data.png) 12 | 13 | ## Nội dung 14 | 15 | ### 1. [Tập dữ liệu hướng dẫn](./instruction_datasets.md) 16 | 17 | Tìm hiểu cách tạo tập dữ liệu hướng dẫn để tinh chỉnh hướng dẫn. Chúng ta sẽ khám phá việc tạo các tập dữ liệu tinh chỉnh hướng dẫn thông qua các lời nhắc (prompting) cơ bản và sử dụng các kỹ thuật nhắc nhở tinh tế hơn từ các bài báo. Các tập dữ liệu tinh chỉnh hướng dẫn với dữ liệu mẫu (seed data) để học trong ngữ cảnh (in-context learning) có thể được tạo ra thông qua các phương pháp như `SelfInstruct` và `Magpie`. Ngoài ra, chúng ta sẽ khám phá sự tiến hóa hướng dẫn thông qua `EvolInstruct`. [Bắt đầu học](./instruction_datasets.md). 18 | 19 | ### 2. [Tập dữ liệu ưu tiên](./preference_datasets.md) 20 | 21 | Tìm hiểu cách tạo tập dữ liệu sở thích để điều chỉnh sở thích. Chúng ta sẽ xây dựng dựa trên các phương pháp và kỹ thuật được giới thiệu trong phần 1, bằng cách tạo thêm các phản hồi. Tiếp theo, chúng ta sẽ học cách cải thiện các phản hồi đó bằng lời nhắc `EvolQuality`. Cuối cùng, chúng ta sẽ khám phá cách đánh giá các phản hồi bằng lời nhắc `UltraFeedback`, lời nhắc này sẽ tạo ra điểm số và phê bình, cho phép chúng ta tạo các cặp sở thích. [Bắt đầu học](./preference_datasets.md). 22 | 23 | ### Notebook bài tập 24 | 25 | | Tiêu đề | Mô tả | Bài tập | Liên kết | Colab | 26 | |-------|-------------|----------|------|-------| 27 | | Tập dữ liệu hướng dẫn | Tạo tập dữ liệu để tinh chỉnh hướng dẫn | 🐢 Tạo tập dữ liệu tinh chỉnh hướng dẫn
🐕 Tạo tập dữ liệu tinh chỉnh hướng dẫn với dữ liệu hạt giống
🦁 Tạo tập dữ liệu tinh chỉnh hướng dẫn với dữ liệu hạt giống và với sự tiến hóa hướng dẫn | [Liên kết](./notebooks/instruction_sft_dataset.ipynb) | [Colab](https://githubtocolab.com/huggingface/smol-course/tree/main/6_synthetic_datasets/notebooks/instruction_sft_dataset.ipynb) | 28 | | Tập dữ liệu ưu tiên | Tạo tập dữ liệu để điều chỉnh sở thích | 🐢 Tạo tập dữ liệu điều chỉnh sở thích
🐕 Tạo tập dữ liệu điều chỉnh sở thích với sự tiến hóa phản hồi
🦁 Tạo tập dữ liệu điều chỉnh sở thích với sự tiến hóa phản hồi và phê bình | [Liên kết](./notebooks/preference_alignment_dataset.ipynb) | [Colab](https://githubtocolab.com/huggingface/smol-course/tree/main/6_synthetic_datasets/notebooks/preference_alignment_dataset.ipynb) | 29 | 30 | ## Tài liệu tham khảo 31 | 32 | - [Tài liệu Distilabel](https://distilabel.argilla.io/latest/) 33 | - [Trình tạo dữ liệu tổng hợp là ứng dụng UI](https://huggingface.co/blog/synthetic-data-generator) 34 | - [SmolTalk](https://huggingface.co/datasets/HuggingFaceTB/smoltalk) 35 | - [Self-instruct](https://arxiv.org/abs/2212.10560) 36 | - [Evol-Instruct](https://arxiv.org/abs/2304.12244) 37 | - [Magpie](https://arxiv.org/abs/2406.08464) 38 | - [UltraFeedback](https://arxiv.org/abs/2310.01377) 39 | - [Deita](https://arxiv.org/abs/2312.15685) -------------------------------------------------------------------------------- /vi/6_synthetic_datasets/images/pipeline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/vi/6_synthetic_datasets/images/pipeline.png -------------------------------------------------------------------------------- /vi/6_synthetic_datasets/images/taxonomy-synthetic-data.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/smol-course/a5cc73e2e0a9df77d2c34369314431c94674a5dd/vi/6_synthetic_datasets/images/taxonomy-synthetic-data.png --------------------------------------------------------------------------------