diff --git a/.github/ISSUE_TEMPLATE/translations.md b/.github/ISSUE_TEMPLATE/translations.md index caf57d9cf..e9bfb323a 100644 --- a/.github/ISSUE_TEMPLATE/translations.md +++ b/.github/ISSUE_TEMPLATE/translations.md @@ -1,109 +1,109 @@ ---- -name: Translation template -about: 🤝 Translating the course to another language -title: '' -labels: translation -assignees: '' - ---- - - - -Hi there 👋 - -Let's translate the course to `YOUR-LANG` so that the whole community can benefit from this resource 🌎! - -Below are the chapters and files that need translating - let us know here if you'd like to translate any and we'll add your name to the list. Once you're finished, open a pull request and tag this issue by including `#issue-number` in the description, where `issue-number` is the number of this issue. - -> 🙋 If you'd like others to help you with the translation, you can also post in our [forums](https://discuss.huggingface.co/c/course/20) or tag [@_lewtun](https://twitter.com/_lewtun) on Twitter to gain some visibility. - -## Chapters - -**0 - Setup** -- [ ] [`1.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter0/1.mdx) - -**1 - Transformer models** -- [ ] [`1.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter1/1.mdx) -- [ ] [`2.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter1/2.mdx) -- [ ] [`3.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter1/3.mdx) -- [ ] [`4.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter1/4.mdx) -- [ ] [`5.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter1/5.mdx) -- [ ] [`6.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter1/6.mdx) -- [ ] [`7.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter1/7.mdx) -- [ ] [`8.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter1/8.mdx) -- [ ] [`9.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter1/9.mdx) -- [ ] [`10.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter1/10.mdx) - -**2 - Using 🤗 Transformers** -- [ ] [`1.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter2/1.mdx) -- [ ] [`2.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter2/2.mdx) -- [ ] [`3.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter2/3.mdx) -- [ ] [`4.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter2/4.mdx) -- [ ] [`5.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter2/5.mdx) -- [ ] [`6.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter2/6.mdx) -- [ ] [`7.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter2/7.mdx) -- [ ] [`8.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter2/8.mdx) - -**3 - Fine-tuning a pretrained model** -- [ ] [`1.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter3/1.mdx) -- [ ] [`2.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter3/2.mdx) -- [ ] [`3.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter3/3.mdx) -- [ ] [`3_tf.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter3/3_tf.mdx) -- [ ] [`4.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter3/4.mdx) -- [ ] [`5.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter3/5.mdx) -- [ ] [`6.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter3/6.mdx) - -**4 - Sharing models and tokenizers** -- [ ] [`1.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter4/1.mdx) -- [ ] [`2.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter4/2.mdx) -- [ ] [`3.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter4/3.mdx) -- [ ] [`4.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter4/4.mdx) -- [ ] [`5.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter4/5.mdx) -- [ ] [`6.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter4/6.mdx) - -**5 - The 🤗 Datasets library** -- [ ] [`1.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter5/1.mdx) -- [ ] [`2.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter5/2.mdx) -- [ ] [`3.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter5/3.mdx) -- [ ] [`4.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter5/4.mdx) -- [ ] [`5.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter5/5.mdx) -- [ ] [`6.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter5/6.mdx) -- [ ] [`7.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter5/7.mdx) -- [ ] [`8.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter5/8.mdx) - -**6 - The 🤗 Tokenizers library** -- [ ] [`1.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/1.mdx) -- [ ] [`2.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/2.mdx) -- [ ] [`3.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/3.mdx) -- [ ] [`3b.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/3b.mdx) -- [ ] [`4.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/4.mdx) -- [ ] [`5.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/5.mdx) -- [ ] [`6.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/6.mdx) -- [ ] [`7.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/7.mdx) -- [ ] [`8.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/8.mdx) -- [ ] [`9.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/9.mdx) -- [ ] [`10.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/10.mdx) - -**7 - Main NLP tasks** -- [ ] [`1.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter7/1.mdx) -- [ ] [`2.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter7/2.mdx) -- [ ] [`3.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter7/3.mdx) -- [ ] [`4.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter7/4.mdx) -- [ ] [`5.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter7/5.mdx) -- [ ] [`6.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter7/6.mdx) -- [ ] [`7.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter7/7.mdx) -- [ ] [`8.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter7/8.mdx) -- [ ] [`9.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter7/9.mdx) - -**8 - How to ask for help** -- [ ] [`1.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter8/1.mdx) -- [ ] [`2.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter8/2.mdx) -- [ ] [`3.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter8/3.mdx) -- [ ] [`4.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter8/4.mdx) -- [ ] [`4_tf.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter8/4_tf.mdx) -- [ ] [`5.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter8/5.mdx) -- [ ] [`6.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter8/6.mdx) -- [ ] [`7.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter8/7.mdx) - -**Events** +--- +name: Translation template +about: 🤝 Translating the course to another language +title: '' +labels: translation +assignees: '' + +--- + + + +Hi there 👋 + +Let's translate the course to `YOUR-LANG` so that the whole community can benefit from this resource 🌎! + +Below are the chapters and files that need translating - let us know here if you'd like to translate any and we'll add your name to the list. Once you're finished, open a pull request and tag this issue by including `#issue-number` in the description, where `issue-number` is the number of this issue. + +> 🙋 If you'd like others to help you with the translation, you can also post in our [forums](https://discuss.huggingface.co/c/course/20) or tag [@_lewtun](https://twitter.com/_lewtun) on Twitter to gain some visibility. + +## Chapters + +**0 - Setup** +- [ ] [`1.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter0/1.mdx) + +**1 - Transformer models** +- [ ] [`1.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter1/1.mdx) +- [ ] [`2.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter1/2.mdx) +- [ ] [`3.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter1/3.mdx) +- [ ] [`4.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter1/4.mdx) +- [ ] [`5.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter1/5.mdx) +- [ ] [`6.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter1/6.mdx) +- [ ] [`7.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter1/7.mdx) +- [ ] [`8.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter1/8.mdx) +- [ ] [`9.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter1/9.mdx) +- [ ] [`10.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter1/10.mdx) + +**2 - Using 🤗 Transformers** +- [ ] [`1.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter2/1.mdx) +- [ ] [`2.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter2/2.mdx) +- [ ] [`3.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter2/3.mdx) +- [ ] [`4.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter2/4.mdx) +- [ ] [`5.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter2/5.mdx) +- [ ] [`6.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter2/6.mdx) +- [ ] [`7.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter2/7.mdx) +- [ ] [`8.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter2/8.mdx) + +**3 - Fine-tuning a pretrained model** +- [ ] [`1.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter3/1.mdx) +- [ ] [`2.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter3/2.mdx) +- [ ] [`3.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter3/3.mdx) +- [ ] [`3_tf.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter3/3_tf.mdx) +- [ ] [`4.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter3/4.mdx) +- [ ] [`5.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter3/5.mdx) +- [ ] [`6.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter3/6.mdx) + +**4 - Sharing models and tokenizers** +- [ ] [`1.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter4/1.mdx) +- [ ] [`2.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter4/2.mdx) +- [ ] [`3.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter4/3.mdx) +- [ ] [`4.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter4/4.mdx) +- [ ] [`5.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter4/5.mdx) +- [ ] [`6.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter4/6.mdx) + +**5 - The 🤗 Datasets library** +- [ ] [`1.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter5/1.mdx) +- [ ] [`2.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter5/2.mdx) +- [ ] [`3.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter5/3.mdx) +- [ ] [`4.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter5/4.mdx) +- [ ] [`5.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter5/5.mdx) +- [ ] [`6.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter5/6.mdx) +- [ ] [`7.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter5/7.mdx) +- [ ] [`8.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter5/8.mdx) + +**6 - The 🤗 Tokenizers library** +- [ ] [`1.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/1.mdx) +- [ ] [`2.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/2.mdx) +- [ ] [`3.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/3.mdx) +- [ ] [`3b.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/3b.mdx) +- [ ] [`4.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/4.mdx) +- [ ] [`5.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/5.mdx) +- [ ] [`6.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/6.mdx) +- [ ] [`7.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/7.mdx) +- [ ] [`8.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/8.mdx) +- [ ] [`9.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/9.mdx) +- [ ] [`10.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter6/10.mdx) + +**7 - Main NLP tasks** +- [ ] [`1.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter7/1.mdx) +- [ ] [`2.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter7/2.mdx) +- [ ] [`3.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter7/3.mdx) +- [ ] [`4.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter7/4.mdx) +- [ ] [`5.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter7/5.mdx) +- [ ] [`6.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter7/6.mdx) +- [ ] [`7.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter7/7.mdx) +- [ ] [`8.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter7/8.mdx) +- [ ] [`9.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter7/9.mdx) + +**8 - How to ask for help** +- [ ] [`1.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter8/1.mdx) +- [ ] [`2.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter8/2.mdx) +- [ ] [`3.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter8/3.mdx) +- [ ] [`4.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter8/4.mdx) +- [ ] [`4_tf.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter8/4_tf.mdx) +- [ ] [`5.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter8/5.mdx) +- [ ] [`6.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter8/6.mdx) +- [ ] [`7.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/chapter8/7.mdx) + +**Events** - [ ] [`1.mdx`](https://github.com/huggingface/course/blob/main/chapters/en/event/1.mdx) \ No newline at end of file diff --git a/.github/workflows/build_documentation.yml b/.github/workflows/build_documentation.yml index a3e462fbe..339d7a254 100644 --- a/.github/workflows/build_documentation.yml +++ b/.github/workflows/build_documentation.yml @@ -14,6 +14,6 @@ jobs: package: course path_to_docs: course/chapters/ additional_args: --not_python_module - languages: ar bn de en es fa fr gj he hi id it ja ko my ne pl pt ru ro te th tr vi zh-CN zh-TW + languages: ar bn de en es fa fr gj he hi id it ja ko ml my ne pl pt ru ro te th tr vi zh-CN zh-TW secrets: hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }} diff --git a/.github/workflows/build_pr_documentation.yml b/.github/workflows/build_pr_documentation.yml index 7bceda10f..dde410abc 100644 --- a/.github/workflows/build_pr_documentation.yml +++ b/.github/workflows/build_pr_documentation.yml @@ -16,4 +16,4 @@ jobs: package: course path_to_docs: course/chapters/ additional_args: --not_python_module - languages: ar bn de en es fa fr gj he hi id it ja ko my ne pl pt ru ro te th tr vi zh-CN zh-TW + languages: ar bn de en es fa fr gj he hi id it ja ko ml my ne pl pt ru ro te th tr vi zh-CN zh-TW diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index 58d381cf4..b81b67485 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -1,21 +1,21 @@ -name: Quality Check - -on: - push: - branches: - - main - pull_request: - -jobs: - quality: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - name: Set up Python 3.8 - uses: actions/setup-python@e9aba2c848f5ebd159c070c61ea2c4e2b122355e # v2 - with: - python-version: 3.8 - - name: Install Python dependencies - run: pip install black - - name: Run Quality check - run: make quality +name: Quality Check + +on: + push: + branches: + - main + pull_request: + +jobs: + quality: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - name: Set up Python 3.8 + uses: actions/setup-python@e9aba2c848f5ebd159c070c61ea2c4e2b122355e # v2 + with: + python-version: 3.8 + - name: Install Python dependencies + run: pip install black + - name: Run Quality check + run: make quality diff --git a/.github/workflows/upload_pr_documentation.yml b/.github/workflows/upload_pr_documentation.yml index 130437218..98e4c728a 100644 --- a/.github/workflows/upload_pr_documentation.yml +++ b/.github/workflows/upload_pr_documentation.yml @@ -1,17 +1,17 @@ -name: Upload PR Documentation - -on: - workflow_run: - workflows: ["Build PR Documentation"] - types: - - completed - -jobs: - build: - uses: huggingface/doc-builder/.github/workflows/upload_pr_documentation.yml@9ad2de8582b56c017cb530c1165116d40433f1c6 # main - with: - package_name: course - hub_base_path: https://moon-ci-docs.huggingface.co - secrets: - hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }} +name: Upload PR Documentation + +on: + workflow_run: + workflows: ["Build PR Documentation"] + types: + - completed + +jobs: + build: + uses: huggingface/doc-builder/.github/workflows/upload_pr_documentation.yml@9ad2de8582b56c017cb530c1165116d40433f1c6 # main + with: + package_name: course + hub_base_path: https://moon-ci-docs.huggingface.co + secrets: + hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }} comment_bot_token: ${{ secrets.COMMENT_BOT_TOKEN }} \ No newline at end of file diff --git a/.gitignore b/.gitignore index a1d21056b..87cb9bb2d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,84 +1,84 @@ -.vscode -.idea/ - -# Logs -logs -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# Runtime data -pids -*.pid -*.seed -*.pid.lock - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage - -# nyc test coverage -.nyc_output - -# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# Bower dependency directory (https://bower.io/) -bower_components - -# node-waf configuration -.lock-wscript - -# Compiled binary addons (http://nodejs.org/api/addons.html) -build/Release - -# Dependency directories -node_modules/ -jspm_packages/ - -# Typescript v1 declaration files -typings/ - -# Optional npm cache directory -.npm - -# Optional eslint cache -.eslintcache - -# Optional REPL history -.node_repl_history - -# Output of 'npm pack' -*.tgz - -# dotenv environment variables file -.env - -# gatsby files -.cache/ -public - -# Mac files -.DS_Store - -# Yarn -yarn-error.log -yarn.lock -.pnp/ -.pnp.js -# Yarn Integrity file -.yarn-integrity - -# Sylvain notes folder -notes - -# Ignore Colab notebooks -nbs/ - -# Byte-compiled -__pycache__/ -.cache/ - +.vscode +.idea/ + +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Typescript v1 declaration files +typings/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# dotenv environment variables file +.env + +# gatsby files +.cache/ +public + +# Mac files +.DS_Store + +# Yarn +yarn-error.log +yarn.lock +.pnp/ +.pnp.js +# Yarn Integrity file +.yarn-integrity + +# Sylvain notes folder +notes + +# Ignore Colab notebooks +nbs/ + +# Byte-compiled +__pycache__/ +.cache/ + diff --git a/LICENSE b/LICENSE index 261eeb9e9..29f81d812 100644 --- a/LICENSE +++ b/LICENSE @@ -1,201 +1,201 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Makefile b/Makefile index 01af2a0aa..0580a6ef7 100644 --- a/Makefile +++ b/Makefile @@ -1,9 +1,9 @@ -.PHONY: quality style - -# Check code formatting -quality: - python utils/code_formatter.py --check_only - -# Format code samples automatically and check is there are any problems left that need manual fixing -style: - python utils/code_formatter.py +.PHONY: quality style + +# Check code formatting +quality: + python utils/code_formatter.py --check_only + +# Format code samples automatically and check is there are any problems left that need manual fixing +style: + python utils/code_formatter.py diff --git a/README.md b/README.md index d26b326b1..f496c8950 100644 --- a/README.md +++ b/README.md @@ -1,183 +1,183 @@ -# The Hugging Face Course - -This repo contains the content that's used to create the **[Hugging Face course](https://huggingface.co/course/chapter1/1)**. The course teaches you about applying Transformers to various tasks in natural language processing and beyond. Along the way, you'll learn how to use the [Hugging Face](https://huggingface.co/) ecosystem — [🤗 Transformers](https://github.com/huggingface/transformers), [🤗 Datasets](https://github.com/huggingface/datasets), [🤗 Tokenizers](https://github.com/huggingface/tokenizers), and [🤗 Accelerate](https://github.com/huggingface/accelerate) — as well as the [Hugging Face Hub](https://huggingface.co/models). It's completely free and open-source! - -## 🌎 Languages and translations - -| Language | Source | Authors | -|:------------------------------------------------------------------------------|:-----------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| [English](https://huggingface.co/course/en/chapter1/1) | [`chapters/en`](https://github.com/huggingface/course/tree/main/chapters/en) | [@sgugger](https://github.com/sgugger), [@lewtun](https://github.com/lewtun), [@LysandreJik](https://github.com/LysandreJik), [@Rocketknight1](https://github.com/Rocketknight1), [@sashavor](https://github.com/sashavor), [@osanseviero](https://github.com/osanseviero), [@SaulLu](https://github.com/SaulLu), [@lvwerra](https://github.com/lvwerra) | -| [Bengali](https://huggingface.co/course/bn/chapter1/1) (WIP) | [`chapters/bn`](https://github.com/huggingface/course/tree/main/chapters/bn) | [@avishek-018](https://github.com/avishek-018), [@eNipu](https://github.com/eNipu) | -| [German](https://huggingface.co/course/de/chapter1/1) (WIP) | [`chapters/de`](https://github.com/huggingface/course/tree/main/chapters/de) | [@JesperDramsch](https://github.com/JesperDramsch), [@MarcusFra](https://github.com/MarcusFra), [@fabridamicelli](https://github.com/fabridamicelli) | -| [Spanish](https://huggingface.co/course/es/chapter1/1) (WIP) | [`chapters/es`](https://github.com/huggingface/course/tree/main/chapters/es) | [@camartinezbu](https://github.com/camartinezbu), [@munozariasjm](https://github.com/munozariasjm), [@fordaz](https://github.com/fordaz) | -| [Persian](https://huggingface.co/course/fa/chapter1/1) (WIP) | [`chapters/fa`](https://github.com/huggingface/course/tree/main/chapters/fa) | [@jowharshamshiri](https://github.com/jowharshamshiri), [@schoobani](https://github.com/schoobani) | -| [French](https://huggingface.co/course/fr/chapter1/1) | [`chapters/fr`](https://github.com/huggingface/course/tree/main/chapters/fr) | [@lbourdois](https://github.com/lbourdois), [@ChainYo](https://github.com/ChainYo), [@melaniedrevet](https://github.com/melaniedrevet), [@abdouaziz](https://github.com/abdouaziz) | -| [Gujarati](https://huggingface.co/course/gu/chapter1/1) (WIP) | [`chapters/gu`](https://github.com/huggingface/course/tree/main/chapters/gu) | [@pandyaved98](https://github.com/pandyaved98) | -| [Hebrew](https://huggingface.co/course/he/chapter1/1) (WIP) | [`chapters/he`](https://github.com/huggingface/course/tree/main/chapters/he) | [@omer-dor](https://github.com/omer-dor) | -| [Hindi](https://huggingface.co/course/hi/chapter1/1) (WIP) | [`chapters/hi`](https://github.com/huggingface/course/tree/main/chapters/hi) | [@pandyaved98](https://github.com/pandyaved98) | -| [Bahasa Indonesia](https://huggingface.co/course/id/chapter1/1) (WIP) | [`chapters/id`](https://github.com/huggingface/course/tree/main/chapters/id) | [@gstdl](https://github.com/gstdl) | -| [Italian](https://huggingface.co/course/it/chapter1/1) (WIP) | [`chapters/it`](https://github.com/huggingface/course/tree/main/chapters/it) | [@CaterinaBi](https://github.com/CaterinaBi), [@ClonedOne](https://github.com/ClonedOne), [@Nolanogenn](https://github.com/Nolanogenn), [@EdAbati](https://github.com/EdAbati), [@gdacciaro](https://github.com/gdacciaro) | -| [Japanese](https://huggingface.co/course/ja/chapter1/1) (WIP) | [`chapters/ja`](https://github.com/huggingface/course/tree/main/chapters/ja) | [@hiromu166](https://github.com/@hiromu166), [@younesbelkada](https://github.com/@younesbelkada), [@HiromuHota](https://github.com/@HiromuHota) | -| [Korean](https://huggingface.co/course/ko/chapter1/1) (WIP) | [`chapters/ko`](https://github.com/huggingface/course/tree/main/chapters/ko) | [@Doohae](https://github.com/Doohae), [@wonhyeongseo](https://github.com/wonhyeongseo), [@dlfrnaos19](https://github.com/dlfrnaos19), [@nsbg](https://github.com/nsbg) | -| [Portuguese](https://huggingface.co/course/pt/chapter1/1) (WIP) | [`chapters/pt`](https://github.com/huggingface/course/tree/main/chapters/pt) | [@johnnv1](https://github.com/johnnv1), [@victorescosta](https://github.com/victorescosta), [@LincolnVS](https://github.com/LincolnVS) | -| [Russian](https://huggingface.co/course/ru/chapter1/1) (WIP) | [`chapters/ru`](https://github.com/huggingface/course/tree/main/chapters/ru) | [@pdumin](https://github.com/pdumin), [@svv73](https://github.com/svv73), [@blademoon](https://github.com/blademoon) | -| [Telugu]( https://huggingface.co/course/te/chapter0/1 ) (WIP) | [`chapters/te`](https://github.com/huggingface/course/tree/main/chapters/te) | [@Ajey95](https://github.com/Ajey95), [@RahulKonda18](https://github.com/RahulKonda18) -| [Thai](https://huggingface.co/course/th/chapter1/1) (WIP) | [`chapters/th`](https://github.com/huggingface/course/tree/main/chapters/th) | [@peeraponw](https://github.com/peeraponw), [@a-krirk](https://github.com/a-krirk), [@jomariya23156](https://github.com/jomariya23156), [@ckingkan](https://github.com/ckingkan) | -| [Turkish](https://huggingface.co/course/tr/chapter1/1) (WIP) | [`chapters/tr`](https://github.com/huggingface/course/tree/main/chapters/tr) | [@tanersekmen](https://github.com/tanersekmen), [@mertbozkir](https://github.com/mertbozkir), [@ftarlaci](https://github.com/ftarlaci), [@akkasayaz](https://github.com/akkasayaz) | -| [Vietnamese](https://huggingface.co/course/vi/chapter1/1) | [`chapters/vi`](https://github.com/huggingface/course/tree/main/chapters/vi) | [@honghanhh](https://github.com/honghanhh) | -| [Chinese (simplified)](https://huggingface.co/course/zh-CN/chapter1/1) | [`chapters/zh-CN`](https://github.com/huggingface/course/tree/main/chapters/zh-CN) | [@zhlhyx](https://github.com/zhlhyx), [petrichor1122](https://github.com/petrichor1122), [@1375626371](https://github.com/1375626371) | -| [Chinese (traditional)](https://huggingface.co/course/zh-TW/chapter1/1) (WIP) | [`chapters/zh-TW`](https://github.com/huggingface/course/tree/main/chapters/zh-TW) | [@davidpeng86](https://github.com/davidpeng86), [@thliang01](https://github.com/thliang01) | -| [Romanian](https://huggingface.co/course/ro/chapter1/1) (WIP) | [`chapters/ro`](https://github.com/huggingface/course/tree/main/chapters/ro) | [@Sigmoid](https://github.com/SigmoidAI), [@eduard-balamatiuc](https://github.com/eduard-balamatiuc), [@FriptuLudmila](https://github.com/FriptuLudmila), [@tokyo-s](https://github.com/tokyo-s), [@hbkdesign](https://github.com/hbkdesign), [@grumpycatyo-collab](https://github.com/grumpycatyo-collab), [@Angroys](https://github.com/Angroys) | - -### Translating the course into your language - -As part of our mission to democratise machine learning, we'd love to have the course available in many more languages! Please follow the steps below if you'd like to help translate the course into your language 🙏. - -**🗞️ Open an issue** - -To get started, navigate to the [_Issues_](https://github.com/huggingface/course/issues) page of this repo and check if anyone else has opened an issue for your language. If not, open a new issue by selecting the _Translation template_ from the _New issue_ button. - -Once an issue is created, post a comment to indicate which chapters you'd like to work on and we'll add your name to the list. - -**🗣 Join our Discord** - -Since it can be difficult to discuss translation details quickly over GitHub issues, we have created dedicated channels for each language on our Discord server. If you'd like to join, follow the instructions at this channel 👉: [https://discord.gg/JfAtkvEtRb](https://discord.gg/JfAtkvEtRb) - -**🍴 Fork the repository** - -Next, you'll need to [fork this repo](https://docs.github.com/en/get-started/quickstart/fork-a-repo). You can do this by clicking on the **Fork** button on the top-right corner of this repo's page. - -Once you've forked the repo, you'll want to get the files on your local machine for editing. You can do that by cloning the fork with Git as follows: - -```bash -git clone https://github.com/YOUR-USERNAME/course -``` - -**📋 Copy-paste the English files with a new language code** - -The course files are organised under a main directory: - -* [`chapters`](https://github.com/huggingface/course/tree/main/chapters): all the text and code snippets associated with the course. - -You'll only need to copy the files in the [`chapters/en`](https://github.com/huggingface/course/tree/main/chapters/en) directory, so first navigate to your fork of the repo and run the following: - -```bash -cd ~/path/to/course -cp -r chapters/en/CHAPTER-NUMBER chapters/LANG-ID/CHAPTER-NUMBER -``` - -Here, `CHAPTER-NUMBER` refers to the chapter you'd like to work on and `LANG-ID` should be one of the ISO 639-1 or ISO 639-2 language codes -- see [here](https://www.loc.gov/standards/iso639-2/php/code_list.php) for a handy table. - -**✍️ Start translating** - -Now comes the fun part - translating the text! The first thing we recommend is translating the part of the `_toctree.yml` file that corresponds to your chapter. This file is used to render the table of contents on the website and provide the links to the Colab notebooks. The only fields you should change are the `title`, ones -- for example, here are the parts of `_toctree.yml` that we'd translate for [Chapter 0](https://huggingface.co/course/chapter0/1?fw=pt): - -```yaml -- title: 0. Setup # Translate this! - sections: - - local: chapter0/1 # Do not change this! - title: Introduction # Translate this! -``` - -> 🚨 Make sure the `_toctree.yml` file only contains the sections that have been translated! Otherwise you won't be able to build the content on the website or locally (see below how). - - -Once you have translated the `_toctree.yml` file, you can start translating the [MDX](https://mdxjs.com/) files associated with your chapter. - -> 🙋 If the `_toctree.yml` file doesn't yet exist for your language, you can simply create one by copy-pasting from the English version and deleting the sections that aren't related to your chapter. Just make sure it exists in the `chapters/LANG-ID/` directory! - -**👷‍♂️ Build the course locally** - -Once you're happy with your changes, you can preview how they'll look by first installing the [`doc-builder`](https://github.com/huggingface/doc-builder) tool that we use for building all documentation at Hugging Face: - -```bash -python -m venv .venv -source .venv/bin/activate -python -m pip install --upgrade pip -python -m pip install "git+https://github.com/huggingface/doc-builder.git" -``` - -```bash -doc-builder preview course ./chapters/LANG-ID --not_python_module -``` - -If `LANG-ID` content is partial, make sure `_toctree.yml` only references files that exist in `chapters/LANG-ID`. - -If preview starts but all routes return `404`, this might be a local `doc-builder` version mismatch between the Python package and the SvelteKit template: - -```bash -python -m pip uninstall -y hf-doc-builder -python -m pip install "git+https://github.com/huggingface/doc-builder.git" -``` - -Then restart `doc-builder preview`. - -> `preview` command does not work with Windows. - -This will build and render the course on [http://localhost:5173/](http://localhost:5173/). Although the content looks much nicer on the Hugging Face website, this step will still allow you to check that everything is formatted correctly. - -**🚀 Submit a pull request** - -If the translations look good locally, the final step is to prepare the content for a pull request. Here, the first think to check is that the files are formatted correctly. For that you can run: - -``` -pip install -r requirements.txt -make style -``` - -Once that's run, commit any changes, open a pull request, and tag [@lewtun](https://github.com/lewtun) and [@stevhliu](https://github.com/stevhliu) for a review. If you also know other native-language speakers who are able to review the translation, tag them as well for help. Congratulations, you've now completed your first translation 🥳! - -> 🚨 To build the course on the website, double-check your language code exists in `languages` field of the `build_documentation.yml` and `build_pr_documentation.yml` files in the `.github` folder. If not, just add them in their alphabetical order. - -## 📔 Jupyter notebooks - -The Jupyter notebooks containing all the code from the course are hosted on the [`huggingface/notebooks`](https://github.com/huggingface/notebooks) repo. If you wish to generate them locally, first install the required dependencies: - -```bash -python -m pip install -r requirements.txt -``` - -Then run the following script: - -```bash -python utils/generate_notebooks.py --output_dir nbs -``` - -This script extracts all the code snippets from the chapters and stores them as notebooks in the `nbs` folder (which is ignored by Git by default). - -## ✍️ Contributing a new chapter - -> Note: we are not currently accepting community contributions for new chapters. These instructions are for the Hugging Face authors. - -Adding a new chapter to the course is quite simple: - -1. Create a new directory under `chapters/en/chapterX`, where `chapterX` is the chapter you'd like to add. -2. Add numbered MDX files `sectionX.mdx` for each section. If you need to include images, place them in the [huggingface-course/documentation-images](https://huggingface.co/datasets/huggingface-course/documentation-images) repository and use the [HTML Images Syntax](https://www.w3schools.com/html/html_images.asp) with the path `https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/{langY}/{chapterX}/{your-image.png}`. -3. Update the `_toctree.yml` file to include your chapter sections -- this information will render the table of contents on the website. If your section involves both the PyTorch and TensorFlow APIs of `transformers`, make sure you include links to both Colabs in the `colab` field. - -If you get stuck, check out one of the existing chapters -- this will often show you the expected syntax. - -Once you are happy with the content, open a pull request and tag [@lewtun](https://github.com/lewtun) for a review. We recommend adding the first chapter draft as a single pull request -- the team will then provide feedback internally to iterate on the content 🤗! - -## Deploying to hf.co/course (for HF staff) - -The course content is deployed to [hf.co/course](https://huggingface.co/learn/nlp-course/chapter1/1) by triggering the [GitHub CI](.github/workflows/build_documentation.yml) from the `release` branch. To trigger the build, first create a new branch from `main` that will be used to update the current state on `release`: - -```shell -git checkout main -git checkout -b bump_release -``` - -Next, resolve any conflicts between the `release` and `bump_release` branches. Since this is tiresome to do manually, we can do the following to accept the latest changes: - -```shell -git checkout bump_release -git merge -s ours release -``` - -Next, push the `bump_release` branch and open a PR against `release` (not `main`!). Here is an example [PR](https://github.com/huggingface/course/pull/768). Once the CI is green, merge the PR and this will trigger the GitHub CI to build the new course content. This takes around 10-15 minutes, after which the latest changes will be visible on [hf.co/course](https://huggingface.co/learn/nlp-course/chapter1/1)! - - -## 🙌 Acknowledgements - -The structure of this repo and README are inspired by the wonderful [Advanced NLP with spaCy](https://github.com/ines/spacy-course) course. +# The Hugging Face Course + +This repo contains the content that's used to create the **[Hugging Face course](https://huggingface.co/course/chapter1/1)**. The course teaches you about applying Transformers to various tasks in natural language processing and beyond. Along the way, you'll learn how to use the [Hugging Face](https://huggingface.co/) ecosystem — [🤗 Transformers](https://github.com/huggingface/transformers), [🤗 Datasets](https://github.com/huggingface/datasets), [🤗 Tokenizers](https://github.com/huggingface/tokenizers), and [🤗 Accelerate](https://github.com/huggingface/accelerate) — as well as the [Hugging Face Hub](https://huggingface.co/models). It's completely free and open-source! + +## 🌎 Languages and translations + +| Language | Source | Authors | +|:------------------------------------------------------------------------------|:-----------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [English](https://huggingface.co/course/en/chapter1/1) | [`chapters/en`](https://github.com/huggingface/course/tree/main/chapters/en) | [@sgugger](https://github.com/sgugger), [@lewtun](https://github.com/lewtun), [@LysandreJik](https://github.com/LysandreJik), [@Rocketknight1](https://github.com/Rocketknight1), [@sashavor](https://github.com/sashavor), [@osanseviero](https://github.com/osanseviero), [@SaulLu](https://github.com/SaulLu), [@lvwerra](https://github.com/lvwerra) | +| [Bengali](https://huggingface.co/course/bn/chapter1/1) (WIP) | [`chapters/bn`](https://github.com/huggingface/course/tree/main/chapters/bn) | [@avishek-018](https://github.com/avishek-018), [@eNipu](https://github.com/eNipu) | +| [German](https://huggingface.co/course/de/chapter1/1) (WIP) | [`chapters/de`](https://github.com/huggingface/course/tree/main/chapters/de) | [@JesperDramsch](https://github.com/JesperDramsch), [@MarcusFra](https://github.com/MarcusFra), [@fabridamicelli](https://github.com/fabridamicelli) | +| [Spanish](https://huggingface.co/course/es/chapter1/1) (WIP) | [`chapters/es`](https://github.com/huggingface/course/tree/main/chapters/es) | [@camartinezbu](https://github.com/camartinezbu), [@munozariasjm](https://github.com/munozariasjm), [@fordaz](https://github.com/fordaz) | +| [Persian](https://huggingface.co/course/fa/chapter1/1) (WIP) | [`chapters/fa`](https://github.com/huggingface/course/tree/main/chapters/fa) | [@jowharshamshiri](https://github.com/jowharshamshiri), [@schoobani](https://github.com/schoobani) | +| [French](https://huggingface.co/course/fr/chapter1/1) | [`chapters/fr`](https://github.com/huggingface/course/tree/main/chapters/fr) | [@lbourdois](https://github.com/lbourdois), [@ChainYo](https://github.com/ChainYo), [@melaniedrevet](https://github.com/melaniedrevet), [@abdouaziz](https://github.com/abdouaziz) | +| [Gujarati](https://huggingface.co/course/gu/chapter1/1) (WIP) | [`chapters/gu`](https://github.com/huggingface/course/tree/main/chapters/gu) | [@pandyaved98](https://github.com/pandyaved98) | +| [Hebrew](https://huggingface.co/course/he/chapter1/1) (WIP) | [`chapters/he`](https://github.com/huggingface/course/tree/main/chapters/he) | [@omer-dor](https://github.com/omer-dor) | +| [Hindi](https://huggingface.co/course/hi/chapter1/1) (WIP) | [`chapters/hi`](https://github.com/huggingface/course/tree/main/chapters/hi) | [@pandyaved98](https://github.com/pandyaved98) | +| [Bahasa Indonesia](https://huggingface.co/course/id/chapter1/1) (WIP) | [`chapters/id`](https://github.com/huggingface/course/tree/main/chapters/id) | [@gstdl](https://github.com/gstdl) | +| [Italian](https://huggingface.co/course/it/chapter1/1) (WIP) | [`chapters/it`](https://github.com/huggingface/course/tree/main/chapters/it) | [@CaterinaBi](https://github.com/CaterinaBi), [@ClonedOne](https://github.com/ClonedOne), [@Nolanogenn](https://github.com/Nolanogenn), [@EdAbati](https://github.com/EdAbati), [@gdacciaro](https://github.com/gdacciaro) | +| [Japanese](https://huggingface.co/course/ja/chapter1/1) (WIP) | [`chapters/ja`](https://github.com/huggingface/course/tree/main/chapters/ja) | [@hiromu166](https://github.com/@hiromu166), [@younesbelkada](https://github.com/@younesbelkada), [@HiromuHota](https://github.com/@HiromuHota) | +| [Korean](https://huggingface.co/course/ko/chapter1/1) (WIP) | [`chapters/ko`](https://github.com/huggingface/course/tree/main/chapters/ko) | [@Doohae](https://github.com/Doohae), [@wonhyeongseo](https://github.com/wonhyeongseo), [@dlfrnaos19](https://github.com/dlfrnaos19), [@nsbg](https://github.com/nsbg) | +| [Portuguese](https://huggingface.co/course/pt/chapter1/1) (WIP) | [`chapters/pt`](https://github.com/huggingface/course/tree/main/chapters/pt) | [@johnnv1](https://github.com/johnnv1), [@victorescosta](https://github.com/victorescosta), [@LincolnVS](https://github.com/LincolnVS) | +| [Russian](https://huggingface.co/course/ru/chapter1/1) (WIP) | [`chapters/ru`](https://github.com/huggingface/course/tree/main/chapters/ru) | [@pdumin](https://github.com/pdumin), [@svv73](https://github.com/svv73), [@blademoon](https://github.com/blademoon) | +| [Telugu]( https://huggingface.co/course/te/chapter0/1 ) (WIP) | [`chapters/te`](https://github.com/huggingface/course/tree/main/chapters/te) | [@Ajey95](https://github.com/Ajey95), [@RahulKonda18](https://github.com/RahulKonda18) +| [Thai](https://huggingface.co/course/th/chapter1/1) (WIP) | [`chapters/th`](https://github.com/huggingface/course/tree/main/chapters/th) | [@peeraponw](https://github.com/peeraponw), [@a-krirk](https://github.com/a-krirk), [@jomariya23156](https://github.com/jomariya23156), [@ckingkan](https://github.com/ckingkan) | +| [Turkish](https://huggingface.co/course/tr/chapter1/1) (WIP) | [`chapters/tr`](https://github.com/huggingface/course/tree/main/chapters/tr) | [@tanersekmen](https://github.com/tanersekmen), [@mertbozkir](https://github.com/mertbozkir), [@ftarlaci](https://github.com/ftarlaci), [@akkasayaz](https://github.com/akkasayaz) | +| [Vietnamese](https://huggingface.co/course/vi/chapter1/1) | [`chapters/vi`](https://github.com/huggingface/course/tree/main/chapters/vi) | [@honghanhh](https://github.com/honghanhh) | +| [Chinese (simplified)](https://huggingface.co/course/zh-CN/chapter1/1) | [`chapters/zh-CN`](https://github.com/huggingface/course/tree/main/chapters/zh-CN) | [@zhlhyx](https://github.com/zhlhyx), [petrichor1122](https://github.com/petrichor1122), [@1375626371](https://github.com/1375626371) | +| [Chinese (traditional)](https://huggingface.co/course/zh-TW/chapter1/1) (WIP) | [`chapters/zh-TW`](https://github.com/huggingface/course/tree/main/chapters/zh-TW) | [@davidpeng86](https://github.com/davidpeng86), [@thliang01](https://github.com/thliang01) | +| [Romanian](https://huggingface.co/course/ro/chapter1/1) (WIP) | [`chapters/ro`](https://github.com/huggingface/course/tree/main/chapters/ro) | [@Sigmoid](https://github.com/SigmoidAI), [@eduard-balamatiuc](https://github.com/eduard-balamatiuc), [@FriptuLudmila](https://github.com/FriptuLudmila), [@tokyo-s](https://github.com/tokyo-s), [@hbkdesign](https://github.com/hbkdesign), [@grumpycatyo-collab](https://github.com/grumpycatyo-collab), [@Angroys](https://github.com/Angroys) | + +### Translating the course into your language + +As part of our mission to democratise machine learning, we'd love to have the course available in many more languages! Please follow the steps below if you'd like to help translate the course into your language 🙏. + +**🗞️ Open an issue** + +To get started, navigate to the [_Issues_](https://github.com/huggingface/course/issues) page of this repo and check if anyone else has opened an issue for your language. If not, open a new issue by selecting the _Translation template_ from the _New issue_ button. + +Once an issue is created, post a comment to indicate which chapters you'd like to work on and we'll add your name to the list. + +**🗣 Join our Discord** + +Since it can be difficult to discuss translation details quickly over GitHub issues, we have created dedicated channels for each language on our Discord server. If you'd like to join, follow the instructions at this channel 👉: [https://discord.gg/JfAtkvEtRb](https://discord.gg/JfAtkvEtRb) + +**🍴 Fork the repository** + +Next, you'll need to [fork this repo](https://docs.github.com/en/get-started/quickstart/fork-a-repo). You can do this by clicking on the **Fork** button on the top-right corner of this repo's page. + +Once you've forked the repo, you'll want to get the files on your local machine for editing. You can do that by cloning the fork with Git as follows: + +```bash +git clone https://github.com/YOUR-USERNAME/course +``` + +**📋 Copy-paste the English files with a new language code** + +The course files are organised under a main directory: + +* [`chapters`](https://github.com/huggingface/course/tree/main/chapters): all the text and code snippets associated with the course. + +You'll only need to copy the files in the [`chapters/en`](https://github.com/huggingface/course/tree/main/chapters/en) directory, so first navigate to your fork of the repo and run the following: + +```bash +cd ~/path/to/course +cp -r chapters/en/CHAPTER-NUMBER chapters/LANG-ID/CHAPTER-NUMBER +``` + +Here, `CHAPTER-NUMBER` refers to the chapter you'd like to work on and `LANG-ID` should be one of the ISO 639-1 or ISO 639-2 language codes -- see [here](https://www.loc.gov/standards/iso639-2/php/code_list.php) for a handy table. + +**✍️ Start translating** + +Now comes the fun part - translating the text! The first thing we recommend is translating the part of the `_toctree.yml` file that corresponds to your chapter. This file is used to render the table of contents on the website and provide the links to the Colab notebooks. The only fields you should change are the `title`, ones -- for example, here are the parts of `_toctree.yml` that we'd translate for [Chapter 0](https://huggingface.co/course/chapter0/1?fw=pt): + +```yaml +- title: 0. Setup # Translate this! + sections: + - local: chapter0/1 # Do not change this! + title: Introduction # Translate this! +``` + +> 🚨 Make sure the `_toctree.yml` file only contains the sections that have been translated! Otherwise you won't be able to build the content on the website or locally (see below how). + + +Once you have translated the `_toctree.yml` file, you can start translating the [MDX](https://mdxjs.com/) files associated with your chapter. + +> 🙋 If the `_toctree.yml` file doesn't yet exist for your language, you can simply create one by copy-pasting from the English version and deleting the sections that aren't related to your chapter. Just make sure it exists in the `chapters/LANG-ID/` directory! + +**👷‍♂️ Build the course locally** + +Once you're happy with your changes, you can preview how they'll look by first installing the [`doc-builder`](https://github.com/huggingface/doc-builder) tool that we use for building all documentation at Hugging Face: + +```bash +python -m venv .venv +source .venv/bin/activate +python -m pip install --upgrade pip +python -m pip install "git+https://github.com/huggingface/doc-builder.git" +``` + +```bash +doc-builder preview course ./chapters/LANG-ID --not_python_module +``` + +If `LANG-ID` content is partial, make sure `_toctree.yml` only references files that exist in `chapters/LANG-ID`. + +If preview starts but all routes return `404`, this might be a local `doc-builder` version mismatch between the Python package and the SvelteKit template: + +```bash +python -m pip uninstall -y hf-doc-builder +python -m pip install "git+https://github.com/huggingface/doc-builder.git" +``` + +Then restart `doc-builder preview`. + +> `preview` command does not work with Windows. + +This will build and render the course on [http://localhost:5173/](http://localhost:5173/). Although the content looks much nicer on the Hugging Face website, this step will still allow you to check that everything is formatted correctly. + +**🚀 Submit a pull request** + +If the translations look good locally, the final step is to prepare the content for a pull request. Here, the first think to check is that the files are formatted correctly. For that you can run: + +``` +pip install -r requirements.txt +make style +``` + +Once that's run, commit any changes, open a pull request, and tag [@lewtun](https://github.com/lewtun) and [@stevhliu](https://github.com/stevhliu) for a review. If you also know other native-language speakers who are able to review the translation, tag them as well for help. Congratulations, you've now completed your first translation 🥳! + +> 🚨 To build the course on the website, double-check your language code exists in `languages` field of the `build_documentation.yml` and `build_pr_documentation.yml` files in the `.github` folder. If not, just add them in their alphabetical order. + +## 📔 Jupyter notebooks + +The Jupyter notebooks containing all the code from the course are hosted on the [`huggingface/notebooks`](https://github.com/huggingface/notebooks) repo. If you wish to generate them locally, first install the required dependencies: + +```bash +python -m pip install -r requirements.txt +``` + +Then run the following script: + +```bash +python utils/generate_notebooks.py --output_dir nbs +``` + +This script extracts all the code snippets from the chapters and stores them as notebooks in the `nbs` folder (which is ignored by Git by default). + +## ✍️ Contributing a new chapter + +> Note: we are not currently accepting community contributions for new chapters. These instructions are for the Hugging Face authors. + +Adding a new chapter to the course is quite simple: + +1. Create a new directory under `chapters/en/chapterX`, where `chapterX` is the chapter you'd like to add. +2. Add numbered MDX files `sectionX.mdx` for each section. If you need to include images, place them in the [huggingface-course/documentation-images](https://huggingface.co/datasets/huggingface-course/documentation-images) repository and use the [HTML Images Syntax](https://www.w3schools.com/html/html_images.asp) with the path `https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/{langY}/{chapterX}/{your-image.png}`. +3. Update the `_toctree.yml` file to include your chapter sections -- this information will render the table of contents on the website. If your section involves both the PyTorch and TensorFlow APIs of `transformers`, make sure you include links to both Colabs in the `colab` field. + +If you get stuck, check out one of the existing chapters -- this will often show you the expected syntax. + +Once you are happy with the content, open a pull request and tag [@lewtun](https://github.com/lewtun) for a review. We recommend adding the first chapter draft as a single pull request -- the team will then provide feedback internally to iterate on the content 🤗! + +## Deploying to hf.co/course (for HF staff) + +The course content is deployed to [hf.co/course](https://huggingface.co/learn/nlp-course/chapter1/1) by triggering the [GitHub CI](.github/workflows/build_documentation.yml) from the `release` branch. To trigger the build, first create a new branch from `main` that will be used to update the current state on `release`: + +```shell +git checkout main +git checkout -b bump_release +``` + +Next, resolve any conflicts between the `release` and `bump_release` branches. Since this is tiresome to do manually, we can do the following to accept the latest changes: + +```shell +git checkout bump_release +git merge -s ours release +``` + +Next, push the `bump_release` branch and open a PR against `release` (not `main`!). Here is an example [PR](https://github.com/huggingface/course/pull/768). Once the CI is green, merge the PR and this will trigger the GitHub CI to build the new course content. This takes around 10-15 minutes, after which the latest changes will be visible on [hf.co/course](https://huggingface.co/learn/nlp-course/chapter1/1)! + + +## 🙌 Acknowledgements + +The structure of this repo and README are inspired by the wonderful [Advanced NLP with spaCy](https://github.com/ines/spacy-course) course. diff --git a/chapters/ar/_toctree.yml b/chapters/ar/_toctree.yml index b9e6467fd..93385b8dd 100644 --- a/chapters/ar/_toctree.yml +++ b/chapters/ar/_toctree.yml @@ -1,4 +1,4 @@ -- title: 0.الإعداد - sections: - - local: chapter0/1 - title: مقدمة +- title: 0.الإعداد + sections: + - local: chapter0/1 + title: مقدمة diff --git a/chapters/ar/chapter0/1.mdx b/chapters/ar/chapter0/1.mdx index 8cec15b6e..0dfcd1237 100644 --- a/chapters/ar/chapter0/1.mdx +++ b/chapters/ar/chapter0/1.mdx @@ -1,136 +1,136 @@ -
- -# مقدمة - -مرحبًا بك في دورة Hugging Face! ستساعدك هذه المقدمة خلال إعداد بيئة العمل. إذا كنت قد بدأت الدورة للتو، فننصحك أولاً بإلقاء نظرة على [الفصل 1](/course/chapter1)، ثم العودة وإعداد بيئتك حتى تتمكن من تجربة الكود بنفسك. - -تتوفر جميع المكتبات التي سنستخدمها في هذه الدورة التدريبية على شكل حزم (Package) Python، لذلك سنوضح لك هنا كيفية إعداد بيئة Python وتثبيت المكتبات المحددة التي ستحتاج إليها. - -سنغطي طريقتين لإعداد بيئة العمل الخاصة بك، باستخدام دفتر Colab أو بيئة Python الافتراضية. لا تتردد في اختيار البيئة التي تناسبك أكثر.نوصي المبتدئين بشدة أن يبدأوا باستخدام دفتر Colab. - -لاحظ أننا لن نغطي نظام Windows. إذا كنت تعمل على نظام Windows، فإننا نوصي بمتابعة استخدام دفتر Colab. إذا كنت تستخدم توزيعة Linux أو macOS، فيمكنك استخدام أي من الطريقتين الموضحتين هنا. - -تعتمد معظم الدورة على امتلاكك لحساب Hugging Face. نوصي بإنشاء حساب الآن: [إنشاء حساب](https://huggingface.co/join). - -## استخدام دفتر Google Colab - -يعد استخدام دفتر Colab أبسط إعداد ممكن؛ فقط قم بتشغيل دفتر Colab في متصفحك ابدأ مباشرة بالبرمجة! - -إذا لم تكن معتادًا على Colab، نوصيك بالبدء باتباع [المقدمة](https://colab.research.google.com/notebooks/intro.ipynb). يتيح لك Colab استخدام بعض أجهزة التسريع، مثل GPUs أو TPUs، وهو مجاني في حال تشغيل مهمات خفيفة. - -بمجرد أن تشعر بالأريحية في التنقل في Colab، أنشئ دفتر ملاحظات جديدًا وابدأ في الإعداد: - -
-An empty colab notebook -
- -الخطوة التالية هي تثبيت المكتبات التي سنستخدمها في هذه الدورة. سنستخدم `pip` للتثبيت، وهو مدير الحزم لPython. حتى تتمكن من تثبيت مكتبة 🤗 Transformers يمكنك تشغيل أوامر النظام عن طريق تسبقها بالحرف `!` في دفتر Colab, على النحو التالي: - -
- -``` -!pip install transformers -``` - -
-يمكنك التأكد من تثبيت الحزمة بشكل صحيح عن طريق استيرادها (import) خلال وقت تشغيل Python: -
- -``` -import transformers -``` - -
-A gif showing the result of the two commands above: installation and import -
- -
-هذا يثبت نسخة خفيفة جدا من مكتبة 🤗 Transformers. أي أنه لم يتم تثبيت أي إطارات عمل محددة للتعلم الآلي (مثل PyTorch أو TensorFlow). نوصي بتثبيت "إصدار التطوير" للمكتبة لأننا سوف نستخدم الكثير من الميزات المختلفة, و هذا الإصدار يأتي مع جميع التبعيات المطلوبة تقريباً لأي حالة استخدام يمكن تخيلها: - -
- -``` -!pip install transformers[sentencepiece] -``` - -
-سيستغرق هذا بعض الوقت، لكنك ستكون جاهزًا بعد ذلك لبقية الدورة! - -## استخدام بيئة Python افتراضية - -إذا كنت تفضل استخدام بيئة Python الافتراضية، فإن الخطوة الأولى هي تثبيت Python على نظامك. للبدء, نوصي باتباع [دليل الإرشادات هذا](https://realpython.com/installing-python/). - -بمجرد تثبيت Python، يجب أن تكون قادرًا على تشغيل أوامر Python في الجهاز المستخدم. للتأكد من تثبيته بشكل صحيح قبل المتابعة إلى الخطوات التالية يمكنك البدء بتشغيل الأمر التالي: `python --version`. يجب أن يطبع هذا إصدار Python المتاح الآن على نظامك. - -عند تشغيل أمر Python في الجهاز المستخدم، مثل `python --version`، يجب أن تفكر في البرنامج الذي يقوم بتشغيل الأمر الخاص بك باعتباره Python "الرئيسي" على نظامك. نوصي بالحفاظ على هذا التثبيت الرئيسي خاليًا من أي حزم، واستخدامه لإنشاء بيئات منفصلة لكل تطبيق تعمل عليه, وبهذه الطريقة، يمكن لكل تطبيق أن يكون له تبعيات وحزم خاصة به، ولن تقلق بشأن مشكلات التوافق المحتملة مع تطبيقات أخرى. - -في Python، يتم ذلك باستخدام [* البيئات الافتراضية *](https://docs.python.org/3/tutorial/venv.html)، وهي عبارة عن تفرعات من المجلدات كل منها قائم بحد ذاته, ويحتوي كل منها على Python مثبت بإصدار معين بالإضافة إلى جميع الحزم التي يحتاجها التطبيق. يمكن إنشاء مثل هذه البيئة الافتراضية باستخدام عدد من الأدوات المختلفة ، لكننا سنستخدم حزمة Python الرسمية لهذا الغرض، والتي تسمى [`venv`](https://docs.python.org/3/library/venv.html#module-venv). - -أولاً، قم بإنشاء المجلد الذي تريد أن يتواجد فيه التطبيق الخاص بك -على سبيل المثال، قد ترغب في إنشاء مجلد جديد يسمى *transformers-course* في المجلد الرئيسي للدورة: -
- -``` -mkdir ~/transformers-course -cd ~/transformers-course -``` - -
- -من داخل هذا المجلد، أنشئ بيئة افتراضية باستخدام وحدة Python `venv`: - -
- -``` -python -m venv .env -``` - -
-يجب أن يكون لديك الآن مجلد يسمى *.env* في المجلد الفارغ الخاص بك: -
- -``` -ls -a -``` - -```out -. .. .env -``` - -
-يمكنك الدخول والخروج من بيئتك الافتراضية باستخدام أوامر "التنشيط" و "إلغاء التنشيط": -
- -``` -# Activate the virtual environment -source .env/bin/activate - -# Deactivate the virtual environment -deactivate -``` - -
-يمكنك التأكد من تنشيط البيئة عن طريق تشغيل الأمر `which python`: إذا كان يشير إلى البيئة الافتراضية، فقد قمت بتنشيطها بنجاح! -
- -``` -which python -``` - -```out -/home//transformers-course/.env/bin/python -``` - -
- -### تثبيت التبعيات - -كما في القسم السابق حول استخدام مثيلات Google Colab، ستحتاج الآن إلى تثبيت الحزم المطلوبة للمتابعة. مرة أخرى، يمكنك تثبيت إصدار التطوير من 🤗 Transformers باستخدام مدير الحزم `pip`: -
- -``` -pip install "transformers[sentencepiece]" -``` - -
-أنت الآن جاهز تمامًا للانطلاق! -
+
+ +# مقدمة + +مرحبًا بك في دورة Hugging Face! ستساعدك هذه المقدمة خلال إعداد بيئة العمل. إذا كنت قد بدأت الدورة للتو، فننصحك أولاً بإلقاء نظرة على [الفصل 1](/course/chapter1)، ثم العودة وإعداد بيئتك حتى تتمكن من تجربة الكود بنفسك. + +تتوفر جميع المكتبات التي سنستخدمها في هذه الدورة التدريبية على شكل حزم (Package) Python، لذلك سنوضح لك هنا كيفية إعداد بيئة Python وتثبيت المكتبات المحددة التي ستحتاج إليها. + +سنغطي طريقتين لإعداد بيئة العمل الخاصة بك، باستخدام دفتر Colab أو بيئة Python الافتراضية. لا تتردد في اختيار البيئة التي تناسبك أكثر.نوصي المبتدئين بشدة أن يبدأوا باستخدام دفتر Colab. + +لاحظ أننا لن نغطي نظام Windows. إذا كنت تعمل على نظام Windows، فإننا نوصي بمتابعة استخدام دفتر Colab. إذا كنت تستخدم توزيعة Linux أو macOS، فيمكنك استخدام أي من الطريقتين الموضحتين هنا. + +تعتمد معظم الدورة على امتلاكك لحساب Hugging Face. نوصي بإنشاء حساب الآن: [إنشاء حساب](https://huggingface.co/join). + +## استخدام دفتر Google Colab + +يعد استخدام دفتر Colab أبسط إعداد ممكن؛ فقط قم بتشغيل دفتر Colab في متصفحك ابدأ مباشرة بالبرمجة! + +إذا لم تكن معتادًا على Colab، نوصيك بالبدء باتباع [المقدمة](https://colab.research.google.com/notebooks/intro.ipynb). يتيح لك Colab استخدام بعض أجهزة التسريع، مثل GPUs أو TPUs، وهو مجاني في حال تشغيل مهمات خفيفة. + +بمجرد أن تشعر بالأريحية في التنقل في Colab، أنشئ دفتر ملاحظات جديدًا وابدأ في الإعداد: + +
+An empty colab notebook +
+ +الخطوة التالية هي تثبيت المكتبات التي سنستخدمها في هذه الدورة. سنستخدم `pip` للتثبيت، وهو مدير الحزم لPython. حتى تتمكن من تثبيت مكتبة 🤗 Transformers يمكنك تشغيل أوامر النظام عن طريق تسبقها بالحرف `!` في دفتر Colab, على النحو التالي: + +
+ +``` +!pip install transformers +``` + +
+يمكنك التأكد من تثبيت الحزمة بشكل صحيح عن طريق استيرادها (import) خلال وقت تشغيل Python: +
+ +``` +import transformers +``` + +
+A gif showing the result of the two commands above: installation and import +
+ +
+هذا يثبت نسخة خفيفة جدا من مكتبة 🤗 Transformers. أي أنه لم يتم تثبيت أي إطارات عمل محددة للتعلم الآلي (مثل PyTorch أو TensorFlow). نوصي بتثبيت "إصدار التطوير" للمكتبة لأننا سوف نستخدم الكثير من الميزات المختلفة, و هذا الإصدار يأتي مع جميع التبعيات المطلوبة تقريباً لأي حالة استخدام يمكن تخيلها: + +
+ +``` +!pip install transformers[sentencepiece] +``` + +
+سيستغرق هذا بعض الوقت، لكنك ستكون جاهزًا بعد ذلك لبقية الدورة! + +## استخدام بيئة Python افتراضية + +إذا كنت تفضل استخدام بيئة Python الافتراضية، فإن الخطوة الأولى هي تثبيت Python على نظامك. للبدء, نوصي باتباع [دليل الإرشادات هذا](https://realpython.com/installing-python/). + +بمجرد تثبيت Python، يجب أن تكون قادرًا على تشغيل أوامر Python في الجهاز المستخدم. للتأكد من تثبيته بشكل صحيح قبل المتابعة إلى الخطوات التالية يمكنك البدء بتشغيل الأمر التالي: `python --version`. يجب أن يطبع هذا إصدار Python المتاح الآن على نظامك. + +عند تشغيل أمر Python في الجهاز المستخدم، مثل `python --version`، يجب أن تفكر في البرنامج الذي يقوم بتشغيل الأمر الخاص بك باعتباره Python "الرئيسي" على نظامك. نوصي بالحفاظ على هذا التثبيت الرئيسي خاليًا من أي حزم، واستخدامه لإنشاء بيئات منفصلة لكل تطبيق تعمل عليه, وبهذه الطريقة، يمكن لكل تطبيق أن يكون له تبعيات وحزم خاصة به، ولن تقلق بشأن مشكلات التوافق المحتملة مع تطبيقات أخرى. + +في Python، يتم ذلك باستخدام [* البيئات الافتراضية *](https://docs.python.org/3/tutorial/venv.html)، وهي عبارة عن تفرعات من المجلدات كل منها قائم بحد ذاته, ويحتوي كل منها على Python مثبت بإصدار معين بالإضافة إلى جميع الحزم التي يحتاجها التطبيق. يمكن إنشاء مثل هذه البيئة الافتراضية باستخدام عدد من الأدوات المختلفة ، لكننا سنستخدم حزمة Python الرسمية لهذا الغرض، والتي تسمى [`venv`](https://docs.python.org/3/library/venv.html#module-venv). + +أولاً، قم بإنشاء المجلد الذي تريد أن يتواجد فيه التطبيق الخاص بك -على سبيل المثال، قد ترغب في إنشاء مجلد جديد يسمى *transformers-course* في المجلد الرئيسي للدورة: +
+ +``` +mkdir ~/transformers-course +cd ~/transformers-course +``` + +
+ +من داخل هذا المجلد، أنشئ بيئة افتراضية باستخدام وحدة Python `venv`: + +
+ +``` +python -m venv .env +``` + +
+يجب أن يكون لديك الآن مجلد يسمى *.env* في المجلد الفارغ الخاص بك: +
+ +``` +ls -a +``` + +```out +. .. .env +``` + +
+يمكنك الدخول والخروج من بيئتك الافتراضية باستخدام أوامر "التنشيط" و "إلغاء التنشيط": +
+ +``` +# Activate the virtual environment +source .env/bin/activate + +# Deactivate the virtual environment +deactivate +``` + +
+يمكنك التأكد من تنشيط البيئة عن طريق تشغيل الأمر `which python`: إذا كان يشير إلى البيئة الافتراضية، فقد قمت بتنشيطها بنجاح! +
+ +``` +which python +``` + +```out +/home//transformers-course/.env/bin/python +``` + +
+ +### تثبيت التبعيات + +كما في القسم السابق حول استخدام مثيلات Google Colab، ستحتاج الآن إلى تثبيت الحزم المطلوبة للمتابعة. مرة أخرى، يمكنك تثبيت إصدار التطوير من 🤗 Transformers باستخدام مدير الحزم `pip`: +
+ +``` +pip install "transformers[sentencepiece]" +``` + +
+أنت الآن جاهز تمامًا للانطلاق! +
diff --git a/chapters/bn/_toctree.yml b/chapters/bn/_toctree.yml index 30d73183a..18c2d0020 100644 --- a/chapters/bn/_toctree.yml +++ b/chapters/bn/_toctree.yml @@ -1,14 +1,14 @@ -- title: 0. সেটআপ - sections: - - local: chapter0/1 - title: ভূমিকা - -- title: 1. ট্রান্সফরমার মডেল - sections: - - local: chapter1/1 - title: ভূমিকা - -- title: 2. 🤗Transformers এর ব্যবহার - sections: - - local: chapter2/1 +- title: 0. সেটআপ + sections: + - local: chapter0/1 + title: ভূমিকা + +- title: 1. ট্রান্সফরমার মডেল + sections: + - local: chapter1/1 + title: ভূমিকা + +- title: 2. 🤗Transformers এর ব্যবহার + sections: + - local: chapter2/1 title: ভূমিকা \ No newline at end of file diff --git a/chapters/bn/chapter0/1.mdx b/chapters/bn/chapter0/1.mdx index 9235ad8a3..c2ab18dff 100644 --- a/chapters/bn/chapter0/1.mdx +++ b/chapters/bn/chapter0/1.mdx @@ -1,112 +1,112 @@ -# ভূমিকা - -হাগিং ফেস কোর্সে স্বাগতম! এই অধ্যায়টি একটি "ওয়ার্কিং এনভায়রনমেন্ট" সেট আপ করতে আপনাকে গাইড করবে। আপনি যদি এইপ্রথম কোর্সটি শুরু করে থাকেন, আমরা আপনাকে প্রথমে [অধ্যায় 1](/course/chapter1) একবার দেখে পড়ে আসার পরামর্শ দিচ্ছি, ফিরে এসে "ওয়ার্কিং এনভায়রনমেন্ট" সেট আপ করুন যাতে আপনি নিজেই কোডটি চেষ্টা করতে পারেন। - -এই কোর্সে আমরা যে সমস্ত লাইব্রেরিগুলি ব্যবহার করব সেগুলি পাইথন প্যাকেজ হিসাবে পাওয়া যাবে, তাই এখানে আমরা আপনাকে দেখাব কিভাবে একটি পাইথন এনভায়রনমেন্ট সেট আপ করতে হয় এবং আপনার প্রয়োজনীয় নির্দিষ্ট লাইব্রেরিগুলি ইনস্টল করতে হয়৷ - -Colab নোটবুক বা পাইথন virtual environment ব্যবহার করে আমরা "ওয়ার্কিং এনভায়রনমেন্ট" সেট-আপ করার দুটি উপায় কভার করব। যে পদ্ধতিটি আপনার কাছে সহজ সেটি আপনি বেছে নিতে পাড়েন। যারা নতুন শুরু করছেন তাদের জন্য আমরা Colab নোটবুক ব্যবহার করে শুরু করতে জোরালোভাবে রিকমেন্ড করি। - -মনে রাখবেন যে এখানে উইন্ডোজ সিস্টেম কভার করা হবে না। আপনি যদি উইন্ডোজ চালান, তাহলে আমরা Colab নোটবুক ব্যবহার করে ফলো করার পরামর্শ দিচ্ছি। আর আপনি যদি লিনাক্স ডিস্ট্রিবিউশন বা ম্যাকওএস ব্যবহার করেন তবে এখানে বর্ণিত পদ্ধতির যেকোনো একটি ব্যবহার করতে পারেন। - -কোর্সের অনেকটাই হাগিং ফেস অ্যাকাউন্ট উপর নির্ভর করবে। তাই আমরা একটি একাউন্ট ওপেন করার করার পরামর্শ দিচ্ছি: [একটি অ্যাকাউন্ট তৈরি করুন](https://huggingface.co/join)। - -## Google Colab নোটবুক ব্যবহার করার পদ্ধতি - -Colab নোটবুক ব্যবহার করার সবচেয়ে সহজ সেটআপ হচ্ছে ব্রাউজারে একটি নোটবুক ওপেন করুন এবং সরাসরি কোডিং এ যান! - -আপনি যদি Colab-এর সাথে পরিচিত না হন তাহলে আমরা আপনাকে [Colab পরিচয়](https://colab.research.google.com/notebooks/intro.ipynb) অনুসরণ করে শুরু করার পরামর্শ দিচ্ছি। Colab আপনাকে কিছু এক্সেলারেসন হার্ডওয়্যার ব্যবহার করতে দেয়, যেমন GPUs বা TPUs যা ছোট ওয়ার্ক লোডের জন্য ফ্রি। - -Colab-এর উপর আপানার হাত চলে আসলে একটি নতুন নোটবুক ওপেন করে সেট-আপ শুরু করুন: - -
-An empty colab notebook -
- -পরবর্তী ধাপে আমরা এই কোর্সে ব্যবহার হবে এমন লাইব্রেরিগুলি ইনস্টল করা দেখাবো। আমরা ইনস্টলেশনের জন্য পাইথনের প্যাকেজ ম্যানেজার `pip` ব্যবহার করব। নোটবুকগুলিতে, আপনি `!` অক্ষর দিয়ে আগে সিস্টেম কমান্ড চালাতে পারবেন। যেমন ধরুন, নিচের কমান্ডটি দিয়ে 🤗 Transformers লাইব্রেরি ইনস্টল করতে পারবেন: - -``` -!pip install transformers -``` - -প্যাকেজটি আপনার পাইথন রানটাইমের মধ্যে সঠিকভাবে ইনস্টল করা হয়েছে কিনা তা import করে নিশ্চিত হতে পাড়েন। - -``` -import transformers -``` - -
-একটি gif উপরের দুটি কমান্ডের ফলাফল দেখাচ্ছে: installation and import -
- -এটি 🤗 ট্রান্সফরমারের একটি খুব লাইট ভার্সন ইনস্টল করে। বিশেষ করে, যদিনা নির্দিষ্ট মেশিন লার্নিং ফ্রেমওয়ার্ক (যেমন PyTorch বা TensorFlow) ইনস্টল করা থাকে। যেহেতু আমরা লাইব্রেরির বিভিন্ন ফিচার ব্যবহার করব, তাই আমরা ডেভেলপমেন্ট ভার্সন ইনস্টল করার পরামর্শ দিচ্ছি, যতে ধারানা করার এমন সব ইউজ কেসে কাজ করবে: - -``` -!pip install transformers[sentencepiece] -``` - -ইনস্টল হতে কিছুটা সময় লাগবে, কিন্তু এরপর আপনি বাকি কোর্সের জন্য প্রস্তুত হয়ে যাবেন! - -## একটি পাইথন virtual environment ব্যবহার করা - -আপনি যদি পাইথন virtual environment ব্যবহার করতে পছন্দ করেন, প্রথম ধাপ হল আপনার সিস্টেমে পাইথন ইনস্টল করা। শুরু করার জন্য আমরা [এই নির্দেশিকা](https://realpython.com/installing-python/) অনুসরণ করার পরামর্শ দিচ্ছি। - -একবার আপনি পাইথন ইনস্টল করলে, আপনি আপনার টার্মিনালে পাইথন কমান্ড চালাতে সক্ষম হবেন। পরবর্তী ধাপে যাওয়ার আগে এটি সঠিকভাবে ইনস্টল করা হয়েছে তা নিশ্চিত করতে আপনি নিম্নলিখিত কমান্ডটি চালিয়ে শুরু করতে পারেন: `python --version`। এটি আপনার সিস্টেমে ইনস্টল হওয়া পাইথন সংস্করণটি প্রিন্ট করা উচিত। - -আপনার টার্মিনালে পাইথন কমান্ড চালানোর সময়, যেমন `python --version`, আপানাকে ভাবতে হবে যে এটি "main" পাইথন প্রোগ্রাম যা আপানার কমান্ড টিকে রান করছে। আমরা এই মূল ইনস্টলেশনটিকে যেকোন প্যাকেজ ইনস্টল থেকে মুক্ত রাখার সুপারিশ করি। এ আপনি যখন আলাদা অ্যাপ্লিকেশনে কাজ করবেন তখন তার জন্য আলাদা virtual environment তৈরি করতে এই পাইথন ইনস্টলেশনটিকে ব্যবহার করবেন। এতে করে প্রতিটি অ্যাপ্লিকেশনের নিজস্ব ডিপেন্ডেন্সি এবং প্যাকেজ আলাদা থাকবে এবং অন্যান্য অ্যাপ্লিকেশনের সাথে এর সম্ভাব্য কম্পাটিবিলটি নিয়ে আপানকে সমস্যায় করতে হবে না। - -পাইথনে এটি [*virtual environments*](https://docs.python.org/3/tutorial/venv.html) দিয়ে করা হয়, যেটি স্বয়ংসম্পূর্ণ ডিরেক্টরি ট্রি। যার প্রত্যেকটিতে এপ্লিকেশনের প্রয়োজনীয় সমস্ত প্যাকেজের পাশাপাশি একটি নির্দিষ্ট পাইথন ভার্শনের পাইথন ইনস্টলেশন আছে। এই ধরনের একটি virtual environments বিভিন্ন ভাবে তৈরি করা যেতে পারে। তবে আমরা এর জন্য অফিসিয়াল পাইথন প্যাকেজ ব্যবহার করব, যাকে বলা হয় [`venv`](https://docs.python.org/3/library) /venv.html#module-venv)। - -প্রথমে, আপনি যে ডিরেক্টরিটি আপনার অ্যাপ্লিকেশনটিতে রাখতে চান তা তৈরি করুন — উদাহরণস্বরূপ, আপনি আপনার হোম ডিরেক্টরির বা ফোল্ডার ভেতর *transformers-course* নামে একটি নতুন ডিরেক্টরি তৈরি করতে চাইতে পারেন: - -``` -mkdir ~/transformers-course -cd ~/transformers-course -``` - -এই ডিরেক্টরির ভিতর থেকে, পাইথন `venv` মডিউল ব্যবহার করে একটি virtual environment তৈরি করুন: - -``` -python -m venv .env -``` - -আপনার এখন *.env* নামে একটি ফোল্ডার থাকা উচিত, অন্যথায় খালি ফোল্ডার : - -``` -ls -a -``` - -```out -. .. .env -``` - - -আপনি এখন virtual environment টি `activate` করতে বা `deactivate` নিচের কমান্ড গুলো ব্যবহার করতে পারেন। - -``` -# virtual environment টি activate করার কমান্ড -source .env/bin/activate - -# virtual environment টি deactivate করার কমান্ড -deactivate -``` - -`which python` কমান্ড চালিয়ে নিশ্চিত করতে পারেন যে virtual environment টি activate হয়েছে কিনা। -যদি এটি virtual environment টি কে পয়েন্ট করে করে, তাহলে আপনি সফলভাবে এটি সক্রিয় করেছেন! - -``` -which python -``` - -```out -/home//transformers-course/.env/bin/python -``` - -### ডিপেন্ডেন্সি ইনস্টল করা - -আগের সেকশনে Google Colab এ যেভাবে প্যাকেজ ইনস্টল করা হয়েছে একই ভাবে এখানেও `pip` প্যাকেজ ম্যানেজার ব্যবহার করে 🤗 Transformer এর development সংস্করণ ইনস্টল করতে পারেন: - -```` -pip install "transformers[sentencepiece]" -```` - -আপনি এখন শুরু করা জন্য সম্পূর্ণ প্রস্তুত! +# ভূমিকা + +হাগিং ফেস কোর্সে স্বাগতম! এই অধ্যায়টি একটি "ওয়ার্কিং এনভায়রনমেন্ট" সেট আপ করতে আপনাকে গাইড করবে। আপনি যদি এইপ্রথম কোর্সটি শুরু করে থাকেন, আমরা আপনাকে প্রথমে [অধ্যায় 1](/course/chapter1) একবার দেখে পড়ে আসার পরামর্শ দিচ্ছি, ফিরে এসে "ওয়ার্কিং এনভায়রনমেন্ট" সেট আপ করুন যাতে আপনি নিজেই কোডটি চেষ্টা করতে পারেন। + +এই কোর্সে আমরা যে সমস্ত লাইব্রেরিগুলি ব্যবহার করব সেগুলি পাইথন প্যাকেজ হিসাবে পাওয়া যাবে, তাই এখানে আমরা আপনাকে দেখাব কিভাবে একটি পাইথন এনভায়রনমেন্ট সেট আপ করতে হয় এবং আপনার প্রয়োজনীয় নির্দিষ্ট লাইব্রেরিগুলি ইনস্টল করতে হয়৷ + +Colab নোটবুক বা পাইথন virtual environment ব্যবহার করে আমরা "ওয়ার্কিং এনভায়রনমেন্ট" সেট-আপ করার দুটি উপায় কভার করব। যে পদ্ধতিটি আপনার কাছে সহজ সেটি আপনি বেছে নিতে পাড়েন। যারা নতুন শুরু করছেন তাদের জন্য আমরা Colab নোটবুক ব্যবহার করে শুরু করতে জোরালোভাবে রিকমেন্ড করি। + +মনে রাখবেন যে এখানে উইন্ডোজ সিস্টেম কভার করা হবে না। আপনি যদি উইন্ডোজ চালান, তাহলে আমরা Colab নোটবুক ব্যবহার করে ফলো করার পরামর্শ দিচ্ছি। আর আপনি যদি লিনাক্স ডিস্ট্রিবিউশন বা ম্যাকওএস ব্যবহার করেন তবে এখানে বর্ণিত পদ্ধতির যেকোনো একটি ব্যবহার করতে পারেন। + +কোর্সের অনেকটাই হাগিং ফেস অ্যাকাউন্ট উপর নির্ভর করবে। তাই আমরা একটি একাউন্ট ওপেন করার করার পরামর্শ দিচ্ছি: [একটি অ্যাকাউন্ট তৈরি করুন](https://huggingface.co/join)। + +## Google Colab নোটবুক ব্যবহার করার পদ্ধতি + +Colab নোটবুক ব্যবহার করার সবচেয়ে সহজ সেটআপ হচ্ছে ব্রাউজারে একটি নোটবুক ওপেন করুন এবং সরাসরি কোডিং এ যান! + +আপনি যদি Colab-এর সাথে পরিচিত না হন তাহলে আমরা আপনাকে [Colab পরিচয়](https://colab.research.google.com/notebooks/intro.ipynb) অনুসরণ করে শুরু করার পরামর্শ দিচ্ছি। Colab আপনাকে কিছু এক্সেলারেসন হার্ডওয়্যার ব্যবহার করতে দেয়, যেমন GPUs বা TPUs যা ছোট ওয়ার্ক লোডের জন্য ফ্রি। + +Colab-এর উপর আপানার হাত চলে আসলে একটি নতুন নোটবুক ওপেন করে সেট-আপ শুরু করুন: + +
+An empty colab notebook +
+ +পরবর্তী ধাপে আমরা এই কোর্সে ব্যবহার হবে এমন লাইব্রেরিগুলি ইনস্টল করা দেখাবো। আমরা ইনস্টলেশনের জন্য পাইথনের প্যাকেজ ম্যানেজার `pip` ব্যবহার করব। নোটবুকগুলিতে, আপনি `!` অক্ষর দিয়ে আগে সিস্টেম কমান্ড চালাতে পারবেন। যেমন ধরুন, নিচের কমান্ডটি দিয়ে 🤗 Transformers লাইব্রেরি ইনস্টল করতে পারবেন: + +``` +!pip install transformers +``` + +প্যাকেজটি আপনার পাইথন রানটাইমের মধ্যে সঠিকভাবে ইনস্টল করা হয়েছে কিনা তা import করে নিশ্চিত হতে পাড়েন। + +``` +import transformers +``` + +
+একটি gif উপরের দুটি কমান্ডের ফলাফল দেখাচ্ছে: installation and import +
+ +এটি 🤗 ট্রান্সফরমারের একটি খুব লাইট ভার্সন ইনস্টল করে। বিশেষ করে, যদিনা নির্দিষ্ট মেশিন লার্নিং ফ্রেমওয়ার্ক (যেমন PyTorch বা TensorFlow) ইনস্টল করা থাকে। যেহেতু আমরা লাইব্রেরির বিভিন্ন ফিচার ব্যবহার করব, তাই আমরা ডেভেলপমেন্ট ভার্সন ইনস্টল করার পরামর্শ দিচ্ছি, যতে ধারানা করার এমন সব ইউজ কেসে কাজ করবে: + +``` +!pip install transformers[sentencepiece] +``` + +ইনস্টল হতে কিছুটা সময় লাগবে, কিন্তু এরপর আপনি বাকি কোর্সের জন্য প্রস্তুত হয়ে যাবেন! + +## একটি পাইথন virtual environment ব্যবহার করা + +আপনি যদি পাইথন virtual environment ব্যবহার করতে পছন্দ করেন, প্রথম ধাপ হল আপনার সিস্টেমে পাইথন ইনস্টল করা। শুরু করার জন্য আমরা [এই নির্দেশিকা](https://realpython.com/installing-python/) অনুসরণ করার পরামর্শ দিচ্ছি। + +একবার আপনি পাইথন ইনস্টল করলে, আপনি আপনার টার্মিনালে পাইথন কমান্ড চালাতে সক্ষম হবেন। পরবর্তী ধাপে যাওয়ার আগে এটি সঠিকভাবে ইনস্টল করা হয়েছে তা নিশ্চিত করতে আপনি নিম্নলিখিত কমান্ডটি চালিয়ে শুরু করতে পারেন: `python --version`। এটি আপনার সিস্টেমে ইনস্টল হওয়া পাইথন সংস্করণটি প্রিন্ট করা উচিত। + +আপনার টার্মিনালে পাইথন কমান্ড চালানোর সময়, যেমন `python --version`, আপানাকে ভাবতে হবে যে এটি "main" পাইথন প্রোগ্রাম যা আপানার কমান্ড টিকে রান করছে। আমরা এই মূল ইনস্টলেশনটিকে যেকোন প্যাকেজ ইনস্টল থেকে মুক্ত রাখার সুপারিশ করি। এ আপনি যখন আলাদা অ্যাপ্লিকেশনে কাজ করবেন তখন তার জন্য আলাদা virtual environment তৈরি করতে এই পাইথন ইনস্টলেশনটিকে ব্যবহার করবেন। এতে করে প্রতিটি অ্যাপ্লিকেশনের নিজস্ব ডিপেন্ডেন্সি এবং প্যাকেজ আলাদা থাকবে এবং অন্যান্য অ্যাপ্লিকেশনের সাথে এর সম্ভাব্য কম্পাটিবিলটি নিয়ে আপানকে সমস্যায় করতে হবে না। + +পাইথনে এটি [*virtual environments*](https://docs.python.org/3/tutorial/venv.html) দিয়ে করা হয়, যেটি স্বয়ংসম্পূর্ণ ডিরেক্টরি ট্রি। যার প্রত্যেকটিতে এপ্লিকেশনের প্রয়োজনীয় সমস্ত প্যাকেজের পাশাপাশি একটি নির্দিষ্ট পাইথন ভার্শনের পাইথন ইনস্টলেশন আছে। এই ধরনের একটি virtual environments বিভিন্ন ভাবে তৈরি করা যেতে পারে। তবে আমরা এর জন্য অফিসিয়াল পাইথন প্যাকেজ ব্যবহার করব, যাকে বলা হয় [`venv`](https://docs.python.org/3/library) /venv.html#module-venv)। + +প্রথমে, আপনি যে ডিরেক্টরিটি আপনার অ্যাপ্লিকেশনটিতে রাখতে চান তা তৈরি করুন — উদাহরণস্বরূপ, আপনি আপনার হোম ডিরেক্টরির বা ফোল্ডার ভেতর *transformers-course* নামে একটি নতুন ডিরেক্টরি তৈরি করতে চাইতে পারেন: + +``` +mkdir ~/transformers-course +cd ~/transformers-course +``` + +এই ডিরেক্টরির ভিতর থেকে, পাইথন `venv` মডিউল ব্যবহার করে একটি virtual environment তৈরি করুন: + +``` +python -m venv .env +``` + +আপনার এখন *.env* নামে একটি ফোল্ডার থাকা উচিত, অন্যথায় খালি ফোল্ডার : + +``` +ls -a +``` + +```out +. .. .env +``` + + +আপনি এখন virtual environment টি `activate` করতে বা `deactivate` নিচের কমান্ড গুলো ব্যবহার করতে পারেন। + +``` +# virtual environment টি activate করার কমান্ড +source .env/bin/activate + +# virtual environment টি deactivate করার কমান্ড +deactivate +``` + +`which python` কমান্ড চালিয়ে নিশ্চিত করতে পারেন যে virtual environment টি activate হয়েছে কিনা। +যদি এটি virtual environment টি কে পয়েন্ট করে করে, তাহলে আপনি সফলভাবে এটি সক্রিয় করেছেন! + +``` +which python +``` + +```out +/home//transformers-course/.env/bin/python +``` + +### ডিপেন্ডেন্সি ইনস্টল করা + +আগের সেকশনে Google Colab এ যেভাবে প্যাকেজ ইনস্টল করা হয়েছে একই ভাবে এখানেও `pip` প্যাকেজ ম্যানেজার ব্যবহার করে 🤗 Transformer এর development সংস্করণ ইনস্টল করতে পারেন: + +```` +pip install "transformers[sentencepiece]" +```` + +আপনি এখন শুরু করা জন্য সম্পূর্ণ প্রস্তুত! diff --git a/chapters/bn/chapter1/1.mdx b/chapters/bn/chapter1/1.mdx index c3c0d7682..6f8feec49 100644 --- a/chapters/bn/chapter1/1.mdx +++ b/chapters/bn/chapter1/1.mdx @@ -1,64 +1,64 @@ -# ভূমিকা - - - -## 🤗 কোর্সে স্বাগতম! - - - -এই কোর্সটি আপনাকে [হাগিং ফেস](https://huggingface.co/) ইকোসিস্টেম থেকে — 🤗 - [🤗 ট্রান্সফরমার](https://github.com/huggingface/transformers),[🤗 ডেটাসেট](https://github.com/huggingface/datasets), [🤗 টোকেনাইজার](https://github.com/huggingface/tokenizers),এবং [🤗 অ্যাক্সিলারেট](https://github.com/huggingface/accelerate) — সেইসাথে হাগিং ফেস হাব থেকে লাইব্রেরি ব্যবহার করে ন্যচারাল ল্যঙ্গুএজ প্রসেসিং(NLP) শেখাবে। এটি সাইট টি বিজ্ঞাপন ছাড়াই সম্পূর্ণ ফ্রি। - - -## এই কোর্সটি থেকে কি আশা করা যায়? - -এখানে কোর্সের একটি সংক্ষিপ্ত বিবরণ রয়েছে: - -
-Brief overview of the chapters of the course. - -
- -- অধ্যায় ১ থেকে ৪ 🤗 ট্রান্সফরমার লাইব্রেরির মূল ধারণাগুলির একটি ভূমিকা প্রদান করে। কোর্সের এই অংশের শেষে, আপনি ট্রান্সফরমার মডেলগুলি কীভাবে কাজ করে তার সাথে পরিচিত হবেন। এছাড়াও [হাগিং ফেস হাব](https://huggingface.co/models) থেকে একটি মডেল কীভাবে ব্যবহার করতে হয়, কীভাবে মডেল এর ডেটাসেটিকে ফাইন-টিউন করতে হয় এবং হাবে কীভাবে আপনার ফলাফল শেয়ার করতে হয় তা জানতে পারবেন! - -- ক্লাসিক NLP টাস্কগুলোর গভীরে যাওয়ার আগে অধ্যায় ৫ থেকে ৮, আপনাকে 🤗 ডেটাসেট এবং 🤗 টোকেনাইজারগুলির মূল বিষয়গুলি শেখাবে৷ এই অংশের শেষে, আপনি নিজেই সবচেয়ে কমন NLP সমস্যাগুলি সমাধান করতে পাড়বেন। - -- অধ্যায় ৯ থেকে ১২, এবং স্পীচ প্রসেসিং এবং কম্পিউটার ভিশনের কাজগুলো ট্রান্সফরমার মডেলগুলোকে কীভাবে ব্যবহার করা যেতে পারে তা খতিয়ে দেখে। অধ্যায়টি পড়তে পড়তে আপনি শিখবেন কিভাবে আপনার মডেল বিল্ড এবং ডেমো শেয়ার করতে হয়, কিভাবে প্রডাকশন এনভায়রনমেন্টের জন্য অপ্টিমাইজ করতে হয়। এই অংশের শেষ নাগাদ, (প্রায়) যেকোনও মেশিন লার্নিং সমস্যায় আপনি 🤗 ট্রান্সফরমার প্রয়োগ করতে প্রস্তুত হয়ে যাবেন! - - -এই কোর্স:: - -* পাইথন সম্পর্কে ভাল জ্ঞান প্রয়োজন -* একটি প্রাথমিক ডিপ লার্নিং কোর্স করে নেওয়া ভালো, যেমন fast.ai-এর [fast.ai's](https://www.fast.ai/) [Practical Deep Learning for Coders](https://course.fast.ai/) বা [DeepLearning.AI](https://www.deeplearning.ai/) এর প্রোগ্রামগুলির মধ্যে একটি। -* [PyTorch](https://pytorch.org/) বা [TensorFlow](https://www.tensorflow.org/) জানা জরুরি না, যদিও এদের যেকোনো একটির সাথে কিছু পরিচয় থাকলে সেটা আপানাকে সাহায্য করবে। - -আপনি এই কোর্সটি সম্পন্ন করার পরে, আমরা DeepLearning.AI-এর [Natural Language Processing Specialization](https://www.coursera.org/specializations/natural-language-processing?utm_source=deeplearning-ai&utm_medium=institutions&utm_campaign=20211011-nlp-2-hugging_face-page-nlp-refresh) কোর্সটি করার পরামর্শ দিই, যেটি প্রথাগত NLP মডেল যেমন naive Bayes এবং LSTMs সম্পর্কে জানতে আপনাকে সাহায্য করবে! - -## আমরা কারা?? - -লেখক সম্পর্কে:: - -**Matthew Carrigan ম্যাথিউ ক্যারিগান** Hugging Face এর একজন মেশিন লার্নিং ইঞ্জিনিয়ার। তিনি আয়ারল্যান্ডের ডাবলিনে থাকেন এবং পূর্বে Parse.ly-এ একজন ML ইঞ্জিনিয়ার হিসেবে এবং তার আগে ট্রিনিটি কলেজ ডাবলিন-এ একজন পোস্ট-ডক্টরাল গবেষক হিসেবে কাজ করেছেন। তিনি বিশ্বাস করেন না যে আমরা বিদ্যমান আর্কিটেকচারগুলিকে স্কেল করে AGI তে পৌছাবো, তবে তিনি দৃড়ভাবে আশা করেন যে আমারা রোবট অমরত্বের দিকে যাচ্ছি৷ - -**Lysandre Debut লিসান্দ্রে ডেব্যু** Hugging Face এর একজন মেশিন লার্নিং ইঞ্জিনিয়ার এবং খুব প্রাথমিক পর্যায় থেকে 🤗 Transformers লাইব্রেরিতে কাজ করছেন। তার লক্ষ্য হল একটি খুব সাধারণ API-এর সাহায্যে টুল ডেভেলপ করে সবার জন্য NLP কে সুবোধ্য করে তোলা। - -**Sylvain Gugger সিলভাইন গুগার** হলেন হাগিং ফেসের একজন গবেষণা প্রকৌশলী এবং 🤗 ট্রান্সফরমার লাইব্রেরির মূল রক্ষণাবেক্ষণকারীদের একজন। পূর্বে তিনি fast.ai-এর একজন গবেষণা বিজ্ঞানী ছিলেন এবং জেরেমি হাওয়ার্ডের সাথে _[Deep Learning for Coders with fastai and PyTorch](https://learning.oreilly.com/library/view/deep-learning-for/9781492045519/)_ বইটি লেখেন। তার গবেষণার মূল ফোকাস হল মডেল গুলিকে আরও উন্নত করে এবং অল্প রিসোর্স ব্যবহার করে ট্রেনিং ব্যবস্থা করার মাধ্যমে সবার জন্য deep learning এর কৌশলগুলি আরও সুবোধ্য করে তোলা। - -**Merve Noyan মার্ভে নইয়ান** হলেন Hugging Face এর একজন ডেভেলপার অ্যাডভোকেট। যিনি টুল ডেভেলপ করেন এবং সেগুলো ব্যবহার করে কন্টেন্ট তৈরি করেন যাতে মেশিন লার্নিংকে গণতান্ত্রিক করা যায়। - -**Lucile Saulnier** হলেন Hugging Face এর একজন মেশিন লার্নিং ইঞ্জিনিয়ার, যিনি ওপেন সোর্স টুলের ডেভেলপমেন্ট ও ব্যবহার এ সাহায্য করে থাকেন। তিনি ন্যচালার ল্যঙ্গুএজ প্রসেসিং এর পাশাপাশি collaborative training এবং বিগসায়েন্সের মতো বিষয়ের অনেক গবেষণা প্রকল্পে সক্রিয়ভাবে জড়িত। - - -**Lewis Tunstall** হলেন একজন মেশিন লার্নিং ইঞ্জিনিয়ার, যিনি ওপেন-সোর্স টুল ডেভেলপ করতে এবং সেগুলিকে বৃহত্তর সম্প্রদায়ের কাছে অ্যাক্সেসযোগ্য করে তোলার দিকে মনোনিবেশ করেন৷ তিনি একটি আসন্ন একটি বইয়ের সহ-লেখক [O’Reilly book on Transformers](https://www.oreilly.com/library/view/natural-language-processing/9781098136789/). - - -**Leandro von Werra** হলেন Hugging Face-এর ওপেন-সোর্স টিমের একজন মেশিন লার্নিং ইঞ্জিনিয়ার এবং ট্রান্সফরমারের উপর একটি আসন্ন O'Reilly বইয়ের সহ-লেখক [O’Reilly book on Transformers](https://www.oreilly.com/library/view/natural-language-processing/9781098136789/). পুরো মেশিন লার্নিং স্ট্যাক জুড়ে কাজ করে NLP প্রকল্পগুলিকে উৎপাদনে নিয়ে আসার কয়েক বছরের ইন্ডাস্ট্রি অভিজ্ঞতা রয়েছে তার। - - -আপনি রোল প্রস্তুত? এই অধ্যায়ে, আপনি শিখবেন: -* কিভাবে টেক্সট জেনারেশন এবং শ্রেণীবিভাগের মতো NLP কাজগুলি সমাধান করতে ` `pipeline()` ফাংশন ব্যবহার করবেন -* ট্রান্সফরমার আর্কিটেকচার সম্পর্কে -* কিভাবে এনকোডার, ডিকোডার এবং এনকোডার-ডিকোডার আর্কিটেকচারের মধ্যে পার্থক্য করা যায় এবং কেস ব্যবহার করা যায়। +# ভূমিকা + + + +## 🤗 কোর্সে স্বাগতম! + + + +এই কোর্সটি আপনাকে [হাগিং ফেস](https://huggingface.co/) ইকোসিস্টেম থেকে — 🤗 + [🤗 ট্রান্সফরমার](https://github.com/huggingface/transformers),[🤗 ডেটাসেট](https://github.com/huggingface/datasets), [🤗 টোকেনাইজার](https://github.com/huggingface/tokenizers),এবং [🤗 অ্যাক্সিলারেট](https://github.com/huggingface/accelerate) — সেইসাথে হাগিং ফেস হাব থেকে লাইব্রেরি ব্যবহার করে ন্যচারাল ল্যঙ্গুএজ প্রসেসিং(NLP) শেখাবে। এটি সাইট টি বিজ্ঞাপন ছাড়াই সম্পূর্ণ ফ্রি। + + +## এই কোর্সটি থেকে কি আশা করা যায়? + +এখানে কোর্সের একটি সংক্ষিপ্ত বিবরণ রয়েছে: + +
+Brief overview of the chapters of the course. + +
+ +- অধ্যায় ১ থেকে ৪ 🤗 ট্রান্সফরমার লাইব্রেরির মূল ধারণাগুলির একটি ভূমিকা প্রদান করে। কোর্সের এই অংশের শেষে, আপনি ট্রান্সফরমার মডেলগুলি কীভাবে কাজ করে তার সাথে পরিচিত হবেন। এছাড়াও [হাগিং ফেস হাব](https://huggingface.co/models) থেকে একটি মডেল কীভাবে ব্যবহার করতে হয়, কীভাবে মডেল এর ডেটাসেটিকে ফাইন-টিউন করতে হয় এবং হাবে কীভাবে আপনার ফলাফল শেয়ার করতে হয় তা জানতে পারবেন! + +- ক্লাসিক NLP টাস্কগুলোর গভীরে যাওয়ার আগে অধ্যায় ৫ থেকে ৮, আপনাকে 🤗 ডেটাসেট এবং 🤗 টোকেনাইজারগুলির মূল বিষয়গুলি শেখাবে৷ এই অংশের শেষে, আপনি নিজেই সবচেয়ে কমন NLP সমস্যাগুলি সমাধান করতে পাড়বেন। + +- অধ্যায় ৯ থেকে ১২, এবং স্পীচ প্রসেসিং এবং কম্পিউটার ভিশনের কাজগুলো ট্রান্সফরমার মডেলগুলোকে কীভাবে ব্যবহার করা যেতে পারে তা খতিয়ে দেখে। অধ্যায়টি পড়তে পড়তে আপনি শিখবেন কিভাবে আপনার মডেল বিল্ড এবং ডেমো শেয়ার করতে হয়, কিভাবে প্রডাকশন এনভায়রনমেন্টের জন্য অপ্টিমাইজ করতে হয়। এই অংশের শেষ নাগাদ, (প্রায়) যেকোনও মেশিন লার্নিং সমস্যায় আপনি 🤗 ট্রান্সফরমার প্রয়োগ করতে প্রস্তুত হয়ে যাবেন! + + +এই কোর্স:: + +* পাইথন সম্পর্কে ভাল জ্ঞান প্রয়োজন +* একটি প্রাথমিক ডিপ লার্নিং কোর্স করে নেওয়া ভালো, যেমন fast.ai-এর [fast.ai's](https://www.fast.ai/) [Practical Deep Learning for Coders](https://course.fast.ai/) বা [DeepLearning.AI](https://www.deeplearning.ai/) এর প্রোগ্রামগুলির মধ্যে একটি। +* [PyTorch](https://pytorch.org/) বা [TensorFlow](https://www.tensorflow.org/) জানা জরুরি না, যদিও এদের যেকোনো একটির সাথে কিছু পরিচয় থাকলে সেটা আপানাকে সাহায্য করবে। + +আপনি এই কোর্সটি সম্পন্ন করার পরে, আমরা DeepLearning.AI-এর [Natural Language Processing Specialization](https://www.coursera.org/specializations/natural-language-processing?utm_source=deeplearning-ai&utm_medium=institutions&utm_campaign=20211011-nlp-2-hugging_face-page-nlp-refresh) কোর্সটি করার পরামর্শ দিই, যেটি প্রথাগত NLP মডেল যেমন naive Bayes এবং LSTMs সম্পর্কে জানতে আপনাকে সাহায্য করবে! + +## আমরা কারা?? + +লেখক সম্পর্কে:: + +**Matthew Carrigan ম্যাথিউ ক্যারিগান** Hugging Face এর একজন মেশিন লার্নিং ইঞ্জিনিয়ার। তিনি আয়ারল্যান্ডের ডাবলিনে থাকেন এবং পূর্বে Parse.ly-এ একজন ML ইঞ্জিনিয়ার হিসেবে এবং তার আগে ট্রিনিটি কলেজ ডাবলিন-এ একজন পোস্ট-ডক্টরাল গবেষক হিসেবে কাজ করেছেন। তিনি বিশ্বাস করেন না যে আমরা বিদ্যমান আর্কিটেকচারগুলিকে স্কেল করে AGI তে পৌছাবো, তবে তিনি দৃড়ভাবে আশা করেন যে আমারা রোবট অমরত্বের দিকে যাচ্ছি৷ + +**Lysandre Debut লিসান্দ্রে ডেব্যু** Hugging Face এর একজন মেশিন লার্নিং ইঞ্জিনিয়ার এবং খুব প্রাথমিক পর্যায় থেকে 🤗 Transformers লাইব্রেরিতে কাজ করছেন। তার লক্ষ্য হল একটি খুব সাধারণ API-এর সাহায্যে টুল ডেভেলপ করে সবার জন্য NLP কে সুবোধ্য করে তোলা। + +**Sylvain Gugger সিলভাইন গুগার** হলেন হাগিং ফেসের একজন গবেষণা প্রকৌশলী এবং 🤗 ট্রান্সফরমার লাইব্রেরির মূল রক্ষণাবেক্ষণকারীদের একজন। পূর্বে তিনি fast.ai-এর একজন গবেষণা বিজ্ঞানী ছিলেন এবং জেরেমি হাওয়ার্ডের সাথে _[Deep Learning for Coders with fastai and PyTorch](https://learning.oreilly.com/library/view/deep-learning-for/9781492045519/)_ বইটি লেখেন। তার গবেষণার মূল ফোকাস হল মডেল গুলিকে আরও উন্নত করে এবং অল্প রিসোর্স ব্যবহার করে ট্রেনিং ব্যবস্থা করার মাধ্যমে সবার জন্য deep learning এর কৌশলগুলি আরও সুবোধ্য করে তোলা। + +**Merve Noyan মার্ভে নইয়ান** হলেন Hugging Face এর একজন ডেভেলপার অ্যাডভোকেট। যিনি টুল ডেভেলপ করেন এবং সেগুলো ব্যবহার করে কন্টেন্ট তৈরি করেন যাতে মেশিন লার্নিংকে গণতান্ত্রিক করা যায়। + +**Lucile Saulnier** হলেন Hugging Face এর একজন মেশিন লার্নিং ইঞ্জিনিয়ার, যিনি ওপেন সোর্স টুলের ডেভেলপমেন্ট ও ব্যবহার এ সাহায্য করে থাকেন। তিনি ন্যচালার ল্যঙ্গুএজ প্রসেসিং এর পাশাপাশি collaborative training এবং বিগসায়েন্সের মতো বিষয়ের অনেক গবেষণা প্রকল্পে সক্রিয়ভাবে জড়িত। + + +**Lewis Tunstall** হলেন একজন মেশিন লার্নিং ইঞ্জিনিয়ার, যিনি ওপেন-সোর্স টুল ডেভেলপ করতে এবং সেগুলিকে বৃহত্তর সম্প্রদায়ের কাছে অ্যাক্সেসযোগ্য করে তোলার দিকে মনোনিবেশ করেন৷ তিনি একটি আসন্ন একটি বইয়ের সহ-লেখক [O’Reilly book on Transformers](https://www.oreilly.com/library/view/natural-language-processing/9781098136789/). + + +**Leandro von Werra** হলেন Hugging Face-এর ওপেন-সোর্স টিমের একজন মেশিন লার্নিং ইঞ্জিনিয়ার এবং ট্রান্সফরমারের উপর একটি আসন্ন O'Reilly বইয়ের সহ-লেখক [O’Reilly book on Transformers](https://www.oreilly.com/library/view/natural-language-processing/9781098136789/). পুরো মেশিন লার্নিং স্ট্যাক জুড়ে কাজ করে NLP প্রকল্পগুলিকে উৎপাদনে নিয়ে আসার কয়েক বছরের ইন্ডাস্ট্রি অভিজ্ঞতা রয়েছে তার। + + +আপনি রোল প্রস্তুত? এই অধ্যায়ে, আপনি শিখবেন: +* কিভাবে টেক্সট জেনারেশন এবং শ্রেণীবিভাগের মতো NLP কাজগুলি সমাধান করতে ` `pipeline()` ফাংশন ব্যবহার করবেন +* ট্রান্সফরমার আর্কিটেকচার সম্পর্কে +* কিভাবে এনকোডার, ডিকোডার এবং এনকোডার-ডিকোডার আর্কিটেকচারের মধ্যে পার্থক্য করা যায় এবং কেস ব্যবহার করা যায়। diff --git a/chapters/bn/chapter2/1.mdx b/chapters/bn/chapter2/1.mdx index fd19b9784..5b79faee4 100644 --- a/chapters/bn/chapter2/1.mdx +++ b/chapters/bn/chapter2/1.mdx @@ -1,24 +1,24 @@ -# ভূমিকা - - - - [অধ্যায় ১](/course/bn/chapter1) এ আমরা দেখে এসেছি যে Transformer মডেলগুলো সাধারণত অনেক বড় হয়। লাখ-লাখ কোটি-কোটি প্যারামিটার সম্বলিত এই মডেল গুলো কে ট্রেনিং এবং ডেপ্লয় করা বেশ জটিল ও কষ্টসাধ্য একটা কাজ। তাছাড়াও প্রায় প্রতিদিনই নতুন নতুন মডেল রিলিজ হচ্ছে এবং সবগুলোরই নিজস্ব বাস্তবায়ন রয়েছে। এই সবকিছু একসাথে এপ্লাই করা খুব সহজ একটা কাজ নয়। - -এই 🤗 Transformers লাইব্রেরিটা বানানো হয়েছে এই সমস্যাগুলো সমাধান করার জন্য। এর আসল উদ্দেশ্য হলো এমন একটি API প্রদান করা যার মাধ্যমে যেকোনো Transformer মডেলকে লোড করা, ট্রেইন করা কিংবা সেভ করা যাবে। লাইব্রেরিটির আসল ফিচারগুলো হলঃ - -- **সহজে ব্যবহারযোগ্য**: ডাউনলোড করা, লোড করা এবং যেকোন state-of-the-art মডেল দিয়ে inference করা যাবে মাত্র দুই লাইনের কোড দিয়ে। -- **ফ্লেক্সিবিলিটি**: সবগুলো Transformer মডেলই আসলে PyTorch `nn.Module` অথবা TensorFlow `tf.keras.Model` ক্লাস , আর অন্য যেকোনো মডেলের মতোই এদেরকে তাদের নিজ নিজ মেশিন লার্নিং ফ্রেমওয়ার্ক এ সহজেই পরিচালনা করা যায়। - -- **সরলতা**: লাইব্রেরি জুড়ে খুব কমই বিমূর্ততা তৈরি করা হয়। "All in one file" এমন একটি ধারণাঃ একটা মডেলের পুরো Forward Pass কে সম্পূর্ণরূপে একটি সিঙ্গেল ফাইলে নিয়ে আসা হয়েছে, যাতে করে কোডটি সহজেই বুঝা ও মডিফাই করা যায়। - -এই শেষ বৈশিষ্ট্যটি(সরলতা) 🤗 ট্রান্সফরমারকে অন্যান্য ML লাইব্রেরি থেকে বেশ আলাদা করে তোলে। এখানে মডেলগুলি কোনো মডিউল এর উপর নির্মিত নয় যেগুলো ফাইল জুড়ে শেয়ার্ড অবস্থায় থাকে; বরংচ, প্রতিটি মডেলের নিজস্ব স্তর(Layer)রয়েছে। মডেলগুলিকে আরও সহজলভ্য এবং বোধগম্য করার পাশাপাশি, 🤗 Transformers আপনাকে অন্য মডেলকে প্রভাবিত না করে সহজেই একটি মডেলে নিয়ে এক্সপেরিমেন্ট করতে দেয়৷ - -এই অধ্যায়টি একটি পূর্নাঙ্গ উদাহরন দিয়ে শুরু হবে, যেখানে [অধ্যায় ১](/course/bn/chapter1) এ উল্লিখিত `pipeline()` ফাংশনটি প্রতিলিপি করতে আমরা একটি মডেল এবং একটি টোকেনাইজার একসাথে ব্যবহার করব। এর পরে, আমরা মডেল API নিয়ে আলোচনা করব: আমরা মডেল এবং কনফিগারেশন ক্লাসগুলির খুঁটিনাটি দেখব এবং আপনাকে দেখাব কীভাবে একটি মডেল লোড করতে হয় এবং কীভাবে এটি সংখ্যাসূচক ইনপুটগুলিকে প্রক্রিয়া করে আউটপুট প্রেডিক্ট করা যায়। - -তারপরে আমরা টোকেনাইজার API দেখব, যা `pipeline()` ফাংশনের অন্য একটি প্রধান উপাদান। টোকেনাইজার জিনিসটা প্রথম ও শেষ প্রসেসিং স্টেপগুলোতে মেইনলি কাজে লাগে, নিউরাল নেটওয়ার্কের জন্য টেক্সট ডাটা থেকে সংখ্যাসূচক ইনপুটে রূপান্তর এবং পরে আবার প্রয়োজন অনুযায়ী সংখ্যাসূচক ডাটা থেকে টেক্সট ডাটাতে রূপান্তর করার সময়। পরিশেষে, আমরা আপনাকে দেখাব কিভাবে ব্যাচের মাধ্যমে একাধিক বাক্যকে একটি মডেলে পাঠানো যায়। তারপরে আরেকবার হাই-লেভেলে `tokenizer()` ফাংশনটিকে একনজরে দেখার মাধ্যমে পুরো অধ্যায়ের ইতি টানব। - -> [!TIP] +# ভূমিকা + + + + [অধ্যায় ১](/course/bn/chapter1) এ আমরা দেখে এসেছি যে Transformer মডেলগুলো সাধারণত অনেক বড় হয়। লাখ-লাখ কোটি-কোটি প্যারামিটার সম্বলিত এই মডেল গুলো কে ট্রেনিং এবং ডেপ্লয় করা বেশ জটিল ও কষ্টসাধ্য একটা কাজ। তাছাড়াও প্রায় প্রতিদিনই নতুন নতুন মডেল রিলিজ হচ্ছে এবং সবগুলোরই নিজস্ব বাস্তবায়ন রয়েছে। এই সবকিছু একসাথে এপ্লাই করা খুব সহজ একটা কাজ নয়। + +এই 🤗 Transformers লাইব্রেরিটা বানানো হয়েছে এই সমস্যাগুলো সমাধান করার জন্য। এর আসল উদ্দেশ্য হলো এমন একটি API প্রদান করা যার মাধ্যমে যেকোনো Transformer মডেলকে লোড করা, ট্রেইন করা কিংবা সেভ করা যাবে। লাইব্রেরিটির আসল ফিচারগুলো হলঃ + +- **সহজে ব্যবহারযোগ্য**: ডাউনলোড করা, লোড করা এবং যেকোন state-of-the-art মডেল দিয়ে inference করা যাবে মাত্র দুই লাইনের কোড দিয়ে। +- **ফ্লেক্সিবিলিটি**: সবগুলো Transformer মডেলই আসলে PyTorch `nn.Module` অথবা TensorFlow `tf.keras.Model` ক্লাস , আর অন্য যেকোনো মডেলের মতোই এদেরকে তাদের নিজ নিজ মেশিন লার্নিং ফ্রেমওয়ার্ক এ সহজেই পরিচালনা করা যায়। + +- **সরলতা**: লাইব্রেরি জুড়ে খুব কমই বিমূর্ততা তৈরি করা হয়। "All in one file" এমন একটি ধারণাঃ একটা মডেলের পুরো Forward Pass কে সম্পূর্ণরূপে একটি সিঙ্গেল ফাইলে নিয়ে আসা হয়েছে, যাতে করে কোডটি সহজেই বুঝা ও মডিফাই করা যায়। + +এই শেষ বৈশিষ্ট্যটি(সরলতা) 🤗 ট্রান্সফরমারকে অন্যান্য ML লাইব্রেরি থেকে বেশ আলাদা করে তোলে। এখানে মডেলগুলি কোনো মডিউল এর উপর নির্মিত নয় যেগুলো ফাইল জুড়ে শেয়ার্ড অবস্থায় থাকে; বরংচ, প্রতিটি মডেলের নিজস্ব স্তর(Layer)রয়েছে। মডেলগুলিকে আরও সহজলভ্য এবং বোধগম্য করার পাশাপাশি, 🤗 Transformers আপনাকে অন্য মডেলকে প্রভাবিত না করে সহজেই একটি মডেলে নিয়ে এক্সপেরিমেন্ট করতে দেয়৷ + +এই অধ্যায়টি একটি পূর্নাঙ্গ উদাহরন দিয়ে শুরু হবে, যেখানে [অধ্যায় ১](/course/bn/chapter1) এ উল্লিখিত `pipeline()` ফাংশনটি প্রতিলিপি করতে আমরা একটি মডেল এবং একটি টোকেনাইজার একসাথে ব্যবহার করব। এর পরে, আমরা মডেল API নিয়ে আলোচনা করব: আমরা মডেল এবং কনফিগারেশন ক্লাসগুলির খুঁটিনাটি দেখব এবং আপনাকে দেখাব কীভাবে একটি মডেল লোড করতে হয় এবং কীভাবে এটি সংখ্যাসূচক ইনপুটগুলিকে প্রক্রিয়া করে আউটপুট প্রেডিক্ট করা যায়। + +তারপরে আমরা টোকেনাইজার API দেখব, যা `pipeline()` ফাংশনের অন্য একটি প্রধান উপাদান। টোকেনাইজার জিনিসটা প্রথম ও শেষ প্রসেসিং স্টেপগুলোতে মেইনলি কাজে লাগে, নিউরাল নেটওয়ার্কের জন্য টেক্সট ডাটা থেকে সংখ্যাসূচক ইনপুটে রূপান্তর এবং পরে আবার প্রয়োজন অনুযায়ী সংখ্যাসূচক ডাটা থেকে টেক্সট ডাটাতে রূপান্তর করার সময়। পরিশেষে, আমরা আপনাকে দেখাব কিভাবে ব্যাচের মাধ্যমে একাধিক বাক্যকে একটি মডেলে পাঠানো যায়। তারপরে আরেকবার হাই-লেভেলে `tokenizer()` ফাংশনটিকে একনজরে দেখার মাধ্যমে পুরো অধ্যায়ের ইতি টানব। + +> [!TIP] > ⚠️ Model Hub এবং 🤗 Transformers এর সাথে উপলব্ধ সমস্ত বৈশিষ্ট্যগুলি থেকে উপকৃত হওয়ার জন্য, আমরা সাজেস্ট করি এখানে একটি একাউন্ট তৈরি করার জন্যে।. \ No newline at end of file diff --git a/chapters/de/TRANSLATING.txt b/chapters/de/TRANSLATING.txt index 053f5930d..9649c90c0 100644 --- a/chapters/de/TRANSLATING.txt +++ b/chapters/de/TRANSLATING.txt @@ -1,46 +1,46 @@ -1. We use the informal "you" (i.e. "Du" instead of "Sie") to keep the tone jovial. - However, don't use slang or local language, so use the correct form of "als", - and "wie" rather than the locally accepted form. - -2. Don't translate industry-accepted acronyms. e.g. TPU or GPU. - -3. The German language accepts English words especially in modern contexts more than - many other languages (i.e. Anglicisms). Check for the correct usage of terms in - computer science and commonly used terms in other publications. - -4. Beware of "false friends" in German and English translations. Translators are trained - for years to specifically avoid false English friends and avoid anglicised translations. - e.g. "Daten" is "data", but "dates" is "Termine". For more examples refer to: - https://lal.de/blog/false-friends-falsche-freunde/ - -5. Keep voice active and consistent. Don't overdo it but try to avoid a passive voice. - -6. Refer and contribute to the glossary frequently to stay on top of the latest - choices we make. This minimizes the amount of editing that is required. - -7. Keep POV consistent. - -8. Smaller sentences are better sentences. Apply with nuance. - -9. If translating a technical word, keep the choice of German translation consistent. - This does not apply for non-technical choices, as in those cases variety actually - helps keep the text engaging. - -10. This is merely a translation. Don't add any technical/contextual information - not present in the original text. Also don't leave stuff out. The creative - choices in composing this information were the original authors' to make. - Our creative choices are in doing a quality translation. - -11. Be exact when choosing equivalents for technical words. Package is package. - Library is library. Don't mix and match. - -12. Library names are kept in the original forms, e.g. "🤗 Datasets", however, - the word dataset in a sentence gets a translation to "Datensatz". - -13. As a style choice prefer the imperative over constructions with auxiliary words - to avoid unnecessary verbosity and addressing of the reader, which seems - unnatural in German. e.g. "Siehe Kapitel X" - "See chapter X" instead of - "Dies kannst du in Kapitel X sehen" - "You can see this in chapter X". - -14. Be careful with sentences using "wir", which can seem unnatural at best and +1. We use the informal "you" (i.e. "Du" instead of "Sie") to keep the tone jovial. + However, don't use slang or local language, so use the correct form of "als", + and "wie" rather than the locally accepted form. + +2. Don't translate industry-accepted acronyms. e.g. TPU or GPU. + +3. The German language accepts English words especially in modern contexts more than + many other languages (i.e. Anglicisms). Check for the correct usage of terms in + computer science and commonly used terms in other publications. + +4. Beware of "false friends" in German and English translations. Translators are trained + for years to specifically avoid false English friends and avoid anglicised translations. + e.g. "Daten" is "data", but "dates" is "Termine". For more examples refer to: + https://lal.de/blog/false-friends-falsche-freunde/ + +5. Keep voice active and consistent. Don't overdo it but try to avoid a passive voice. + +6. Refer and contribute to the glossary frequently to stay on top of the latest + choices we make. This minimizes the amount of editing that is required. + +7. Keep POV consistent. + +8. Smaller sentences are better sentences. Apply with nuance. + +9. If translating a technical word, keep the choice of German translation consistent. + This does not apply for non-technical choices, as in those cases variety actually + helps keep the text engaging. + +10. This is merely a translation. Don't add any technical/contextual information + not present in the original text. Also don't leave stuff out. The creative + choices in composing this information were the original authors' to make. + Our creative choices are in doing a quality translation. + +11. Be exact when choosing equivalents for technical words. Package is package. + Library is library. Don't mix and match. + +12. Library names are kept in the original forms, e.g. "🤗 Datasets", however, + the word dataset in a sentence gets a translation to "Datensatz". + +13. As a style choice prefer the imperative over constructions with auxiliary words + to avoid unnecessary verbosity and addressing of the reader, which seems + unnatural in German. e.g. "Siehe Kapitel X" - "See chapter X" instead of + "Dies kannst du in Kapitel X sehen" - "You can see this in chapter X". + +14. Be careful with sentences using "wir", which can seem unnatural at best and condescending at worst in German. \ No newline at end of file diff --git a/chapters/de/_toctree.yml b/chapters/de/_toctree.yml index cf4af10c2..d16e3320e 100644 --- a/chapters/de/_toctree.yml +++ b/chapters/de/_toctree.yml @@ -1,66 +1,66 @@ -- title: 0. Einrichtung - sections: - - local: chapter0/1 - title: Einführung - -- title: 1. Transformer-Modelle - sections: - - local: chapter1/1 - title: Einführung - - local: chapter1/2 - title: Natural Language Processing - - local: chapter1/3 - title: Transformer-Modelle - wozu sind sie imstande? - - local: chapter1/4 - title: Wie funktionieren Transformer-Modelle? - - local: chapter1/5 - title: Encoder-Modelle - - local: chapter1/6 - title: Decoder-Modelle - - local: chapter1/7 - title: Sequence-to-Sequence-Modelle - - local: chapter1/8 - title: Bias und Einschränkungen - - local: chapter1/9 - title: Zusammenfassung - - local: chapter1/10 - title: Quiz am Ende des Kapitels - quiz: 1 - -- title: 3. Fine-tuning von vortrainierten Modellen - sections: - - local: chapter3/1 - title: Einführung - - local: chapter3/2 - title: Datenbearbeitung - - local: chapter3/3 - title: Fine-tuning von Modellen mit der Trainer API oder Keras - local_fw: { pt: chapter3/3, tf: chapter3/3_tf } - - local: chapter3/4 - title: Komplettes Training - - local: chapter3/5 - title: Fine-tuning, Check! - - local: chapter3/6 - title: Quiz am Ende des Kapitels - quiz: 3 - -- title: 4. Teilen von Modellen und Tokenizers - sections: - - local: chapter4/1 - title: Der Hugging Face Hub - - local: chapter4/2 - title: Verwendung vortrainierter Modelle - - local: chapter4/3 - title: Vortrainierte Modelle teilen - - local: chapter4/4 - title: Erstellung einer Modellkarte ("model card") - - local: chapter4/5 - title: Teil 1 abgeschlossen! - - local: chapter4/6 - title: Quiz am Ende des Kapitels - quiz: 4 - -- title: Wörterverzeichnis - sections: - - local: glossary/1 - title: Wörterverzeichnis +- title: 0. Einrichtung + sections: + - local: chapter0/1 + title: Einführung + +- title: 1. Transformer-Modelle + sections: + - local: chapter1/1 + title: Einführung + - local: chapter1/2 + title: Natural Language Processing + - local: chapter1/3 + title: Transformer-Modelle - wozu sind sie imstande? + - local: chapter1/4 + title: Wie funktionieren Transformer-Modelle? + - local: chapter1/5 + title: Encoder-Modelle + - local: chapter1/6 + title: Decoder-Modelle + - local: chapter1/7 + title: Sequence-to-Sequence-Modelle + - local: chapter1/8 + title: Bias und Einschränkungen + - local: chapter1/9 + title: Zusammenfassung + - local: chapter1/10 + title: Quiz am Ende des Kapitels + quiz: 1 + +- title: 3. Fine-tuning von vortrainierten Modellen + sections: + - local: chapter3/1 + title: Einführung + - local: chapter3/2 + title: Datenbearbeitung + - local: chapter3/3 + title: Fine-tuning von Modellen mit der Trainer API oder Keras + local_fw: { pt: chapter3/3, tf: chapter3/3_tf } + - local: chapter3/4 + title: Komplettes Training + - local: chapter3/5 + title: Fine-tuning, Check! + - local: chapter3/6 + title: Quiz am Ende des Kapitels + quiz: 3 + +- title: 4. Teilen von Modellen und Tokenizers + sections: + - local: chapter4/1 + title: Der Hugging Face Hub + - local: chapter4/2 + title: Verwendung vortrainierter Modelle + - local: chapter4/3 + title: Vortrainierte Modelle teilen + - local: chapter4/4 + title: Erstellung einer Modellkarte ("model card") + - local: chapter4/5 + title: Teil 1 abgeschlossen! + - local: chapter4/6 + title: Quiz am Ende des Kapitels + quiz: 4 + +- title: Wörterverzeichnis + sections: + - local: glossary/1 + title: Wörterverzeichnis diff --git a/chapters/de/chapter0/1.mdx b/chapters/de/chapter0/1.mdx index 9b9fd8805..e9bddf15a 100644 --- a/chapters/de/chapter0/1.mdx +++ b/chapters/de/chapter0/1.mdx @@ -1,110 +1,110 @@ -# Einführung - -Willkommen zum Hugging-Face-Kurs! Die vorliegende Einführung wird dir dabei helfen, deine Arbeitsumgebung einzurichten. Wenn du den Kurs gerade erst beginnst, empfehlen wir dir, zuerst einen Überblick über [Kapitel 1](/course/chapter1) zu gewinnen und dann wieder hierher zurückzukommen und deine Umgebung einzurichten, damit du den Code selbst ausprobieren kannst. - -Alle Bibliotheken, die wir in diesem Kurs verwenden werden, sind als Python-Pakete verfügbar. Daher zeigen wir dir hier, wie du eine Python-Umgebung einrichtest und die benötigten Bibliotheken installierst. - -Wir stellen zwei verschiedene Möglichkeiten vor, wie du deine Arbeitsumgebung einrichten kannst: entweder über ein Colab-Notebook oder über eine virtuelle Python-Umgebung. Du kannst dich für die Variante entscheiden, die dir am meisten zusagt. Anfängern empfehlen wir dringend, mit einem Colab-Notebook zu beginnen. - -Wir werden nicht auf das Windows-System eingehen. Wenn du auf einem Windows-System arbeitest, empfehlen wir dir, ein Colab-Notebook zu verwenden. Wenn du eine Linux-Distribution oder macOS verwendest, kannst du beide der hier beschriebenen Ansätze nutzen. - -Für den Großteil des Kurses ist es erforderlich, dass du ein Konto bei Hugging Face hast. Wir raten dir, am besten gleich eines zu erstellen: [Konto erstellen](https://huggingface.co/join). - -## Verwendung eines Google-Colab-Notebooks - -Ein Colab-Notebook zu verwenden, ist die einfachste Lösung: Starte einfach ein Notebook in deinem Browser und fange direkt an zu programmieren! - -Falls du mit Colab noch nicht vertraut sein solltest, empfehlen wir dir, zunächst mit der [bereitstehenden Einführung](https://colab.research.google.com/notebooks/intro.ipynb) zu beginnen. Colab ermöglicht die Verwendung von beschleunigter Hardware, wie GPUs oder TPUs, und ist für kleinere Workloads kostenlos. - -Sobald du dich in Colab ausreichend zurechtfindest, kannst du ein neues Notebook anlegen und mit der Einrichtung beginnen: - -
-An empty colab notebook -
- -Im nächsten Schritt installieren wir die Bibliotheken, die wir in diesem Kurs verwenden werden. Für die Installation werden wir die Paketverwaltung für Python, `pip`, verwenden. Um Systembefehle in Notebooks ausführen zu können, musst du ihnen das Zeichen `!` voranstellen. Dementsprechend kannst du die 🤗 Transformers-Bibliothek wie folgt installieren: - -``` -!pip install transformers -``` - -Wenn du gleich sicherstellen möchtest, dass das Paket korrekt installiert wurde, kannst du es einfach in deiner Python-Laufzeitumgebung importieren: - -``` -import transformers -``` - -
-A gif showing the result of the two commands above: installation and import -
- -Damit wird eine sehr abgespeckte Version der 🤗 Transformers-Bibliothek installiert. Insbesondere werden keine spezifischen Frameworks für maschinelles Lernen (wie PyTorch oder TensorFlow) installiert. Da wir viele verschiedene Funktionen der Bibliothek verwenden werden, empfehlen wir die Installation der Entwicklungs- bzw. Development-Version, die alle erforderlichen Abhängigkeiten für so ziemlich jeden erdenklichen Anwendungsfall enthält: - -``` -!pip install transformers[sentencepiece] -``` - -Dies dauert zwar etwas länger, aber anschließend bist du bereit für den Rest des Kurses! - -## Verwendung einer virtuellen Python-Umgebung - -Wenn du lieber eine virtuelle Python-Umgebung verwenden möchtest, musst du zunächst Python auf deinem System installieren. Für den Anfang empfehlen wir [diese Anleitung](https://realpython.com/installing-python/). - -Sobald du Python installiert hast, solltest du in der Lage sein, Python-Befehle in deinem Terminal auszuführen. Zunächst kannst du den folgenden Befehl ausführen, um sicherzustellen, dass Python korrekt installiert ist, bevor du mit den nächsten Schritten fortfährst: `python --version`. Dies sollte die Python-Version ausgeben, die jetzt auf deinem System installiert ist. - -Wenn du einen Python-Befehl in deinem Terminal ausführst, z. B. `python --version`, solltest du das Programm, das deinen Befehl ausführt, als Hauptinstallation von Python auf deinem System betrachten. Wir empfehlen, diese Hauptinstallation frei von Paketen zu halten und für jede Anwendung, an der du arbeitest, eine eigene Umgebung zu erstellen. Auf diese Weise kann jede Anwendung ihre eigenen Abhängigkeiten und Pakete haben, und du musst dir keine Gedanken über mögliche Kompatibilitätsprobleme mit anderen Anwendungen machen. - -In Python wird dies mit [*virtuellen Umgebungen*](https://docs.python.org/3/tutorial/venv.html) bewerkstelligt. Das sind in sich geschlossene Verzeichnisbäume, die jeweils eine Python-Installation mit einer bestimmten Python-Version sowie alle Pakete enthalten, die die Anwendung benötigt. Eine solche virtuelle Umgebung kann mit verschiedenen Werkzeugen erstellt werden. Wir werden dafür auf das offizielle Python-Paket [`venv`](https://docs.python.org/3/library/venv.html#module-venv) zurückgreifen. - -Erstelle zunächst das Verzeichnis, in dem du deine Anwendung unterbringen möchtest - zum Beispiel könntest du ein neues Verzeichnis namens *transformers-course* als Unterverzeichnis deines Hauptverzeichnisses (*home*) anlegen: - -``` -mkdir ~/transformers-course -cd ~/transformers-course -``` - -Erstelle nun in diesem Verzeichnis mithilfe des Python-Moduls `venv` eine virtuelle Umgebung: - -``` -python -m venv .env -``` - -Du solltest jetzt ein Verzeichnis namens *.env* in deinem ansonsten leeren Ordner haben: - -``` -ls -a -``` - -```out -. .. .env -``` - -Mit den Skripten "activate" und "deactivate" kannst du in deine virtuelle Umgebung hinein- und herauswechseln: - -``` -# Aktivieren der virtuellen Umgebung -source .env/bin/activate - -# Deaktivieren der virtuellen Umgebung -deactivate -``` - -Du kannst dich vergewissern, dass die Umgebung aktiviert ist, indem du den Befehl `which python` ausführst: Wenn er auf die virtuelle Umgebung verweist, dann hast du sie erfolgreich aktiviert! - -``` -which python -``` - -```out -/home//transformers-course/.env/bin/python -``` - -### Installieren von Abhängigkeiten - -Wie im vorherigen Abschnitt zur Verwendung von Google-Colab-Instanzen musst du nun noch die Pakete installieren, die du zum Fortfahren benötigst. Auch hier empfehlen wir, die Entwicklungsversion von 🤗 Transformers mithilfe des Paketverwaltungsprogramm `pip` zu installieren: - -``` -pip install "transformers[sentencepiece]" -``` - -So, nun bist du startklar und kannst loslegen! +# Einführung + +Willkommen zum Hugging-Face-Kurs! Die vorliegende Einführung wird dir dabei helfen, deine Arbeitsumgebung einzurichten. Wenn du den Kurs gerade erst beginnst, empfehlen wir dir, zuerst einen Überblick über [Kapitel 1](/course/chapter1) zu gewinnen und dann wieder hierher zurückzukommen und deine Umgebung einzurichten, damit du den Code selbst ausprobieren kannst. + +Alle Bibliotheken, die wir in diesem Kurs verwenden werden, sind als Python-Pakete verfügbar. Daher zeigen wir dir hier, wie du eine Python-Umgebung einrichtest und die benötigten Bibliotheken installierst. + +Wir stellen zwei verschiedene Möglichkeiten vor, wie du deine Arbeitsumgebung einrichten kannst: entweder über ein Colab-Notebook oder über eine virtuelle Python-Umgebung. Du kannst dich für die Variante entscheiden, die dir am meisten zusagt. Anfängern empfehlen wir dringend, mit einem Colab-Notebook zu beginnen. + +Wir werden nicht auf das Windows-System eingehen. Wenn du auf einem Windows-System arbeitest, empfehlen wir dir, ein Colab-Notebook zu verwenden. Wenn du eine Linux-Distribution oder macOS verwendest, kannst du beide der hier beschriebenen Ansätze nutzen. + +Für den Großteil des Kurses ist es erforderlich, dass du ein Konto bei Hugging Face hast. Wir raten dir, am besten gleich eines zu erstellen: [Konto erstellen](https://huggingface.co/join). + +## Verwendung eines Google-Colab-Notebooks + +Ein Colab-Notebook zu verwenden, ist die einfachste Lösung: Starte einfach ein Notebook in deinem Browser und fange direkt an zu programmieren! + +Falls du mit Colab noch nicht vertraut sein solltest, empfehlen wir dir, zunächst mit der [bereitstehenden Einführung](https://colab.research.google.com/notebooks/intro.ipynb) zu beginnen. Colab ermöglicht die Verwendung von beschleunigter Hardware, wie GPUs oder TPUs, und ist für kleinere Workloads kostenlos. + +Sobald du dich in Colab ausreichend zurechtfindest, kannst du ein neues Notebook anlegen und mit der Einrichtung beginnen: + +
+An empty colab notebook +
+ +Im nächsten Schritt installieren wir die Bibliotheken, die wir in diesem Kurs verwenden werden. Für die Installation werden wir die Paketverwaltung für Python, `pip`, verwenden. Um Systembefehle in Notebooks ausführen zu können, musst du ihnen das Zeichen `!` voranstellen. Dementsprechend kannst du die 🤗 Transformers-Bibliothek wie folgt installieren: + +``` +!pip install transformers +``` + +Wenn du gleich sicherstellen möchtest, dass das Paket korrekt installiert wurde, kannst du es einfach in deiner Python-Laufzeitumgebung importieren: + +``` +import transformers +``` + +
+A gif showing the result of the two commands above: installation and import +
+ +Damit wird eine sehr abgespeckte Version der 🤗 Transformers-Bibliothek installiert. Insbesondere werden keine spezifischen Frameworks für maschinelles Lernen (wie PyTorch oder TensorFlow) installiert. Da wir viele verschiedene Funktionen der Bibliothek verwenden werden, empfehlen wir die Installation der Entwicklungs- bzw. Development-Version, die alle erforderlichen Abhängigkeiten für so ziemlich jeden erdenklichen Anwendungsfall enthält: + +``` +!pip install transformers[sentencepiece] +``` + +Dies dauert zwar etwas länger, aber anschließend bist du bereit für den Rest des Kurses! + +## Verwendung einer virtuellen Python-Umgebung + +Wenn du lieber eine virtuelle Python-Umgebung verwenden möchtest, musst du zunächst Python auf deinem System installieren. Für den Anfang empfehlen wir [diese Anleitung](https://realpython.com/installing-python/). + +Sobald du Python installiert hast, solltest du in der Lage sein, Python-Befehle in deinem Terminal auszuführen. Zunächst kannst du den folgenden Befehl ausführen, um sicherzustellen, dass Python korrekt installiert ist, bevor du mit den nächsten Schritten fortfährst: `python --version`. Dies sollte die Python-Version ausgeben, die jetzt auf deinem System installiert ist. + +Wenn du einen Python-Befehl in deinem Terminal ausführst, z. B. `python --version`, solltest du das Programm, das deinen Befehl ausführt, als Hauptinstallation von Python auf deinem System betrachten. Wir empfehlen, diese Hauptinstallation frei von Paketen zu halten und für jede Anwendung, an der du arbeitest, eine eigene Umgebung zu erstellen. Auf diese Weise kann jede Anwendung ihre eigenen Abhängigkeiten und Pakete haben, und du musst dir keine Gedanken über mögliche Kompatibilitätsprobleme mit anderen Anwendungen machen. + +In Python wird dies mit [*virtuellen Umgebungen*](https://docs.python.org/3/tutorial/venv.html) bewerkstelligt. Das sind in sich geschlossene Verzeichnisbäume, die jeweils eine Python-Installation mit einer bestimmten Python-Version sowie alle Pakete enthalten, die die Anwendung benötigt. Eine solche virtuelle Umgebung kann mit verschiedenen Werkzeugen erstellt werden. Wir werden dafür auf das offizielle Python-Paket [`venv`](https://docs.python.org/3/library/venv.html#module-venv) zurückgreifen. + +Erstelle zunächst das Verzeichnis, in dem du deine Anwendung unterbringen möchtest - zum Beispiel könntest du ein neues Verzeichnis namens *transformers-course* als Unterverzeichnis deines Hauptverzeichnisses (*home*) anlegen: + +``` +mkdir ~/transformers-course +cd ~/transformers-course +``` + +Erstelle nun in diesem Verzeichnis mithilfe des Python-Moduls `venv` eine virtuelle Umgebung: + +``` +python -m venv .env +``` + +Du solltest jetzt ein Verzeichnis namens *.env* in deinem ansonsten leeren Ordner haben: + +``` +ls -a +``` + +```out +. .. .env +``` + +Mit den Skripten "activate" und "deactivate" kannst du in deine virtuelle Umgebung hinein- und herauswechseln: + +``` +# Aktivieren der virtuellen Umgebung +source .env/bin/activate + +# Deaktivieren der virtuellen Umgebung +deactivate +``` + +Du kannst dich vergewissern, dass die Umgebung aktiviert ist, indem du den Befehl `which python` ausführst: Wenn er auf die virtuelle Umgebung verweist, dann hast du sie erfolgreich aktiviert! + +``` +which python +``` + +```out +/home//transformers-course/.env/bin/python +``` + +### Installieren von Abhängigkeiten + +Wie im vorherigen Abschnitt zur Verwendung von Google-Colab-Instanzen musst du nun noch die Pakete installieren, die du zum Fortfahren benötigst. Auch hier empfehlen wir, die Entwicklungsversion von 🤗 Transformers mithilfe des Paketverwaltungsprogramm `pip` zu installieren: + +``` +pip install "transformers[sentencepiece]" +``` + +So, nun bist du startklar und kannst loslegen! diff --git a/chapters/de/chapter1/1.mdx b/chapters/de/chapter1/1.mdx index 14e19601c..5213759c8 100644 --- a/chapters/de/chapter1/1.mdx +++ b/chapters/de/chapter1/1.mdx @@ -1,102 +1,102 @@ -# Einführung - - - -## Willkommen zum 🤗 Kurs! - - - -In diesem Kurs lernst du verschiedene Teilbereiche der maschinellen Verarbeitung natürlicher Sprache (engl. Natural Language Processing, NLP) - im Deutschen auch als Maschinelle Sprachverarbeitung oder Computerlinguistik (CL) bezeichnet - unter Verwendung der Bibliotheken des Ökosystems von [Hugging Face](https://huggingface.co/) kennen: die [🤗 Transformers-](https://github.com/huggingface/transformers), die [🤗 Datasets-](https://github.com/huggingface/datasets), die [🤗 Tokenizers-](https://github.com/huggingface/tokenizers) sowie die [🤗 Accelerate-Bibliotheken](https://github.com/huggingface/accelerate) als auch der [Hugging Face Hub](https://huggingface.co/models). Der Kurs ist komplett kostenlos und frei von Werbung. - - -## Was erwartet dich? - -Hier ein kurzer Überblick über den Kurs: - -
-Brief overview of the chapters of the course. - -
- -- Die Kapitel 1 bis 4 geben eine Einführung in die wichtigsten Konzepte der 🤗 Transformers-Bibliothek. Am Ende dieses Teils des Kurses wirst du mit der Funktionsweise von Transformer-Modellen vertraut sein und wissen, wie du ein Modell aus dem [Hugging Face Hub](https://huggingface.co/models) verwendest, es auf einem Datensatz feintunst und deine Ergebnisse mit anderen auf dem Hub teilst! -- In den Kapiteln 5 bis 8 lernst du die Grundlagen der 🤗 Datasets- und 🤗 Tokenizers-Bibliotheken kennen, bevor du in die typischen Problemstellungen des NLP eintauchst. Am Ende dieses Teils wirst du in der Lage sein, die gängisten Problemstellungen im NLP selbstständig zu lösen. -- Die Kapitel 9 bis 12 gehen über den Bereich des NLP hinaus und zeigen, wie Transformer-Modelle für Aufgaben bei der Verarbeitung gesprochener Sprache (engl. Speech Processing) und im Bereich Computer Vision (im Deutschen ungefähr mit computerbasiertem Sehen zu übersetzen) eingesetzt werden können. Nebenbei lernst du, wie du eigene Versionen deiner Modelle zu Demonstrationszwecken erstellen und sie mit anderen teilen kannst, und wie du sie für Produktionsumgebungen optimierst. Am Ende dieses Teils wirst du in der Lage sein, die 🤗 Transformers-Bibliothek auf (fast) jede Problemstellung, die dir im Bereich des Maschinellen Lernens begegnen, anzuwenden! - -Dieser Kurs: - -* Erfordert gute Kenntnisse in Python -* Sollte am besten nach einem Einführungskurs in Deep Learning gemacht werden, wie z. B. [fast.ai's Kurs](https://www.fast.ai/) [Practical Deep Learning for Coders](https://course.fast.ai/) oder eines der von [DeepLearning.AI](https://www.deeplearning.ai/) entwickelten Kursprogramme -* Setzt keine Vorkenntnisse in [PyTorch](https://pytorch.org/) oder [TensorFlow](https://www.tensorflow.org/) voraus, obwohl es hilfreich ist, wenn du bereits mit ihnen vertraut sein solltest. - -Nachdem du diesen Kurs abgeschlossen hast, empfehlen wir dir den [Spezialisierungskurs Natural Language Processing von DeepLearning.AI](https://www.coursera.org/specializations/natural-language-processing?utm_source=deeplearning-ai&utm_medium=institutions&utm_campaign=20211011-nlp-2-hugging_face-page-nlp-refresh), der eine breite Palette traditioneller NLP-Modelle wie Naive Bayes und LSTMs abdeckt, bei denen es sich lohnt, sich mit ihnen vertraut zu machen! - -## Wer sind wir? - -Über die Autorinnen und Autoren: - -**Matthew Carrigan** ist Machine Learning Engineer bei Hugging Face. Er lebt in der irischen Hauptstadt Dublin und hat zuvor als Machine Learning Engineer bei Parse.ly und als Post-Doktorand am Trinity College Dublin gearbeitet. Er glaubt nicht, dass wir eine künstliche allgemeine Intelligenz (engl. Artificial General Intelligence, AGI) durch eine zunehmende Skalierung bestehender Architekturen erreichen werden, hat aber dennoch die Hoffnung, dass Roboter auf dem Weg zur Unsterblichkeit sind. - -**Lysandre Debut** ist Machine Learning Engineer bei Hugging Face und arbeitet bereits seit Entstehung an der 🤗 Transformers-Bibliothek mit. Sein Ziel ist es, NLP für alle zugänglich zu machen, indem er Tools entwickelt, die eine sehr einfache API bieten. - -**Sylvain Gugger** ist Research Engineer bei Hugging Face und einer der Hauptverantwortlichen für die Pflege der 🤗 Transformers-Bibliothek. Zuvor war er Research Scientist bei fast.ai und hat zusammen mit Jeremy Howard das Buch _[Deep Learning for Coders with fastai and PyTorch](https://learning.oreilly.com/library/view/deep-learning-for/9781492045519/)_ verfasst. Seine Forschung ist darauf ausgerichtet, Deep Learning zugänglicher zu machen. Hierfür entwickelt und verbessert er Techniken, mit denen Modelle auch bei begrenzter Ressourcenausstattung auf schnelle Weise trainiert werden können. - -**Merve Noyan** ist Developer Advocate bei Hugging Face und arbeitet daran, Tools zu entwickeln und Inhalte zu erstellen, die Maschinelles Lernen für jeden zugänglich machen. - -**Lucile Saulnier** ist Machine Learning Engineer bei Hugging Face und entwickelt und unterstützt die Nutzung von Open-Source-Tools. Außerdem ist sie aktiv an vielen Forschungsprojekten im Bereich des NLP beteiligt, z. B. an kollaborativem Training und BigScience. - -**Lewis Tunstall** ist Machine Learning Engineer bei Hugging Face, und konzentriert sich darauf, Open-Source-Tools zu entwickeln und sie der breiten Community zugänglich zu machen. Zudem ist er Mitverfasser des O'Reilly-Buches [Natural Language Processing with Transformers](https://www.oreilly.com/library/view/natural-language-processing/9781098136789/). - -**Leandro von Werra** ist Machine Learning Engineer im Open-Source-Team von Hugging Face und ebenfalls einer der Autoren des O'Reilly-Buches [Natural Language Processing with Transformers](https://www.oreilly.com/library/view/natural-language-processing/9781098136789/). Er hat mehrere Jahre praktische Erfahrung darin gesammelt, NLP-Projekte in die Produktion zu bringen, und dabei den gesamten ML-Stack beackert. - -## Häufig gestellte Fragen (FAQ) - -Hier findest du einige Antworten auf häufig gestellte Fragen: - -- **Erhalte ich für die Teilnahme an diesem Kurs ein Zertifikat? -Derzeit gibt es für diesen Kurs noch kein Zertifikat. Wir arbeiten jedoch an einem Programm zur Erlangung eines Zertifikats für das Hugging-Face-Ökosystem - bleib' auf dem Laufenden! - -- **Wie viel Zeit sollte ich für diesen Kurs einplanen? -Jedes Kapitel dieses Kurses ist so konzipiert, dass es innerhalb einer Woche abgeschlossen werden kann, wenn du circa 6 bis 8 Stunden Arbeit einplanst. Du kannst dir jedoch so viel Zeit nehmen wie nötig. - -- **Wo kann ich Fragen stellen, wenn ich welche habe?** -Wenn du eine Frage zu einem Kursabschnitt hast, klicke einfach auf das sich oben auf der Seite befindende Banner "*Ask a question*" und du wirst automatisch zum entsprechenden Bereich des [Hugging-Face-Forums](https://discuss.huggingface.co/) weitergeleitet: - -Link to the Hugging Face forums - -Wenn du nach dem Kurs noch weiter üben möchtest, steht dir in den Foren eine Liste mit [Projektideen](https://discuss.huggingface.co/c/course/course-event/25) zur Verfügung. - -- **Wo finde ich den Code für den Kurs?** -In jedem Abschnitt kannst du auf das oben auf der Seite befindliche Banner klicken, um den Code entweder in Google Colab oder in Amazon SageMaker Studio Lab auszuführen: - -Link to the Hugging Face course notebooks - -Die Jupyter-Notebooks, die den gesamten Code des Kurses enthalten, befinden sich im [`huggingface/notebooks`-Repo](https://github.com/huggingface/notebooks). Wenn du sie lokal aufsetzen möchtest, schau dir die Anweisungen im [`course`-Repository](https://github.com/huggingface/course#-jupyter-notebooks) auf GitHub an. - - -- **Wie kann ich etwas zum Kurs beitragen?** -Es gibt mehrere Möglichkeiten, zum Kurs beizutragen! Wenn du einen Tippfehler oder einen Fehler entdeckst, eröffne bitte ein Issue in dem [`course`-Repository](https://github.com/huggingface/course). Wenn du uns dabei unterstützen möchtest, den Kurs in deine Muttersprache zu übersetzen, sieh dir bitte die [Anleitung](https://github.com/huggingface/course#translating-the-course-into-your-language) an. - -- **Welche Entscheidungen wurden bei den einzelnen Übersetzungen getroffen?** -Für jede Übersetzung gibt es ein Glossar und die Datei `TRANSLATING.txt`, in der die gewählten Fachtermini usw. festgehalten sind. Ein Beispiel für die deutsche Fassung findest du [hier](https://github.com/huggingface/course/blob/main/chapters/de/TRANSLATING.txt). - - -- **Kann ich diesen Kurs auch an anderer Stelle verwenden?** -Ja, natürlich! Der Kurs ist unter der permissiven [Apache-2-Lizenz](https://www.apache.org/licenses/LICENSE-2.0.html) veröffentlicht. Das bedeutet, dass du den Kurs in angemessener Weise erwähnen, einen Verweis zur Lizenz angeben und darauf hinweisen musst, wenn du Änderungen vorgenommen hast. Du kannst dies in jeder angemessenen Weise tun, allerdings nicht in einer Weise, die den Eindruck erweckt, dass der Lizenzgeber dich oder deine Nutzung unterstützt. Wenn du den Kurs zitieren möchtest, verwende bitte den folgenden BibTeX-Eintrag: - -``` -@misc{huggingfacecourse, - author = {Hugging Face}, - title = {The Hugging Face Course, 2022}, - howpublished = "\url{https://huggingface.co/course}", - year = {2022}, - note = "[Online; accessed ]" -} -``` - -Bist du bereit, loszulegen? In diesem Kapitel lernst du -* wie man die Funktion `pipeline()` benutzt, um computerlinguistische Aufgaben wie Textgenerierung und Klassifizierung zu lösen, -* mehr über die Transformer-Architektur und -* wie zwischen Encoder-, Decoder- und Encoder-Decoder-basierten Architekturen und -Anwendungsfällen unterschieden werden kann. +# Einführung + + + +## Willkommen zum 🤗 Kurs! + + + +In diesem Kurs lernst du verschiedene Teilbereiche der maschinellen Verarbeitung natürlicher Sprache (engl. Natural Language Processing, NLP) - im Deutschen auch als Maschinelle Sprachverarbeitung oder Computerlinguistik (CL) bezeichnet - unter Verwendung der Bibliotheken des Ökosystems von [Hugging Face](https://huggingface.co/) kennen: die [🤗 Transformers-](https://github.com/huggingface/transformers), die [🤗 Datasets-](https://github.com/huggingface/datasets), die [🤗 Tokenizers-](https://github.com/huggingface/tokenizers) sowie die [🤗 Accelerate-Bibliotheken](https://github.com/huggingface/accelerate) als auch der [Hugging Face Hub](https://huggingface.co/models). Der Kurs ist komplett kostenlos und frei von Werbung. + + +## Was erwartet dich? + +Hier ein kurzer Überblick über den Kurs: + +
+Brief overview of the chapters of the course. + +
+ +- Die Kapitel 1 bis 4 geben eine Einführung in die wichtigsten Konzepte der 🤗 Transformers-Bibliothek. Am Ende dieses Teils des Kurses wirst du mit der Funktionsweise von Transformer-Modellen vertraut sein und wissen, wie du ein Modell aus dem [Hugging Face Hub](https://huggingface.co/models) verwendest, es auf einem Datensatz feintunst und deine Ergebnisse mit anderen auf dem Hub teilst! +- In den Kapiteln 5 bis 8 lernst du die Grundlagen der 🤗 Datasets- und 🤗 Tokenizers-Bibliotheken kennen, bevor du in die typischen Problemstellungen des NLP eintauchst. Am Ende dieses Teils wirst du in der Lage sein, die gängisten Problemstellungen im NLP selbstständig zu lösen. +- Die Kapitel 9 bis 12 gehen über den Bereich des NLP hinaus und zeigen, wie Transformer-Modelle für Aufgaben bei der Verarbeitung gesprochener Sprache (engl. Speech Processing) und im Bereich Computer Vision (im Deutschen ungefähr mit computerbasiertem Sehen zu übersetzen) eingesetzt werden können. Nebenbei lernst du, wie du eigene Versionen deiner Modelle zu Demonstrationszwecken erstellen und sie mit anderen teilen kannst, und wie du sie für Produktionsumgebungen optimierst. Am Ende dieses Teils wirst du in der Lage sein, die 🤗 Transformers-Bibliothek auf (fast) jede Problemstellung, die dir im Bereich des Maschinellen Lernens begegnen, anzuwenden! + +Dieser Kurs: + +* Erfordert gute Kenntnisse in Python +* Sollte am besten nach einem Einführungskurs in Deep Learning gemacht werden, wie z. B. [fast.ai's Kurs](https://www.fast.ai/) [Practical Deep Learning for Coders](https://course.fast.ai/) oder eines der von [DeepLearning.AI](https://www.deeplearning.ai/) entwickelten Kursprogramme +* Setzt keine Vorkenntnisse in [PyTorch](https://pytorch.org/) oder [TensorFlow](https://www.tensorflow.org/) voraus, obwohl es hilfreich ist, wenn du bereits mit ihnen vertraut sein solltest. + +Nachdem du diesen Kurs abgeschlossen hast, empfehlen wir dir den [Spezialisierungskurs Natural Language Processing von DeepLearning.AI](https://www.coursera.org/specializations/natural-language-processing?utm_source=deeplearning-ai&utm_medium=institutions&utm_campaign=20211011-nlp-2-hugging_face-page-nlp-refresh), der eine breite Palette traditioneller NLP-Modelle wie Naive Bayes und LSTMs abdeckt, bei denen es sich lohnt, sich mit ihnen vertraut zu machen! + +## Wer sind wir? + +Über die Autorinnen und Autoren: + +**Matthew Carrigan** ist Machine Learning Engineer bei Hugging Face. Er lebt in der irischen Hauptstadt Dublin und hat zuvor als Machine Learning Engineer bei Parse.ly und als Post-Doktorand am Trinity College Dublin gearbeitet. Er glaubt nicht, dass wir eine künstliche allgemeine Intelligenz (engl. Artificial General Intelligence, AGI) durch eine zunehmende Skalierung bestehender Architekturen erreichen werden, hat aber dennoch die Hoffnung, dass Roboter auf dem Weg zur Unsterblichkeit sind. + +**Lysandre Debut** ist Machine Learning Engineer bei Hugging Face und arbeitet bereits seit Entstehung an der 🤗 Transformers-Bibliothek mit. Sein Ziel ist es, NLP für alle zugänglich zu machen, indem er Tools entwickelt, die eine sehr einfache API bieten. + +**Sylvain Gugger** ist Research Engineer bei Hugging Face und einer der Hauptverantwortlichen für die Pflege der 🤗 Transformers-Bibliothek. Zuvor war er Research Scientist bei fast.ai und hat zusammen mit Jeremy Howard das Buch _[Deep Learning for Coders with fastai and PyTorch](https://learning.oreilly.com/library/view/deep-learning-for/9781492045519/)_ verfasst. Seine Forschung ist darauf ausgerichtet, Deep Learning zugänglicher zu machen. Hierfür entwickelt und verbessert er Techniken, mit denen Modelle auch bei begrenzter Ressourcenausstattung auf schnelle Weise trainiert werden können. + +**Merve Noyan** ist Developer Advocate bei Hugging Face und arbeitet daran, Tools zu entwickeln und Inhalte zu erstellen, die Maschinelles Lernen für jeden zugänglich machen. + +**Lucile Saulnier** ist Machine Learning Engineer bei Hugging Face und entwickelt und unterstützt die Nutzung von Open-Source-Tools. Außerdem ist sie aktiv an vielen Forschungsprojekten im Bereich des NLP beteiligt, z. B. an kollaborativem Training und BigScience. + +**Lewis Tunstall** ist Machine Learning Engineer bei Hugging Face, und konzentriert sich darauf, Open-Source-Tools zu entwickeln und sie der breiten Community zugänglich zu machen. Zudem ist er Mitverfasser des O'Reilly-Buches [Natural Language Processing with Transformers](https://www.oreilly.com/library/view/natural-language-processing/9781098136789/). + +**Leandro von Werra** ist Machine Learning Engineer im Open-Source-Team von Hugging Face und ebenfalls einer der Autoren des O'Reilly-Buches [Natural Language Processing with Transformers](https://www.oreilly.com/library/view/natural-language-processing/9781098136789/). Er hat mehrere Jahre praktische Erfahrung darin gesammelt, NLP-Projekte in die Produktion zu bringen, und dabei den gesamten ML-Stack beackert. + +## Häufig gestellte Fragen (FAQ) + +Hier findest du einige Antworten auf häufig gestellte Fragen: + +- **Erhalte ich für die Teilnahme an diesem Kurs ein Zertifikat? +Derzeit gibt es für diesen Kurs noch kein Zertifikat. Wir arbeiten jedoch an einem Programm zur Erlangung eines Zertifikats für das Hugging-Face-Ökosystem - bleib' auf dem Laufenden! + +- **Wie viel Zeit sollte ich für diesen Kurs einplanen? +Jedes Kapitel dieses Kurses ist so konzipiert, dass es innerhalb einer Woche abgeschlossen werden kann, wenn du circa 6 bis 8 Stunden Arbeit einplanst. Du kannst dir jedoch so viel Zeit nehmen wie nötig. + +- **Wo kann ich Fragen stellen, wenn ich welche habe?** +Wenn du eine Frage zu einem Kursabschnitt hast, klicke einfach auf das sich oben auf der Seite befindende Banner "*Ask a question*" und du wirst automatisch zum entsprechenden Bereich des [Hugging-Face-Forums](https://discuss.huggingface.co/) weitergeleitet: + +Link to the Hugging Face forums + +Wenn du nach dem Kurs noch weiter üben möchtest, steht dir in den Foren eine Liste mit [Projektideen](https://discuss.huggingface.co/c/course/course-event/25) zur Verfügung. + +- **Wo finde ich den Code für den Kurs?** +In jedem Abschnitt kannst du auf das oben auf der Seite befindliche Banner klicken, um den Code entweder in Google Colab oder in Amazon SageMaker Studio Lab auszuführen: + +Link to the Hugging Face course notebooks + +Die Jupyter-Notebooks, die den gesamten Code des Kurses enthalten, befinden sich im [`huggingface/notebooks`-Repo](https://github.com/huggingface/notebooks). Wenn du sie lokal aufsetzen möchtest, schau dir die Anweisungen im [`course`-Repository](https://github.com/huggingface/course#-jupyter-notebooks) auf GitHub an. + + +- **Wie kann ich etwas zum Kurs beitragen?** +Es gibt mehrere Möglichkeiten, zum Kurs beizutragen! Wenn du einen Tippfehler oder einen Fehler entdeckst, eröffne bitte ein Issue in dem [`course`-Repository](https://github.com/huggingface/course). Wenn du uns dabei unterstützen möchtest, den Kurs in deine Muttersprache zu übersetzen, sieh dir bitte die [Anleitung](https://github.com/huggingface/course#translating-the-course-into-your-language) an. + +- **Welche Entscheidungen wurden bei den einzelnen Übersetzungen getroffen?** +Für jede Übersetzung gibt es ein Glossar und die Datei `TRANSLATING.txt`, in der die gewählten Fachtermini usw. festgehalten sind. Ein Beispiel für die deutsche Fassung findest du [hier](https://github.com/huggingface/course/blob/main/chapters/de/TRANSLATING.txt). + + +- **Kann ich diesen Kurs auch an anderer Stelle verwenden?** +Ja, natürlich! Der Kurs ist unter der permissiven [Apache-2-Lizenz](https://www.apache.org/licenses/LICENSE-2.0.html) veröffentlicht. Das bedeutet, dass du den Kurs in angemessener Weise erwähnen, einen Verweis zur Lizenz angeben und darauf hinweisen musst, wenn du Änderungen vorgenommen hast. Du kannst dies in jeder angemessenen Weise tun, allerdings nicht in einer Weise, die den Eindruck erweckt, dass der Lizenzgeber dich oder deine Nutzung unterstützt. Wenn du den Kurs zitieren möchtest, verwende bitte den folgenden BibTeX-Eintrag: + +``` +@misc{huggingfacecourse, + author = {Hugging Face}, + title = {The Hugging Face Course, 2022}, + howpublished = "\url{https://huggingface.co/course}", + year = {2022}, + note = "[Online; accessed ]" +} +``` + +Bist du bereit, loszulegen? In diesem Kapitel lernst du +* wie man die Funktion `pipeline()` benutzt, um computerlinguistische Aufgaben wie Textgenerierung und Klassifizierung zu lösen, +* mehr über die Transformer-Architektur und +* wie zwischen Encoder-, Decoder- und Encoder-Decoder-basierten Architekturen und -Anwendungsfällen unterschieden werden kann. diff --git a/chapters/de/chapter1/10.mdx b/chapters/de/chapter1/10.mdx index c6102e63e..977ec0b5f 100644 --- a/chapters/de/chapter1/10.mdx +++ b/chapters/de/chapter1/10.mdx @@ -1,260 +1,260 @@ - - - - - -# Quiz am Ende des Kapitels - -In diesem Kapitel hast du viel gelernt! Mach dir keine Sorgen, wenn du noch nicht alle Einzelheiten verstanden hast. In den nächsten Kapiteln wirst du mehr darüber erfahren, wie die Dinge im Einzelnen funktionieren. - -Doch zuerst wollen wir noch testen, was du in diesem Kapitel gelernt hast! - - -### 1. Erkunde den Hub und suche nach dem Checkpoint `roberta-large-mnli`. Welche Aufgabe unterstützt er? - - -roberta-large-mnli nach." - }, - { - text: "Text Classification (Textklassifizierung)", - explain: "Genauer gesagt, wird klassifiziert, ob zwei Sätze hinsichtlich dreier Labels (Widerspruch (engl. Contradiction), Neutral, Konsequenz (engl. Entailment)) logisch miteinander verbunden sind - eine Aufgabe, die auch als Natural Language Inference bezeichnet wird.", - correct: true - }, - { - text: "Text Generation (Textgenerierung)", - explain: "Sieh nochmal auf der Seite des Modells roberta-large-mnli nach." - } - ]} -/> - -### 2. Was gibt der folgende Code zurück? - -```py -from transformers import pipeline - -ner = pipeline("ner", aggregation_strategy="simple") -ner("My name is Sylvain and I work at Hugging Face in Brooklyn.") -``` - -sentiment-analysis-Pipeline verwenden." - }, - { - text: "Er wird einen generierten Text zurückgeben, der diesen Satz vervollständigt.", - explain: "Das ist nicht richtig - dafür müsstest du eine text-generation-Pipeline verwenden.", - }, - { - text: "Er gibt Begriffe zurück, die für Personen, Organisationen oder Orte stehen.", - explain: "Außerdem werden mit aggregation_strategy="simple" die Wörter, die zur selben Entität gehören, gruppiert, wie z. B. \"Hugging Face\".", - correct: true - } - ]} -/> - -### 3. Wodurch müsste ... in diesem Codebeispiel ersetzt werden? - -```py -from transformers import pipeline - -filler = pipeline("fill-mask", model="bert-base-cased") -result = filler("...") -``` - - has been waiting for you.", - explain: "Das stimmt nicht. Schau dir die bert-base-cased-Übersichtsseite des Modells an und versuche, deinen Fehler zu entdecken." - }, - { - text: "This [MASK] has been waiting for you.", - explain: "Richtig! Der Mask Token dieses Modells ist [MASK].", - correct: true - }, - { - text: "This man has been waiting for you.", - explain: "Leider falsch. Diese Pipeline füllt maskierte Wörter auf, also braucht sie irgendwo einen Mask Token." - } - ]} -/> - -### 4. Warum wird dieser Code nicht funktionieren? - -```py -from transformers import pipeline - -classifier = pipeline("zero-shot-classification") -result = classifier("This is a course about the Transformers library") -``` - -candidate_labels=[...] enthalten.", - correct: true - }, - { - text: "Diese Pipeline erfordert mehrere Sätze, nicht nur einen.", - explain: "Das ist falsch - obwohl diese Pipeline, wenn sie korrekt verwendet wird, eine Liste von Sätzen verarbeiten kann (wie alle anderen Pipelines)." - }, - { - text: "Die 🤗 Transformers-Bibliothek funktioniert wie immer nicht.", - explain: "Zu dieser Antwort erübrigt sich jeder Kommentar!" - }, - { - text: "Diese Pipeline erfordert längere Inputs; diese hier sind zu kurz.", - explain: "Das ist falsch. Übrigens wird ein sehr langer Text bei der Verarbeitung durch diese Pipeline gestutzt (engl. truncated) bzw. gekürzt." - } - ]} -/> - -### 5. Was bedeutet der Begriff "Transfer Learning"? - - - -### 6. Richtig oder falsch? Ein Sprachmodell benötigt im Rahmen des Pretraining in der Regel keine Labels. - - -selbstüberwacht (engl. self-supervised), d. h. die Labels werden automatisch aus den Inputs erstellt (wie z. B. die Vorhersage des nächsten Wortes oder das Auffüllen einiger maskierter Wörter).", - correct: true - }, - { - text: "Falsch", - explain: "Das ist nicht die richtige Antwort." - } - ]} -/> - -### 7. Wähle den Satz aus, der die Begriffe "Modell", "Architektur" und "Gewichte" bzw. "Gewichtung" am besten beschreibt. - - - - -### 8. Welche dieser Modelle würdest du nutzen, um einen Prompt bzw. Text-Input durch einen generierten Text vervollständigen zu lassen? - - - -### 9. Welche dieser Modelle würdest du für die Zusammenfassung von Texten verwenden? - - - -### 10. Welche Art von Modellen würdest du verwenden, um Text-Inputs entsprechend bestimmter Labels zu klassifizieren? - - - -### 11. Welche mögliche Ursache kann eine vom Modell zu beobachtende Voreingenommenheit (Bias) haben? - - + + + + + +# Quiz am Ende des Kapitels + +In diesem Kapitel hast du viel gelernt! Mach dir keine Sorgen, wenn du noch nicht alle Einzelheiten verstanden hast. In den nächsten Kapiteln wirst du mehr darüber erfahren, wie die Dinge im Einzelnen funktionieren. + +Doch zuerst wollen wir noch testen, was du in diesem Kapitel gelernt hast! + + +### 1. Erkunde den Hub und suche nach dem Checkpoint `roberta-large-mnli`. Welche Aufgabe unterstützt er? + + +roberta-large-mnli nach." + }, + { + text: "Text Classification (Textklassifizierung)", + explain: "Genauer gesagt, wird klassifiziert, ob zwei Sätze hinsichtlich dreier Labels (Widerspruch (engl. Contradiction), Neutral, Konsequenz (engl. Entailment)) logisch miteinander verbunden sind - eine Aufgabe, die auch als Natural Language Inference bezeichnet wird.", + correct: true + }, + { + text: "Text Generation (Textgenerierung)", + explain: "Sieh nochmal auf der Seite des Modells roberta-large-mnli nach." + } + ]} +/> + +### 2. Was gibt der folgende Code zurück? + +```py +from transformers import pipeline + +ner = pipeline("ner", aggregation_strategy="simple") +ner("My name is Sylvain and I work at Hugging Face in Brooklyn.") +``` + +sentiment-analysis-Pipeline verwenden." + }, + { + text: "Er wird einen generierten Text zurückgeben, der diesen Satz vervollständigt.", + explain: "Das ist nicht richtig - dafür müsstest du eine text-generation-Pipeline verwenden.", + }, + { + text: "Er gibt Begriffe zurück, die für Personen, Organisationen oder Orte stehen.", + explain: "Außerdem werden mit aggregation_strategy="simple" die Wörter, die zur selben Entität gehören, gruppiert, wie z. B. \"Hugging Face\".", + correct: true + } + ]} +/> + +### 3. Wodurch müsste ... in diesem Codebeispiel ersetzt werden? + +```py +from transformers import pipeline + +filler = pipeline("fill-mask", model="bert-base-cased") +result = filler("...") +``` + + has been waiting for you.", + explain: "Das stimmt nicht. Schau dir die bert-base-cased-Übersichtsseite des Modells an und versuche, deinen Fehler zu entdecken." + }, + { + text: "This [MASK] has been waiting for you.", + explain: "Richtig! Der Mask Token dieses Modells ist [MASK].", + correct: true + }, + { + text: "This man has been waiting for you.", + explain: "Leider falsch. Diese Pipeline füllt maskierte Wörter auf, also braucht sie irgendwo einen Mask Token." + } + ]} +/> + +### 4. Warum wird dieser Code nicht funktionieren? + +```py +from transformers import pipeline + +classifier = pipeline("zero-shot-classification") +result = classifier("This is a course about the Transformers library") +``` + +candidate_labels=[...] enthalten.", + correct: true + }, + { + text: "Diese Pipeline erfordert mehrere Sätze, nicht nur einen.", + explain: "Das ist falsch - obwohl diese Pipeline, wenn sie korrekt verwendet wird, eine Liste von Sätzen verarbeiten kann (wie alle anderen Pipelines)." + }, + { + text: "Die 🤗 Transformers-Bibliothek funktioniert wie immer nicht.", + explain: "Zu dieser Antwort erübrigt sich jeder Kommentar!" + }, + { + text: "Diese Pipeline erfordert längere Inputs; diese hier sind zu kurz.", + explain: "Das ist falsch. Übrigens wird ein sehr langer Text bei der Verarbeitung durch diese Pipeline gestutzt (engl. truncated) bzw. gekürzt." + } + ]} +/> + +### 5. Was bedeutet der Begriff "Transfer Learning"? + + + +### 6. Richtig oder falsch? Ein Sprachmodell benötigt im Rahmen des Pretraining in der Regel keine Labels. + + +selbstüberwacht (engl. self-supervised), d. h. die Labels werden automatisch aus den Inputs erstellt (wie z. B. die Vorhersage des nächsten Wortes oder das Auffüllen einiger maskierter Wörter).", + correct: true + }, + { + text: "Falsch", + explain: "Das ist nicht die richtige Antwort." + } + ]} +/> + +### 7. Wähle den Satz aus, der die Begriffe "Modell", "Architektur" und "Gewichte" bzw. "Gewichtung" am besten beschreibt. + + + + +### 8. Welche dieser Modelle würdest du nutzen, um einen Prompt bzw. Text-Input durch einen generierten Text vervollständigen zu lassen? + + + +### 9. Welche dieser Modelle würdest du für die Zusammenfassung von Texten verwenden? + + + +### 10. Welche Art von Modellen würdest du verwenden, um Text-Inputs entsprechend bestimmter Labels zu klassifizieren? + + + +### 11. Welche mögliche Ursache kann eine vom Modell zu beobachtende Voreingenommenheit (Bias) haben? + + diff --git a/chapters/de/chapter1/2.mdx b/chapters/de/chapter1/2.mdx index 9f36f8315..99a9d7e9f 100644 --- a/chapters/de/chapter1/2.mdx +++ b/chapters/de/chapter1/2.mdx @@ -1,26 +1,26 @@ -# Computerlinguistik - - - -Bevor wir uns mit Transformer-Modellen beschäftigen, wollen wir dir einen kurzen Überblick darüber geben, was Computerlinguistik (engl. Natural Language Processing, NLP) ist und welche Gründe es gibt, sich damit zu befassen. - -## Was ist Computerlinguistik (CL)? - -CL ist ein Bereich der Linguistik und des Maschinellen Lernens (engl. Machine Learning, ML), der sich darauf konzentriert, alle mit menschlicher Sprache zusammenhängenden Dinge zu verstehen. Das Ziel bei CL-Aufgabenstellungen (engl. Tasks) ist es, nicht nur einzelne Wörter zu verstehen, sondern auch den Kontext dieser Wörter zu erfassen. - -Im Folgenden findest du eine Liste der häufigsten CL-Aufgabenstellungen mit jeweils einigen Beispielen: - -- **Ganze Sätze klassifizieren**: Die mit einer bestimmten Bewertung verbundene Stimmungslage ermitteln, erkennen, ob eine E-Mail Spam ist, bestimmen, ob ein Satz grammatikalisch korrekt ist oder ob zwei Sätze logisch zusammenhängen oder nicht -- **Jedes einzelne Wort in einem Satz klassifizieren**: Identifizieren der grammatikalischen Bestandteile eines Satzes (Substantiv, Verb, Adjektiv) oder der benannten Entitäten (Person, Ort, Organisation) (engl. Named Entities) -- **Generieren von Textinhalten**: Einen Prompt durch einen automatisch generierten Text vervollständigen oder Lücken in einem Text auffüllen, in dem einzelne Wörter maskiert sind -- **Eine Antwort aus einem Text extrahieren**: Auf Basis einer Frage und eines gegebenen Kontexts die Antwort auf die Frage anhand der im Kontext enthaltenen Informationen extrahieren -- **Generieren eines neuen Satzes auf Basis eines Input-Textes**: Einen Text in eine andere Sprache automatisch übersetzen, Zusammenfassen eines Textes - -Die Computerlinguistik ist jedoch nicht nur auf die Verarbeitung geschriebener Texte beschränkt. Sie stellt sich auch komplexen Herausforderungen in den Bereichen der Spracherkennung (engl. Speech Recognition) und Computer Vision, wie z. B. ein Transkript einer Audioaufnahme zu erstellen oder ein Bild zu beschreiben. - -## Warum ist Computerlinguistik so schwierig? - -Computer verarbeiten Informationen nicht auf die gleiche Weise wie Menschen. Wenn wir zum Beispiel den Satz "Ich bin hungrig" lesen, können wir seine Bedeutung leicht erfassen. Genauso können wir bei zwei Sätzen wie "Ich habe Hunger" und "Ich bin traurig" leicht feststellen, wie ähnlich sie sind. Für ML-Modelle sind solche Aufgaben schwieriger zu lösen. Der Text muss erst so verarbeitet werden, dass das Modell in der Lage ist, daraus zu lernen. Und weil Sprache komplex ist, müssen wir uns genau überlegen, wie diese Verarbeitung erfolgen sollte. Es wurde eine rege Forschung dazu betrieben, wie Texte repräsentiert werden können. Einige dieser Methoden werden wir uns im nächsten Kapitel ansehen. +# Computerlinguistik + + + +Bevor wir uns mit Transformer-Modellen beschäftigen, wollen wir dir einen kurzen Überblick darüber geben, was Computerlinguistik (engl. Natural Language Processing, NLP) ist und welche Gründe es gibt, sich damit zu befassen. + +## Was ist Computerlinguistik (CL)? + +CL ist ein Bereich der Linguistik und des Maschinellen Lernens (engl. Machine Learning, ML), der sich darauf konzentriert, alle mit menschlicher Sprache zusammenhängenden Dinge zu verstehen. Das Ziel bei CL-Aufgabenstellungen (engl. Tasks) ist es, nicht nur einzelne Wörter zu verstehen, sondern auch den Kontext dieser Wörter zu erfassen. + +Im Folgenden findest du eine Liste der häufigsten CL-Aufgabenstellungen mit jeweils einigen Beispielen: + +- **Ganze Sätze klassifizieren**: Die mit einer bestimmten Bewertung verbundene Stimmungslage ermitteln, erkennen, ob eine E-Mail Spam ist, bestimmen, ob ein Satz grammatikalisch korrekt ist oder ob zwei Sätze logisch zusammenhängen oder nicht +- **Jedes einzelne Wort in einem Satz klassifizieren**: Identifizieren der grammatikalischen Bestandteile eines Satzes (Substantiv, Verb, Adjektiv) oder der benannten Entitäten (Person, Ort, Organisation) (engl. Named Entities) +- **Generieren von Textinhalten**: Einen Prompt durch einen automatisch generierten Text vervollständigen oder Lücken in einem Text auffüllen, in dem einzelne Wörter maskiert sind +- **Eine Antwort aus einem Text extrahieren**: Auf Basis einer Frage und eines gegebenen Kontexts die Antwort auf die Frage anhand der im Kontext enthaltenen Informationen extrahieren +- **Generieren eines neuen Satzes auf Basis eines Input-Textes**: Einen Text in eine andere Sprache automatisch übersetzen, Zusammenfassen eines Textes + +Die Computerlinguistik ist jedoch nicht nur auf die Verarbeitung geschriebener Texte beschränkt. Sie stellt sich auch komplexen Herausforderungen in den Bereichen der Spracherkennung (engl. Speech Recognition) und Computer Vision, wie z. B. ein Transkript einer Audioaufnahme zu erstellen oder ein Bild zu beschreiben. + +## Warum ist Computerlinguistik so schwierig? + +Computer verarbeiten Informationen nicht auf die gleiche Weise wie Menschen. Wenn wir zum Beispiel den Satz "Ich bin hungrig" lesen, können wir seine Bedeutung leicht erfassen. Genauso können wir bei zwei Sätzen wie "Ich habe Hunger" und "Ich bin traurig" leicht feststellen, wie ähnlich sie sind. Für ML-Modelle sind solche Aufgaben schwieriger zu lösen. Der Text muss erst so verarbeitet werden, dass das Modell in der Lage ist, daraus zu lernen. Und weil Sprache komplex ist, müssen wir uns genau überlegen, wie diese Verarbeitung erfolgen sollte. Es wurde eine rege Forschung dazu betrieben, wie Texte repräsentiert werden können. Einige dieser Methoden werden wir uns im nächsten Kapitel ansehen. diff --git a/chapters/de/chapter1/3.mdx b/chapters/de/chapter1/3.mdx index 1e2c509d5..f3df13086 100644 --- a/chapters/de/chapter1/3.mdx +++ b/chapters/de/chapter1/3.mdx @@ -249,8 +249,7 @@ Bei der automatischen Textzusammenfassung (engl. Summarization) geht es darum, e from transformers import pipeline summarizer = pipeline("summarization") -summarizer( - """ +summarizer(""" America has changed dramatically during recent years. Not only has the number of graduates in traditional engineering disciplines such as mechanical, civil, electrical, chemical, and aeronautical engineering declined, but in most of @@ -269,8 +268,7 @@ summarizer( Other industrial countries at minimum maintain their output, while America suffers an increasingly serious decline in the number of engineering graduates and a lack of well-educated engineers. -""" -) +""") ``` ```python out diff --git a/chapters/de/chapter1/4.mdx b/chapters/de/chapter1/4.mdx index c9641aa31..006248ba1 100644 --- a/chapters/de/chapter1/4.mdx +++ b/chapters/de/chapter1/4.mdx @@ -1,176 +1,176 @@ -# Wie funktionieren Transformer-Modelle? - - - -In diesem Abschnitt werfen wir einen Blick auf die Architektur von Transformer-Modellen. - -## Kurz zur Entwicklungsgeschichte der Transformer-Modelle - -Hier sind einige wichtige Meilensteine in der (kurzen) Geschichte der Transformer-Modelle: - -
-A brief chronology of Transformers models. - -
- -Die [Transformer-Architektur](https://arxiv.org/abs/1706.03762) wurde erstmals im Juni 2017 veröffentlicht. Der Schwerpunkt der ursprünglichen Forschung lag auf Übersetzungsaufgaben. In der Folge wurden mehrere einflussreiche Modelle veröffentlicht, darunter: - -- **Juni 2018**: [GPT](https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf), das erste vortrainierte Transformer-Modell, wurde zum Feintuning für verschiedene CL-Aufgaben eingesetzt und erzielte Ergebnisse, die dem neuesten Stand der Technik entsprachen. - -- **Oktober 2018**: [BERT](https://arxiv.org/abs/1810.04805), ein weiteres großes vortrainiertes Modell, das dazu dient, bessere Zusammenfassungen von Sätzen zu erstellen (mehr dazu im nächsten Kapitel!) - -- **Februar 2019**: [GPT-2](https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf), eine verbesserte (und größere) Version von GPT, die aus ethischen Erwägungen nicht sofort veröffentlicht wurde - -- **Oktober 2019**: [DistilBERT](https://arxiv.org/abs/1910.01108), eine abgespeckte Version von BERT, die 60 % schneller ist, 40 % weniger Speicherplatz benötigt und dennoch 97 % der Leistung von BERT erreicht - -- **Oktober 2019**: [BART](https://arxiv.org/abs/1910.13461) und [T5](https://arxiv.org/abs/1910.10683), zwei große vortrainierte Modelle, die dieselbe Architektur wie das ursprüngliche Transformer-Modell verwenden (die ersten, die dies getan haben) - -- **Mai 2020**, [GPT-3](https://arxiv.org/abs/2005.14165), eine noch größere Version von GPT-2, die in der Lage ist, bei einer Vielzahl von Aufgabenstellungen gute Leistungen zu erbringen, ohne dass ein Feintuning erforderlich ist (auch _Zero-Shot Learning_ genannt) - -Diese Auflistung ist bei weitem nicht vollständig und soll nur einige der verschiedenen Arten von Transformer-Modellen aufzeigen. Sie lassen sich grob in drei Kategorien einteilen: - -- GPT-ähnliche (auch _autoregressive_-Transformer-Modelle genannt) -- BERT-ähnliche (auch _Auto-Encoding_-Transformer-Modelle genannt) -- BART-/T5-ähnliche (auch _Sequence-to-Sequence_-Transformer-Modelle genannt) - -Wir werden uns mit diesen unterschiedlichen Modellfamilien später noch eingehender beschäftigen. - -## Transformer-Modelle sind Sprachmodelle - -Alle oben genannten Transformer-Modelle (GPT, BERT, BART, T5, etc.) wurden als *Sprachmodelle* (engl. Language Models) trainiert. Das bedeutet, dass sie mit großen Mengen an Rohtext auf selbstüberwachte (engl. self-supervised) Weise trainiert wurden. Selbstüberwachtes Lernen ist eine Form des Trainings, bei der die vorherzusagende Variable, die sog. Zielvariable (engl. Target), automatisch aus den Inputs des Modells berechnet wird. Das bedeutet, dass kein menschliches Zutun nötig ist, um die Daten zu labeln! - -Diese Art von Modell entwickelt ein statistisches Verständnis der Sprache, auf die es trainiert wurde, ist aber für spezifische praktische Aufgaben nicht sehr nützlich. Aus diesem Grund durchläuft das allgemeine, vortrainierte Modell ein Vorgang namens *Transfer Learning*. Während dieses Vorgangs wird das Modell unter Überwachung - d. h. mit Hilfe von durch Menschen bereitgestellte Labels - für eine bestimmte Aufgabe feingetunt. - -Ein Beispiel für eine Aufgabe ist die Vorhersage des nächsten Wortes in einem Satz, nachdem man die *n* vorherigen Wörter gelesen hat. Dies nennt sich *kausale Sprachmodellierung* (engl. Causal Language Modeling), da der Output von den vergangenen und aktuellen Inputs abhängt, aber nicht von den zukünftigen. - -
-Example of causal language modeling in which the next word from a sentence is predicted. - -
- -Ein weiteres Beispiel ist die *maskierte Sprachmodellierung* (engl. Masked Language Modeling), bei der das Modell ein Wort im Satz, das maskiert ist, vorhersagt. - -
-Example of masked language modeling in which a masked word from a sentence is predicted. - -
- -## Transformer-Modelle sind groß - -Abgesehen von einigen wenigen Ausreißern (wie DistilBERT) besteht die allgemeine Strategie, um eine bessere Leistung zu erzielen, darin, die Modelle zu vergrößern und die Menge an Daten zu erhöhen, auf denen sie vortrainiert werden. - -
-Number of parameters of recent Transformers models -
- -Leider erfordert das Training eines Modells, insbesondere eines großen, eine große Menge an Daten. Das ist sehr kostspielig in Bezug auf Zeit und Rechenleistung. Es hat sogar Auswirkungen auf die Umwelt, wie in der folgenden Grafik zu sehen ist. - -
-The carbon footprint of a large language model. - -
- - - -Hier ist ein Projekt zu sehen, bei dem ein Team gezielt versucht, die Umweltauswirkungen des Pretrainings (sehr großer) Modelle zu reduzieren. Wenn man die vielen Versuche berücksichtigt, die dazu nötig sind, die besten Hyperparameter zu finden, wären die zu bemessenden ökologischen Konsequenzen noch größer. - -Stell dir vor, dass jedes Mal, wenn ein Forschungsteam, eine Bildungseinrichtung oder ein Unternehmen ein Modell trainieren möchte, dies von Grund auf tun müsste. Das würde zu enormen, unnötigen globalen Kosten führen! - -Deshalb ist die gemeinsame Nutzung von Sprachmodellen von größter Bedeutung: trainierte Gewichtungen gemeinsam zu nutzen und auf bereits trainierten Gewichtungen aufzubauen, reduziert die gesamten Rechenkosten und den CO2-Fußabdruck der Community. - - -## Transfer Learning - - - -Beim *Pretraining* wird ein Modell von Grund auf neu trainiert: Die Gewichte werden nach dem Zufallsprinzip initialisiert und das Training beginnt ohne jegliches Vorwissen. - -
-The pretraining of a language model is costly in both time and money. - -
- -Dieses Pretraining wird normalerweise mit sehr großen Datenmengen durchgeführt. Daher wird ein sehr großer Korpus an Daten benötigt und das Training kann mehrere Wochen in Anspruch nehmen. - -*Feintuning* ist hingegen das Training, das **nach** dem Pretraining eines Modells durchgeführt wird. Für das Feintuning nimmst du zunächst ein vortrainiertes Sprachmodell und trainierst es dann mit einem aufgabenspezifischen Datensatz nach. Moment - warum trainierst du das Modell nicht gleich für die endgültige Aufgabe? Dafür gibt es mehrere Gründe: - -* Das vortrainierte Modell wurde bereits auf einem Datensatz trainiert, der einige Ähnlichkeiten mit dem Datensatz, der für das Feintuning verwendet wird, aufweist. Beim Feintuning kann also von dem Wissen profitiert werden, das das ursprüngliche Modell während des Pretrainings erlangt hat (bei CL-Problemstellungen verfügt das vortrainierte Modell zum Beispiel über eine Art statistisches Verständnis der Sprache, die du für deine Aufgabe verwendest). -* Da das vortrainierte Modell bereits auf vielen Daten trainiert wurde, sind zum Feintuning bedeutend weniger Daten erforderlich, um brauchbare Ergebnisse erzielen zu können. -* Aus demselben Grund sind der Zeitaufwand und die Ressourcen, die für gute Ergebnisse benötigt werden, bedeutend geringer. - -Man könnte zum Beispiel ein auf Englisch trainiertes Modell nutzen und es dann auf einem arXiv-Korpus feintunen, um ein auf wissenschaftliche Sprache ausgerichtetes Modell zu erstellen. Für das Feintuning wird nur eine begrenzte Menge an Daten benötigt: Das Wissen, das das vortrainierte Modell erworben hat, wird "übertragen" (engl. transferred), daher der Begriff *Transfer Learning*. - -
-The fine-tuning of a language model is cheaper than pretraining in both time and money. - -
- -Das Feintuning eines Modells ist daher mit geringeren Zeit-, Daten-, Umwelt- und finanziellen Kosten verbunden. Es ist auch schneller und einfacher, verschiedene Modelle für das Feintuning auszuprobieren, da das Training mit geringeren Einschränkungen einhergeht als ein vollständiges Pretraining. - -Dieser Ansatz führt auch zu besseren Ergebnissen als ein Training von Grund auf (es sei denn, du hast viele Daten). Deshalb solltest du immer versuchen, ein vortrainiertes Modell zu nutzen - und zwar ein Modell, das so nah wie möglich an deiner Aufgabenstellung ist - und es für das Feintuning verwenden. - -## Grundlegende Architektur - -In diesem Abschnitt gehen wir auf die grundlegende Architektur des Transformer-Modells ein. Mach dir keine Sorgen, wenn du einige der Konzepte nicht verstehst. Im weiteren Verlauf folgen noch ausführliche Abschnitte zu den einzelnen Komponenten. - - - -## Einführung - -Das Modell besteht hauptsächlich aus zwei Blöcken: - -* **Encoder (links)**: Der Encoder, auch Kodierer genannt, empfängt einen Input und erstellt eine numerische Darstellung bzw. Repräsentation des Inputs (seiner Features, im Deutschen auch als Merkmale bezeichnet). Das bedeutet, dass das Modell darauf optimiert ist, ein Verständnis vom Input zu erlangen. -* **Decoder (rechts)**: Der Decoder, auch bekannt als Dekodierer, verwendet die Repräsentation des Encoders (Features) zusammen mit anderen Inputs, um eine Zielsequenz zu generieren. Das bedeutet, dass das Modell darauf optimiert ist, einen Output zu generieren. - -
-Architecture of a Transformers models - -
- -Jede dieser Komponenten kann je nach Aufgabe unabhängig voneinander verwendet werden: - -* **Rein Encoder-basierte Modelle** ("Encoder-only Models"): Gut für Aufgaben, die ein Verständnis des Inputs erfordern, wie z. B. bei der Klassifizierung von Sätzen und der Eigennamenerkennung (NER). -* **Rein Decoder-basierte Modelle** ("Decoder-only Models"): Gut geeignet für generative Aufgaben wie die Textgenerierung. -* **Encoder-Decoder-basierte Modelle** bzw. **Sequence-to-Sequence-Modelle**: Gut für generative Aufgaben, die einen Input erfordern, wie z. B. Übersetzungen oder Zusammenfassungen. - -Wir werden diese Architekturen in späteren Abschnitten noch gesondert behandeln. - -## Attention-Layer - -Ein wesentliches Merkmal der Transformer-Modelle ist, dass sie mit speziellen Layern (im Deutschen auch als Schichten bezeichnet), den *Attention-Layern*, aufgebaut sind. Der Titel des Forschungsbeitrags, in dem die Transformer-Architektur vorgestellt wurde, lautete sogar ["Attention Is All You Need"](https://arxiv.org/abs/1706.03762)! Wir werden uns später im Kurs mit den Details von Attention-Layern befassen. Für den Moment musst du nur wissen, dass dieser Layer dem Modell sagt, dass es bei der Repräsentation eines jeden Worts in einem Satz, den du ihm übergeben hast, bestimmten Wörtern besondere Aufmerksamkeit schenken (und die anderen mehr oder weniger ignorieren) soll. - -Angenommen, du sollst einen Text aus dem Englischen ins Französische übersetzen. Bei dem Input "You like this course" muss ein Übersetzungsmodell auch das angrenzende Wort "You" berücksichtigen, um die richtige Übersetzung für das Wort "like" zu erhalten, denn im Französischen wird das Verb "like" je nach Subjekt unterschiedlich konjugiert. Der Rest des Satzes ist jedoch für die Übersetzung dieses Wortes nicht hilfreich. Genauso muss das Modell bei der Übersetzung von "this" auf das Wort "course" achten, denn "this" wird unterschiedlich übersetzt, je nachdem, ob das zugehörige Substantiv männlich oder weiblich ist. Auch hier spielen die anderen Wörter im Satz für die Übersetzung von "this" keine Rolle. Bei komplexeren Sätzen (und komplexeren Grammatikregeln) muss das Modell besonders auf Wörter achten, die weiter entfernt im Satz vorkommen, um jedes Wort richtig zu übersetzen. - -Das gleiche Konzept gilt für jede Aufgabenstellung, die mit natürlicher Sprache zu tun hat: Ein Wort an sich hat eine Bedeutung, aber diese Bedeutung hängt stark vom Kontext ab, der sich durch ein anderes Wort (oder Wörter) vor oder nach dem untersuchten Wort ergibt. - -Nachdem du nun eine Vorstellung davon hast, worum es bei Attention-Layern geht, nehmen wir die Transformer-Architektur genauer unter die Lupe. - -## Die ursprüngliche Architektur - -Die Transformer-Architektur wurde ursprünglich für die maschinelle Übersetzung entwickelt. Beim Training erhält der Encoder Inputs (Sätze) in einer bestimmten Sprache, während der Decoder die gleichen Sätze in der gewünschten Zielsprache erhält. Im Encoder können die Attention-Layer alle Wörter eines Satzes verwenden (denn wie wir gerade gesehen haben, kann die Übersetzung eines bestimmten Wortes sowohl von dem abhängen, was nach, als auch von dem, was vor dem Wort im Satz steht). Der Decoder arbeitet hingegen sequentiell und kann nur die Wörter im Satz berücksichtigen, die er bereits übersetzt hat (also nur die Wörter vor dem Wort, das gerade generiert wird). Wenn wir zum Beispiel die ersten drei Wörter der übersetzten Zielsequenz vorhergesagt haben, geben wir sie an den Decoder weiter, der dann alle Inputs des Encoders verwendet, um das vierte Wort vorherzusagen. - -Um das Training zu beschleunigen (insofern das Modell Zugriff auf die Zielsätze hat), wird der Decoder mit dem gesamten (vorherzusagenden) Zielsatz gefüttert, aber er darf keine nachfolgenden Wörter verwenden (wenn er Zugriff zum Wort an Position 2 hätte, während er versucht, das Wort an Position 2 vorherzusagen, wäre die Aufgabe nicht sonderlich schwer!). Wenn er zum Beispiel versucht, das vierte Wort vorherzusagen, hat der Attention-Layer nur Zugriff zu den Wörtern an den Positionen 1 bis 3. - -Die ursprüngliche Transformer-Architektur sah wie folgt aus - mit dem Encoder auf der linken und dem Decoder auf der rechten Seite: - -
-Architecture of a Transformers models - -
- -Beachte, dass die Attention des ersten Attention-Layers in einem Decoder-Block alle (vorangegangenen) Inputs, die der Decoder erhalten hat, berücksichtigt, während der zweite Attention-Layer den Output des Encoders verwendet. Im Rahmen der Vorhersage des aktuellen Wortes kann er also auf den gesamten Input-Satz zugreifen. Das ist vor allem deshalb nützlich, da es in den verschiedenen Sprachen unterschiedliche grammatikalische Regeln geben kann, wodurch die Wörter in einer anderen Reihenfolge aneinandergereiht werden. Ebenso könnte ein erst später im Satz enthaltener Zusammenhang dabei hilfreich sein, die beste Übersetzung eines bestimmten Wortes zu bestimmen. - -Die *Attention-Mask* kann auch im Encoder bzw. Decoder verwendet werden, um zu verhindern, dass das Modell bestimmte Wörter beachtet - zum Beispiel das spezielle Füllwort (engl. Padding Word), das verwendet wird, um alle Inputs auf die gleiche Länge zu bringen, wenn die Sätze zu Batches zusammengeführt werden. - -## Architekturen vs. Checkpoints - -Wenn wir uns in diesem Kurs mit Transformer-Modellen beschäftigen, wirst du auf *Architekturen*, *Checkpoints* und auch auf *Modelle* stoßen. Diese Begriffe haben alle eine etwas unterschiedliche Bedeutung: - -* **Architektur**: Dies ist das Skelett des Modells - die Definition jedes Layers und jeder Operation, die innerhalb des Modells stattfindet. -* **Checkpoints**: Dies ist die Gewichtung, die für eine bestimmte Architektur geladen wird. -* **Modell**: Dies ist ein Oberbegriff, der nicht so präzise ist wie "Architektur" oder "Checkpoint": Er kann beides bedeuten. In diesem Kurs wird jeweils explizit spezifiziert, ob es sich um eine *Architektur* oder um einen *Checkpoint* handelt, um Zweideutigkeiten zu vermeiden. - -BERT ist zum Beispiel eine Architektur, während `bert-base-cased` - ein Satz von Gewichten, der vom Google-Team für die erste Version von BERT trainiert wurde - ein Checkpoint ist. Man kann aber auch "das BERT-Modell" oder "das `bert-base-cased`-Modell" sagen. +# Wie funktionieren Transformer-Modelle? + + + +In diesem Abschnitt werfen wir einen Blick auf die Architektur von Transformer-Modellen. + +## Kurz zur Entwicklungsgeschichte der Transformer-Modelle + +Hier sind einige wichtige Meilensteine in der (kurzen) Geschichte der Transformer-Modelle: + +
+A brief chronology of Transformers models. + +
+ +Die [Transformer-Architektur](https://arxiv.org/abs/1706.03762) wurde erstmals im Juni 2017 veröffentlicht. Der Schwerpunkt der ursprünglichen Forschung lag auf Übersetzungsaufgaben. In der Folge wurden mehrere einflussreiche Modelle veröffentlicht, darunter: + +- **Juni 2018**: [GPT](https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf), das erste vortrainierte Transformer-Modell, wurde zum Feintuning für verschiedene CL-Aufgaben eingesetzt und erzielte Ergebnisse, die dem neuesten Stand der Technik entsprachen. + +- **Oktober 2018**: [BERT](https://arxiv.org/abs/1810.04805), ein weiteres großes vortrainiertes Modell, das dazu dient, bessere Zusammenfassungen von Sätzen zu erstellen (mehr dazu im nächsten Kapitel!) + +- **Februar 2019**: [GPT-2](https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf), eine verbesserte (und größere) Version von GPT, die aus ethischen Erwägungen nicht sofort veröffentlicht wurde + +- **Oktober 2019**: [DistilBERT](https://arxiv.org/abs/1910.01108), eine abgespeckte Version von BERT, die 60 % schneller ist, 40 % weniger Speicherplatz benötigt und dennoch 97 % der Leistung von BERT erreicht + +- **Oktober 2019**: [BART](https://arxiv.org/abs/1910.13461) und [T5](https://arxiv.org/abs/1910.10683), zwei große vortrainierte Modelle, die dieselbe Architektur wie das ursprüngliche Transformer-Modell verwenden (die ersten, die dies getan haben) + +- **Mai 2020**, [GPT-3](https://arxiv.org/abs/2005.14165), eine noch größere Version von GPT-2, die in der Lage ist, bei einer Vielzahl von Aufgabenstellungen gute Leistungen zu erbringen, ohne dass ein Feintuning erforderlich ist (auch _Zero-Shot Learning_ genannt) + +Diese Auflistung ist bei weitem nicht vollständig und soll nur einige der verschiedenen Arten von Transformer-Modellen aufzeigen. Sie lassen sich grob in drei Kategorien einteilen: + +- GPT-ähnliche (auch _autoregressive_-Transformer-Modelle genannt) +- BERT-ähnliche (auch _Auto-Encoding_-Transformer-Modelle genannt) +- BART-/T5-ähnliche (auch _Sequence-to-Sequence_-Transformer-Modelle genannt) + +Wir werden uns mit diesen unterschiedlichen Modellfamilien später noch eingehender beschäftigen. + +## Transformer-Modelle sind Sprachmodelle + +Alle oben genannten Transformer-Modelle (GPT, BERT, BART, T5, etc.) wurden als *Sprachmodelle* (engl. Language Models) trainiert. Das bedeutet, dass sie mit großen Mengen an Rohtext auf selbstüberwachte (engl. self-supervised) Weise trainiert wurden. Selbstüberwachtes Lernen ist eine Form des Trainings, bei der die vorherzusagende Variable, die sog. Zielvariable (engl. Target), automatisch aus den Inputs des Modells berechnet wird. Das bedeutet, dass kein menschliches Zutun nötig ist, um die Daten zu labeln! + +Diese Art von Modell entwickelt ein statistisches Verständnis der Sprache, auf die es trainiert wurde, ist aber für spezifische praktische Aufgaben nicht sehr nützlich. Aus diesem Grund durchläuft das allgemeine, vortrainierte Modell ein Vorgang namens *Transfer Learning*. Während dieses Vorgangs wird das Modell unter Überwachung - d. h. mit Hilfe von durch Menschen bereitgestellte Labels - für eine bestimmte Aufgabe feingetunt. + +Ein Beispiel für eine Aufgabe ist die Vorhersage des nächsten Wortes in einem Satz, nachdem man die *n* vorherigen Wörter gelesen hat. Dies nennt sich *kausale Sprachmodellierung* (engl. Causal Language Modeling), da der Output von den vergangenen und aktuellen Inputs abhängt, aber nicht von den zukünftigen. + +
+Example of causal language modeling in which the next word from a sentence is predicted. + +
+ +Ein weiteres Beispiel ist die *maskierte Sprachmodellierung* (engl. Masked Language Modeling), bei der das Modell ein Wort im Satz, das maskiert ist, vorhersagt. + +
+Example of masked language modeling in which a masked word from a sentence is predicted. + +
+ +## Transformer-Modelle sind groß + +Abgesehen von einigen wenigen Ausreißern (wie DistilBERT) besteht die allgemeine Strategie, um eine bessere Leistung zu erzielen, darin, die Modelle zu vergrößern und die Menge an Daten zu erhöhen, auf denen sie vortrainiert werden. + +
+Number of parameters of recent Transformers models +
+ +Leider erfordert das Training eines Modells, insbesondere eines großen, eine große Menge an Daten. Das ist sehr kostspielig in Bezug auf Zeit und Rechenleistung. Es hat sogar Auswirkungen auf die Umwelt, wie in der folgenden Grafik zu sehen ist. + +
+The carbon footprint of a large language model. + +
+ + + +Hier ist ein Projekt zu sehen, bei dem ein Team gezielt versucht, die Umweltauswirkungen des Pretrainings (sehr großer) Modelle zu reduzieren. Wenn man die vielen Versuche berücksichtigt, die dazu nötig sind, die besten Hyperparameter zu finden, wären die zu bemessenden ökologischen Konsequenzen noch größer. + +Stell dir vor, dass jedes Mal, wenn ein Forschungsteam, eine Bildungseinrichtung oder ein Unternehmen ein Modell trainieren möchte, dies von Grund auf tun müsste. Das würde zu enormen, unnötigen globalen Kosten führen! + +Deshalb ist die gemeinsame Nutzung von Sprachmodellen von größter Bedeutung: trainierte Gewichtungen gemeinsam zu nutzen und auf bereits trainierten Gewichtungen aufzubauen, reduziert die gesamten Rechenkosten und den CO2-Fußabdruck der Community. + + +## Transfer Learning + + + +Beim *Pretraining* wird ein Modell von Grund auf neu trainiert: Die Gewichte werden nach dem Zufallsprinzip initialisiert und das Training beginnt ohne jegliches Vorwissen. + +
+The pretraining of a language model is costly in both time and money. + +
+ +Dieses Pretraining wird normalerweise mit sehr großen Datenmengen durchgeführt. Daher wird ein sehr großer Korpus an Daten benötigt und das Training kann mehrere Wochen in Anspruch nehmen. + +*Feintuning* ist hingegen das Training, das **nach** dem Pretraining eines Modells durchgeführt wird. Für das Feintuning nimmst du zunächst ein vortrainiertes Sprachmodell und trainierst es dann mit einem aufgabenspezifischen Datensatz nach. Moment - warum trainierst du das Modell nicht gleich für die endgültige Aufgabe? Dafür gibt es mehrere Gründe: + +* Das vortrainierte Modell wurde bereits auf einem Datensatz trainiert, der einige Ähnlichkeiten mit dem Datensatz, der für das Feintuning verwendet wird, aufweist. Beim Feintuning kann also von dem Wissen profitiert werden, das das ursprüngliche Modell während des Pretrainings erlangt hat (bei CL-Problemstellungen verfügt das vortrainierte Modell zum Beispiel über eine Art statistisches Verständnis der Sprache, die du für deine Aufgabe verwendest). +* Da das vortrainierte Modell bereits auf vielen Daten trainiert wurde, sind zum Feintuning bedeutend weniger Daten erforderlich, um brauchbare Ergebnisse erzielen zu können. +* Aus demselben Grund sind der Zeitaufwand und die Ressourcen, die für gute Ergebnisse benötigt werden, bedeutend geringer. + +Man könnte zum Beispiel ein auf Englisch trainiertes Modell nutzen und es dann auf einem arXiv-Korpus feintunen, um ein auf wissenschaftliche Sprache ausgerichtetes Modell zu erstellen. Für das Feintuning wird nur eine begrenzte Menge an Daten benötigt: Das Wissen, das das vortrainierte Modell erworben hat, wird "übertragen" (engl. transferred), daher der Begriff *Transfer Learning*. + +
+The fine-tuning of a language model is cheaper than pretraining in both time and money. + +
+ +Das Feintuning eines Modells ist daher mit geringeren Zeit-, Daten-, Umwelt- und finanziellen Kosten verbunden. Es ist auch schneller und einfacher, verschiedene Modelle für das Feintuning auszuprobieren, da das Training mit geringeren Einschränkungen einhergeht als ein vollständiges Pretraining. + +Dieser Ansatz führt auch zu besseren Ergebnissen als ein Training von Grund auf (es sei denn, du hast viele Daten). Deshalb solltest du immer versuchen, ein vortrainiertes Modell zu nutzen - und zwar ein Modell, das so nah wie möglich an deiner Aufgabenstellung ist - und es für das Feintuning verwenden. + +## Grundlegende Architektur + +In diesem Abschnitt gehen wir auf die grundlegende Architektur des Transformer-Modells ein. Mach dir keine Sorgen, wenn du einige der Konzepte nicht verstehst. Im weiteren Verlauf folgen noch ausführliche Abschnitte zu den einzelnen Komponenten. + + + +## Einführung + +Das Modell besteht hauptsächlich aus zwei Blöcken: + +* **Encoder (links)**: Der Encoder, auch Kodierer genannt, empfängt einen Input und erstellt eine numerische Darstellung bzw. Repräsentation des Inputs (seiner Features, im Deutschen auch als Merkmale bezeichnet). Das bedeutet, dass das Modell darauf optimiert ist, ein Verständnis vom Input zu erlangen. +* **Decoder (rechts)**: Der Decoder, auch bekannt als Dekodierer, verwendet die Repräsentation des Encoders (Features) zusammen mit anderen Inputs, um eine Zielsequenz zu generieren. Das bedeutet, dass das Modell darauf optimiert ist, einen Output zu generieren. + +
+Architecture of a Transformers models + +
+ +Jede dieser Komponenten kann je nach Aufgabe unabhängig voneinander verwendet werden: + +* **Rein Encoder-basierte Modelle** ("Encoder-only Models"): Gut für Aufgaben, die ein Verständnis des Inputs erfordern, wie z. B. bei der Klassifizierung von Sätzen und der Eigennamenerkennung (NER). +* **Rein Decoder-basierte Modelle** ("Decoder-only Models"): Gut geeignet für generative Aufgaben wie die Textgenerierung. +* **Encoder-Decoder-basierte Modelle** bzw. **Sequence-to-Sequence-Modelle**: Gut für generative Aufgaben, die einen Input erfordern, wie z. B. Übersetzungen oder Zusammenfassungen. + +Wir werden diese Architekturen in späteren Abschnitten noch gesondert behandeln. + +## Attention-Layer + +Ein wesentliches Merkmal der Transformer-Modelle ist, dass sie mit speziellen Layern (im Deutschen auch als Schichten bezeichnet), den *Attention-Layern*, aufgebaut sind. Der Titel des Forschungsbeitrags, in dem die Transformer-Architektur vorgestellt wurde, lautete sogar ["Attention Is All You Need"](https://arxiv.org/abs/1706.03762)! Wir werden uns später im Kurs mit den Details von Attention-Layern befassen. Für den Moment musst du nur wissen, dass dieser Layer dem Modell sagt, dass es bei der Repräsentation eines jeden Worts in einem Satz, den du ihm übergeben hast, bestimmten Wörtern besondere Aufmerksamkeit schenken (und die anderen mehr oder weniger ignorieren) soll. + +Angenommen, du sollst einen Text aus dem Englischen ins Französische übersetzen. Bei dem Input "You like this course" muss ein Übersetzungsmodell auch das angrenzende Wort "You" berücksichtigen, um die richtige Übersetzung für das Wort "like" zu erhalten, denn im Französischen wird das Verb "like" je nach Subjekt unterschiedlich konjugiert. Der Rest des Satzes ist jedoch für die Übersetzung dieses Wortes nicht hilfreich. Genauso muss das Modell bei der Übersetzung von "this" auf das Wort "course" achten, denn "this" wird unterschiedlich übersetzt, je nachdem, ob das zugehörige Substantiv männlich oder weiblich ist. Auch hier spielen die anderen Wörter im Satz für die Übersetzung von "this" keine Rolle. Bei komplexeren Sätzen (und komplexeren Grammatikregeln) muss das Modell besonders auf Wörter achten, die weiter entfernt im Satz vorkommen, um jedes Wort richtig zu übersetzen. + +Das gleiche Konzept gilt für jede Aufgabenstellung, die mit natürlicher Sprache zu tun hat: Ein Wort an sich hat eine Bedeutung, aber diese Bedeutung hängt stark vom Kontext ab, der sich durch ein anderes Wort (oder Wörter) vor oder nach dem untersuchten Wort ergibt. + +Nachdem du nun eine Vorstellung davon hast, worum es bei Attention-Layern geht, nehmen wir die Transformer-Architektur genauer unter die Lupe. + +## Die ursprüngliche Architektur + +Die Transformer-Architektur wurde ursprünglich für die maschinelle Übersetzung entwickelt. Beim Training erhält der Encoder Inputs (Sätze) in einer bestimmten Sprache, während der Decoder die gleichen Sätze in der gewünschten Zielsprache erhält. Im Encoder können die Attention-Layer alle Wörter eines Satzes verwenden (denn wie wir gerade gesehen haben, kann die Übersetzung eines bestimmten Wortes sowohl von dem abhängen, was nach, als auch von dem, was vor dem Wort im Satz steht). Der Decoder arbeitet hingegen sequentiell und kann nur die Wörter im Satz berücksichtigen, die er bereits übersetzt hat (also nur die Wörter vor dem Wort, das gerade generiert wird). Wenn wir zum Beispiel die ersten drei Wörter der übersetzten Zielsequenz vorhergesagt haben, geben wir sie an den Decoder weiter, der dann alle Inputs des Encoders verwendet, um das vierte Wort vorherzusagen. + +Um das Training zu beschleunigen (insofern das Modell Zugriff auf die Zielsätze hat), wird der Decoder mit dem gesamten (vorherzusagenden) Zielsatz gefüttert, aber er darf keine nachfolgenden Wörter verwenden (wenn er Zugriff zum Wort an Position 2 hätte, während er versucht, das Wort an Position 2 vorherzusagen, wäre die Aufgabe nicht sonderlich schwer!). Wenn er zum Beispiel versucht, das vierte Wort vorherzusagen, hat der Attention-Layer nur Zugriff zu den Wörtern an den Positionen 1 bis 3. + +Die ursprüngliche Transformer-Architektur sah wie folgt aus - mit dem Encoder auf der linken und dem Decoder auf der rechten Seite: + +
+Architecture of a Transformers models + +
+ +Beachte, dass die Attention des ersten Attention-Layers in einem Decoder-Block alle (vorangegangenen) Inputs, die der Decoder erhalten hat, berücksichtigt, während der zweite Attention-Layer den Output des Encoders verwendet. Im Rahmen der Vorhersage des aktuellen Wortes kann er also auf den gesamten Input-Satz zugreifen. Das ist vor allem deshalb nützlich, da es in den verschiedenen Sprachen unterschiedliche grammatikalische Regeln geben kann, wodurch die Wörter in einer anderen Reihenfolge aneinandergereiht werden. Ebenso könnte ein erst später im Satz enthaltener Zusammenhang dabei hilfreich sein, die beste Übersetzung eines bestimmten Wortes zu bestimmen. + +Die *Attention-Mask* kann auch im Encoder bzw. Decoder verwendet werden, um zu verhindern, dass das Modell bestimmte Wörter beachtet - zum Beispiel das spezielle Füllwort (engl. Padding Word), das verwendet wird, um alle Inputs auf die gleiche Länge zu bringen, wenn die Sätze zu Batches zusammengeführt werden. + +## Architekturen vs. Checkpoints + +Wenn wir uns in diesem Kurs mit Transformer-Modellen beschäftigen, wirst du auf *Architekturen*, *Checkpoints* und auch auf *Modelle* stoßen. Diese Begriffe haben alle eine etwas unterschiedliche Bedeutung: + +* **Architektur**: Dies ist das Skelett des Modells - die Definition jedes Layers und jeder Operation, die innerhalb des Modells stattfindet. +* **Checkpoints**: Dies ist die Gewichtung, die für eine bestimmte Architektur geladen wird. +* **Modell**: Dies ist ein Oberbegriff, der nicht so präzise ist wie "Architektur" oder "Checkpoint": Er kann beides bedeuten. In diesem Kurs wird jeweils explizit spezifiziert, ob es sich um eine *Architektur* oder um einen *Checkpoint* handelt, um Zweideutigkeiten zu vermeiden. + +BERT ist zum Beispiel eine Architektur, während `bert-base-cased` - ein Satz von Gewichten, der vom Google-Team für die erste Version von BERT trainiert wurde - ein Checkpoint ist. Man kann aber auch "das BERT-Modell" oder "das `bert-base-cased`-Modell" sagen. diff --git a/chapters/de/chapter1/5.mdx b/chapters/de/chapter1/5.mdx index 5f1b68f53..665dac512 100644 --- a/chapters/de/chapter1/5.mdx +++ b/chapters/de/chapter1/5.mdx @@ -1,22 +1,22 @@ -# Encoder-Modelle - - - - - -Encoder-Modelle verwenden nur den Encoder eines Transformer-Modells. Die Attention-Layer können zu jeder Zeit auf alle Wörter des Ausgangssatzes zugreifen. Diese Modelle werden häufig als Modelle mit "bidirektionaler" (engl. bi-directional) Attention bezeichnet und oft *Auto-Encoding-Modelle* genannt. - -Beim Pretraining dieser Modelle geht es in der Regel darum, einen bestimmten Satz auf irgendeine Weise zu verfälschen (z. B. indem zufällig Wörter darin maskiert werden) und das Modell dann damit zu betrauen, den ursprünglichen Satz zu finden bzw. zu rekonstruieren. - -Rein Encoder-basierte Modelle eignen sich am besten für Aufgaben, die ein Verständnis des gesamten Satzes erfordern, wie z. B. die Klassifizierung von Sätzen, die Eigennamenerkennung (bzw. allgemeiner die Klassifikation von Wörtern) und extraktive Frage-Antwort-Systeme. - -Zu dieser Modellfamilie gehören unter anderem: - -- [ALBERT](https://huggingface.co/transformers/model_doc/albert) -- [BERT](https://huggingface.co/transformers/model_doc/bert) -- [DistilBERT](https://huggingface.co/transformers/model_doc/distilbert) -- [ELECTRA](https://huggingface.co/transformers/model_doc/electra) -- [RoBERTa](https://huggingface.co/transformers/model_doc/roberta) +# Encoder-Modelle + + + + + +Encoder-Modelle verwenden nur den Encoder eines Transformer-Modells. Die Attention-Layer können zu jeder Zeit auf alle Wörter des Ausgangssatzes zugreifen. Diese Modelle werden häufig als Modelle mit "bidirektionaler" (engl. bi-directional) Attention bezeichnet und oft *Auto-Encoding-Modelle* genannt. + +Beim Pretraining dieser Modelle geht es in der Regel darum, einen bestimmten Satz auf irgendeine Weise zu verfälschen (z. B. indem zufällig Wörter darin maskiert werden) und das Modell dann damit zu betrauen, den ursprünglichen Satz zu finden bzw. zu rekonstruieren. + +Rein Encoder-basierte Modelle eignen sich am besten für Aufgaben, die ein Verständnis des gesamten Satzes erfordern, wie z. B. die Klassifizierung von Sätzen, die Eigennamenerkennung (bzw. allgemeiner die Klassifikation von Wörtern) und extraktive Frage-Antwort-Systeme. + +Zu dieser Modellfamilie gehören unter anderem: + +- [ALBERT](https://huggingface.co/transformers/model_doc/albert) +- [BERT](https://huggingface.co/transformers/model_doc/bert) +- [DistilBERT](https://huggingface.co/transformers/model_doc/distilbert) +- [ELECTRA](https://huggingface.co/transformers/model_doc/electra) +- [RoBERTa](https://huggingface.co/transformers/model_doc/roberta) diff --git a/chapters/de/chapter1/6.mdx b/chapters/de/chapter1/6.mdx index 948c010a2..5d3725be0 100644 --- a/chapters/de/chapter1/6.mdx +++ b/chapters/de/chapter1/6.mdx @@ -1,21 +1,21 @@ -# Decoder-Modelle - - - - - -Decoder-Modelle verwenden nur den Decoder eines Transformer-Modells. Die Attention-Layer können bei jedem Schritt hinsichtlich eines bestimmten Wortes nur auf die Wörter zugreifen, die vor diesem Wort im Satz stehen. Diese Modelle werden oft als *autoregressive Modelle* bezeichnet. - -Beim Pretraining von Decoder-Modellen geht es in der Regel um die Vorhersage des nächsten Wortes im Satz. - -Diese Modelle sind am besten für Aufgaben geeignet, bei denen es um die Generierung von Texten geht. - -Zu dieser Modellfamilie gehören unter anderem: - -- [CTRL](https://huggingface.co/transformers/model_doc/ctrl) -- [GPT](https://huggingface.co/docs/transformers/model_doc/openai-gpt) -- [GPT-2](https://huggingface.co/transformers/model_doc/gpt2) -- [Transformer XL](https://huggingface.co/transformers/model_doc/transformerxl) +# Decoder-Modelle + + + + + +Decoder-Modelle verwenden nur den Decoder eines Transformer-Modells. Die Attention-Layer können bei jedem Schritt hinsichtlich eines bestimmten Wortes nur auf die Wörter zugreifen, die vor diesem Wort im Satz stehen. Diese Modelle werden oft als *autoregressive Modelle* bezeichnet. + +Beim Pretraining von Decoder-Modellen geht es in der Regel um die Vorhersage des nächsten Wortes im Satz. + +Diese Modelle sind am besten für Aufgaben geeignet, bei denen es um die Generierung von Texten geht. + +Zu dieser Modellfamilie gehören unter anderem: + +- [CTRL](https://huggingface.co/transformers/model_doc/ctrl) +- [GPT](https://huggingface.co/docs/transformers/model_doc/openai-gpt) +- [GPT-2](https://huggingface.co/transformers/model_doc/gpt2) +- [Transformer XL](https://huggingface.co/transformers/model_doc/transformerxl) diff --git a/chapters/de/chapter1/7.mdx b/chapters/de/chapter1/7.mdx index 4bf04585f..1c28056f2 100644 --- a/chapters/de/chapter1/7.mdx +++ b/chapters/de/chapter1/7.mdx @@ -1,21 +1,21 @@ -# Sequence-to-Sequence-Modelle - - - - - -Encoder-Decoder-Modelle (auch *Sequence-to-Sequence-Modelle* genannt) verwenden beide Teile der Transformer-Architektur. Die Attention-Layer des Encoders können in jedem Schritt auf alle Wörter des Ausgangssatzes zugreifen, während die Attention-Layer des Decoders nur auf die Wörter zugreifen können, die vor einem bestimmten Wort des Inputs stehen. - -Das Pretraining dieser Modelle kann wie das Pretraining von rein Encoder- oder Decoder-basierten Modellen erfolgen, ist aber in der Regel etwas komplexer. Beim Pretraining von [T5](https://huggingface.co/t5-base) werden zum Beispiel zufällige Textabschnitte (die mehrere Wörter enthalten können) durch ein einzelnes spezielles Maskierungswort ersetzt, und das Ziel (engl. Pretraining Objective) besteht dann darin, den Text vorherzusagen, der durch dieses Maskierungswort ersetzt bzw. verdeckt wurde. - -Sequence-to-Sequence-Modelle eignen sich am besten für Aufgaben, bei denen es darum geht, neue Sätze in Abhängigkeit von einem bestimmten Input zu generieren, z. B. bei der Zusammenfassung, Übersetzung oder generativen Frage-Antwort-Systemen. - -Vertreter dieser Modellfamilie sind u. a.: - -- [BART](https://huggingface.co/transformers/model_doc/bart) -- [mBART](https://huggingface.co/transformers/model_doc/mbart) -- [Marian](https://huggingface.co/transformers/model_doc/marian) -- [T5](https://huggingface.co/transformers/model_doc/t5) +# Sequence-to-Sequence-Modelle + + + + + +Encoder-Decoder-Modelle (auch *Sequence-to-Sequence-Modelle* genannt) verwenden beide Teile der Transformer-Architektur. Die Attention-Layer des Encoders können in jedem Schritt auf alle Wörter des Ausgangssatzes zugreifen, während die Attention-Layer des Decoders nur auf die Wörter zugreifen können, die vor einem bestimmten Wort des Inputs stehen. + +Das Pretraining dieser Modelle kann wie das Pretraining von rein Encoder- oder Decoder-basierten Modellen erfolgen, ist aber in der Regel etwas komplexer. Beim Pretraining von [T5](https://huggingface.co/t5-base) werden zum Beispiel zufällige Textabschnitte (die mehrere Wörter enthalten können) durch ein einzelnes spezielles Maskierungswort ersetzt, und das Ziel (engl. Pretraining Objective) besteht dann darin, den Text vorherzusagen, der durch dieses Maskierungswort ersetzt bzw. verdeckt wurde. + +Sequence-to-Sequence-Modelle eignen sich am besten für Aufgaben, bei denen es darum geht, neue Sätze in Abhängigkeit von einem bestimmten Input zu generieren, z. B. bei der Zusammenfassung, Übersetzung oder generativen Frage-Antwort-Systemen. + +Vertreter dieser Modellfamilie sind u. a.: + +- [BART](https://huggingface.co/transformers/model_doc/bart) +- [mBART](https://huggingface.co/transformers/model_doc/mbart) +- [Marian](https://huggingface.co/transformers/model_doc/marian) +- [T5](https://huggingface.co/transformers/model_doc/t5) diff --git a/chapters/de/chapter1/8.mdx b/chapters/de/chapter1/8.mdx index 5e15e56e9..be928fdba 100644 --- a/chapters/de/chapter1/8.mdx +++ b/chapters/de/chapter1/8.mdx @@ -1,32 +1,32 @@ -# Bias und Einschränkungen - - - -Wenn du vorhast, ein vortrainiertes Modell oder eine feingetunte Modellversion in der Produktion zu verwenden, sei dir bitte darüber im Klaren, dass diese zwar leistungsstarke Werkzeuge sind, allerdings aber auch ihre Grenzen haben. Die größte Einschränkung ergibt sich daraus, dass Forscherinnen und Forscher für das auf Basis großer Datenmengen durchgeführte Pretraining oft alle Inhalte, die sie finden können, zusammensuchen und dabei sowohl all das Gute als auch das Schlechte einbezogen wird, was das Internet zu bieten hat. - -Greifen wir zur Veranschaulichung noch einmal das Beispiel einer `fill-mask`-Pipeline mit dem BERT-Modell auf: - -```python -from transformers import pipeline - -unmasker = pipeline("fill-mask", model="bert-base-uncased") -result = unmasker("This man works as a [MASK].") -print([r["token_str"] for r in result]) - -result = unmasker("This woman works as a [MASK].") -print([r["token_str"] for r in result]) -``` - -```python out -['lawyer', 'carpenter', 'doctor', 'waiter', 'mechanic'] -['nurse', 'waitress', 'teacher', 'maid', 'prostitute'] -``` - -Wenn das Modell aufgefordert wird, das fehlende Wort in diesen beiden Sätzen zu ergänzen, gibt es lediglich eine geschlechtsneutrale Antwort (Kellnerin/Kellner - waitress/waiter). Bei den anderen handelt es sich um Berufe, die normalerweise mit einem bestimmten Geschlecht assoziiert werden - und ja, "prostitute" landete unter den Top 5, die das Modell mit "woman" und "work" assoziiert. Und das, obwohl BERT eines der wenigen Transformer-Modelle ist, das nicht auf Daten aus dem gesamten Internet beruht, sondern auf vermeintlich neutralen Daten (es wurde auf dem [englischsprachigen Wikipedia-](https://huggingface.co/datasets/wikipedia) und dem [BookCorpus-Datensatz](https://huggingface.co/datasets/bookcorpus) trainiert). - -Wenn du diese Werkzeuge verwendest, musst du daher im Hinterkopf behalten, dass das ursprüngliche Modell, das du verwendest, sehr leicht sexistische, rassistische oder homophobe Inhalte hervorbringen könnte. Beim Feintuning des Modells auf deinen Daten werden diese inhärenten Voreingenommenheiten bzw. Vorurteile (engl. Bias) nicht verschwinden. +# Bias und Einschränkungen + + + +Wenn du vorhast, ein vortrainiertes Modell oder eine feingetunte Modellversion in der Produktion zu verwenden, sei dir bitte darüber im Klaren, dass diese zwar leistungsstarke Werkzeuge sind, allerdings aber auch ihre Grenzen haben. Die größte Einschränkung ergibt sich daraus, dass Forscherinnen und Forscher für das auf Basis großer Datenmengen durchgeführte Pretraining oft alle Inhalte, die sie finden können, zusammensuchen und dabei sowohl all das Gute als auch das Schlechte einbezogen wird, was das Internet zu bieten hat. + +Greifen wir zur Veranschaulichung noch einmal das Beispiel einer `fill-mask`-Pipeline mit dem BERT-Modell auf: + +```python +from transformers import pipeline + +unmasker = pipeline("fill-mask", model="bert-base-uncased") +result = unmasker("This man works as a [MASK].") +print([r["token_str"] for r in result]) + +result = unmasker("This woman works as a [MASK].") +print([r["token_str"] for r in result]) +``` + +```python out +['lawyer', 'carpenter', 'doctor', 'waiter', 'mechanic'] +['nurse', 'waitress', 'teacher', 'maid', 'prostitute'] +``` + +Wenn das Modell aufgefordert wird, das fehlende Wort in diesen beiden Sätzen zu ergänzen, gibt es lediglich eine geschlechtsneutrale Antwort (Kellnerin/Kellner - waitress/waiter). Bei den anderen handelt es sich um Berufe, die normalerweise mit einem bestimmten Geschlecht assoziiert werden - und ja, "prostitute" landete unter den Top 5, die das Modell mit "woman" und "work" assoziiert. Und das, obwohl BERT eines der wenigen Transformer-Modelle ist, das nicht auf Daten aus dem gesamten Internet beruht, sondern auf vermeintlich neutralen Daten (es wurde auf dem [englischsprachigen Wikipedia-](https://huggingface.co/datasets/wikipedia) und dem [BookCorpus-Datensatz](https://huggingface.co/datasets/bookcorpus) trainiert). + +Wenn du diese Werkzeuge verwendest, musst du daher im Hinterkopf behalten, dass das ursprüngliche Modell, das du verwendest, sehr leicht sexistische, rassistische oder homophobe Inhalte hervorbringen könnte. Beim Feintuning des Modells auf deinen Daten werden diese inhärenten Voreingenommenheiten bzw. Vorurteile (engl. Bias) nicht verschwinden. diff --git a/chapters/de/chapter1/9.mdx b/chapters/de/chapter1/9.mdx index f65fc8fa4..843d59a5e 100644 --- a/chapters/de/chapter1/9.mdx +++ b/chapters/de/chapter1/9.mdx @@ -1,16 +1,16 @@ -# Zusammenfassung - - - -In diesem Kapitel hast du gelernt, wie du verschiedene CL-Aufgaben mit der High-Level-Funktion `pipeline()` aus der 🤗 Transformers-Bibliothek angehen kannst. Du hast auch erfahren, wie du im Hub nach Modellen suchen und sie nutzen kannst, und wie du die Inference API verwenden kannst, um die Modelle direkt in deinem Browser zu testen. - -Wir haben besprochen, wie Transformer-Modelle im Großen und Ganzen funktionieren, und haben die Bedeutung von Tranfer Learning und Feintuning erläutert. Ein wichtiger Aspekt ist, dass du entweder die gesamte Architektur, nur den Encoder oder auch nur den Decoder verwenden kannst - je nachdem, welche Art von Aufgabe du lösen willst. Die nachfolgende Tabelle gibt noch einmal einen guten Überblick: - -| Modell | Beispiele | Aufgaben (Tasks) | -|-----------------|--------------------------------------------|----------------------------------------------------------------------------------| -| Encoder | ALBERT, BERT, DistilBERT, ELECTRA, RoBERTa | Klassifizierung von Sätzen, Eigennamenerkennung/NER, Extraktive Frage-Antwort-Systeme | -| Decoder | CTRL, GPT, GPT-2, Transformer XL | Textgenerierung | -| Encoder-Decoder | BART, T5, Marian, mBART | Automatische Textzusammenfassung, Maschinelle Übersetzung, Generative Frage-Antwort-Systeme | +# Zusammenfassung + + + +In diesem Kapitel hast du gelernt, wie du verschiedene CL-Aufgaben mit der High-Level-Funktion `pipeline()` aus der 🤗 Transformers-Bibliothek angehen kannst. Du hast auch erfahren, wie du im Hub nach Modellen suchen und sie nutzen kannst, und wie du die Inference API verwenden kannst, um die Modelle direkt in deinem Browser zu testen. + +Wir haben besprochen, wie Transformer-Modelle im Großen und Ganzen funktionieren, und haben die Bedeutung von Tranfer Learning und Feintuning erläutert. Ein wichtiger Aspekt ist, dass du entweder die gesamte Architektur, nur den Encoder oder auch nur den Decoder verwenden kannst - je nachdem, welche Art von Aufgabe du lösen willst. Die nachfolgende Tabelle gibt noch einmal einen guten Überblick: + +| Modell | Beispiele | Aufgaben (Tasks) | +|-----------------|--------------------------------------------|----------------------------------------------------------------------------------| +| Encoder | ALBERT, BERT, DistilBERT, ELECTRA, RoBERTa | Klassifizierung von Sätzen, Eigennamenerkennung/NER, Extraktive Frage-Antwort-Systeme | +| Decoder | CTRL, GPT, GPT-2, Transformer XL | Textgenerierung | +| Encoder-Decoder | BART, T5, Marian, mBART | Automatische Textzusammenfassung, Maschinelle Übersetzung, Generative Frage-Antwort-Systeme | diff --git a/chapters/de/chapter3/1.mdx b/chapters/de/chapter3/1.mdx index 7d275b917..7f1611828 100644 --- a/chapters/de/chapter3/1.mdx +++ b/chapters/de/chapter3/1.mdx @@ -1,26 +1,26 @@ - - -# Einführung - - - -In [Kapitel 2](/course/chapter2) haben wir behandelt, wie man Tokenizer und vortrainierte Modelle verwendet, um Vorhersagen zu treffen. Was passiert aber, wenn wir ein vortrainiertes Modell für unseren eigenen Datensatz optimieren möchten? Das ist das Thema dieses Kapitels! Folgendes wirst du lernen: - -{#if fw === 'pt'} -* Wie bereitet man einen großen Datensatz aus dem Hub vor? -* Wie nutzt man die höhere `Trainer` API um Modelle zu fein-tunen? -* Wie implementiert man eine benutzerdefinierte Trainingsschleife -* Wie nutzen wir die 🤗 Accelerate Bibliothek für benutzerdefinierte Trainingschleifen auf verteilten Systemen - -{:else} -* Wie bereitet man einen großen Datensatz aus dem Hub vor? -* Wie nutzt man Keras um Modelle zu fein-tunen? -* Wie setzt man Keras für Vorhersagen ein? -* Wie implementiert benutzerdefinierte Metriken? - -{/if} - + + +# Einführung + + + +In [Kapitel 2](/course/chapter2) haben wir behandelt, wie man Tokenizer und vortrainierte Modelle verwendet, um Vorhersagen zu treffen. Was passiert aber, wenn wir ein vortrainiertes Modell für unseren eigenen Datensatz optimieren möchten? Das ist das Thema dieses Kapitels! Folgendes wirst du lernen: + +{#if fw === 'pt'} +* Wie bereitet man einen großen Datensatz aus dem Hub vor? +* Wie nutzt man die höhere `Trainer` API um Modelle zu fein-tunen? +* Wie implementiert man eine benutzerdefinierte Trainingsschleife +* Wie nutzen wir die 🤗 Accelerate Bibliothek für benutzerdefinierte Trainingschleifen auf verteilten Systemen + +{:else} +* Wie bereitet man einen großen Datensatz aus dem Hub vor? +* Wie nutzt man Keras um Modelle zu fein-tunen? +* Wie setzt man Keras für Vorhersagen ein? +* Wie implementiert benutzerdefinierte Metriken? + +{/if} + Um deine trainierten Checkpoints auf den Hugging Face Hub hochzuladen, benötigst du ein huggingface.co-Konto: [Erstelle ein Konto](https://huggingface.co/join) \ No newline at end of file diff --git a/chapters/de/chapter3/2.mdx b/chapters/de/chapter3/2.mdx index 1c9aaad0a..03e12b3c9 100644 --- a/chapters/de/chapter3/2.mdx +++ b/chapters/de/chapter3/2.mdx @@ -1,376 +1,376 @@ - - -# Vorbereitung der Daten - -{#if fw === 'pt'} - - - -{:else} - - - -{/if} - -{#if fw === 'pt'} -Wir fahren mit dem Beispiel aus dem [vorigen Kapitel](/course/chapter2) fort. Folgenderweise würden wir einen Sequenzklassifikator mit einem Batch in PyTorch trainieren: - -```python -import torch -from torch.optim import AdamW -from transformers import AutoTokenizer, AutoModelForSequenceClassification - -# Genau wie vorher -checkpoint = "bert-base-uncased" -tokenizer = AutoTokenizer.from_pretrained(checkpoint) -model = AutoModelForSequenceClassification.from_pretrained(checkpoint) -sequences = [ - "I've been waiting for a HuggingFace course my whole life.", # Ich habe mein ganzes Leben auf einen HuggingFace-Kurs gewartet. - "This course is amazing!", # Dieser Kurs ist fantastisch! -] -batch = tokenizer(sequences, padding=True, truncation=True, return_tensors="pt") - -# Dies ist neu -batch["labels"] = torch.tensor([1, 1]) - -optimizer = AdamW(model.parameters()) -loss = model(**batch).loss -loss.backward() -optimizer.step() -``` -{:else} -Wir fahren mit dem Beispiel aus dem [vorigen Kapitel](/course/chapter2) fort. Folgenderweise würden wir einen Sequenzklassifikator mit einem Batch in Tensorflow trainieren: - -```python -import tensorflow as tf -import numpy as np -from transformers import AutoTokenizer, TFAutoModelForSequenceClassification - -# Genau wie vorher -checkpoint = "bert-base-uncased" -tokenizer = AutoTokenizer.from_pretrained(checkpoint) -model = TFAutoModelForSequenceClassification.from_pretrained(checkpoint) -sequences = [ - "I've been waiting for a HuggingFace course my whole life.", # Ich habe mein ganzes Leben auf einen HuggingFace-Kurs gewartet. - "This course is amazing!", # Dieser Kurs ist fantastisch! -] -batch = dict(tokenizer(sequences, padding=True, truncation=True, return_tensors="tf")) - -# Dies ist neu -model.compile(optimizer="adam", loss="sparse_categorical_crossentropy") -labels = tf.convert_to_tensor([1, 1]) -model.train_on_batch(batch, labels) -``` -{/if} - -Natürlich würde das Training von Modellen mit nur zwei Sätzen keine sonderlich guten Ergebnisse liefern. Um bessere Ergebnisse zu erzielen, müssen wir einen größeren Datensatz vorbereiten. - -In diesem Abschnitt verwenden wir den MRPC-Datensatz (Microsoft Research Paraphrase Corpus) als Beispiel. Dieser wurde in einem [Paper](https://www.aclweb.org/anthology/I05-5002.pdf) von William B. Dolan und Chris Brockett veröffentlicht. Der Datensatz besteht aus insgesamt 5.801 Satzpaaren und enthält ein Label, das angibt, ob es sich bei einem Paar um Paraphrasen handelt (d.h. ob beide Sätze dasselbe bedeuten). Wir haben diesen Datensatz für dieses Kapitel ausgewählt, weil es sich um einen kleinen Datensatz handelt, sodass es einfach ist, während dem Training zu experimentieren. - -### Laden eines Datensatzes vom Hub - -{#if fw === 'pt'} - -{:else} - -{/if} - -Das Hub enthält nicht nur Modelle; Es hat auch mehrere Datensätze in vielen verschiedenen Sprachen. Du kannst die Datensätze [hier](https://huggingface.co/datasets) durchsuchen, und wir empfehlen, einen weiteren Datensatz zu laden und zu verarbeiten, sobald Sie diesen Abschnitt abgeschlossen haben (die Dokumentation befindet sich [hier](https://huggingface.co/docs/datasets/loading)). Aber jetzt konzentrieren wir uns auf den MRPC-Datensatz! Dies ist einer der 10 Datensätze, aus denen sich das [GLUE-Benchmark](https://gluebenchmark.com/) zusammensetzt. Dies ist ein akademisches Benchmark, das verwendet wird, um die Performance von ML-Modellen in 10 verschiedenen Textklassifizierungsaufgaben zu messen. - -Die Bibliothek 🤗 Datasets bietet einen leichten Befehl zum Herunterladen und Caching eines Datensatzes aus dem Hub. Wir können den MRPC-Datensatz wie folgt herunterladen: - -⚠️ ** Warnung** Stelle sicher, dass `datasets` installiert ist, indem du `pip install datasets` ausführst. Dann lade den MRPC-Datensatz und drucke ihn aus, um zu sehen, was er enthält. - - -```py -from datasets import load_dataset - -raw_datasets = load_dataset("glue", "mrpc") -raw_datasets -``` - -```python out -DatasetDict({ - train: Dataset({ - features: ['sentence1', 'sentence2', 'label', 'idx'], - num_rows: 3668 - }) - validation: Dataset({ - features: ['sentence1', 'sentence2', 'label', 'idx'], - num_rows: 408 - }) - test: Dataset({ - features: ['sentence1', 'sentence2', 'label', 'idx'], - num_rows: 1725 - }) -}) -``` - -Wie du sehen kannst, erhalten wir ein `DatasetDict`-Objekt, das die Trainingsdaten, die Validierungsdaten und die Testdaten enthält. Jedes Objekt enthält mehrere Spalten (`sentence1`, `sentence2`, `label` und `idx`) und eine unterschiedliche Anzahl an Zeilen, dies ist die Anzahl der Elemente in jedem Datensatz (also gibt es 3.668 Satzpaare in den Trainingsdaten, 408 in den Validierungsdaten und 1.725 in den Testdaten). - -Dieser Befehl lädt das Dataset herunter und speichert es im Cache, standardmäßig in *~/.cache/huggingface/dataset*. Wir Erinnern uns an Kapitel 2, dass der Cache-Ordner anpasst werden kann, indem man die Umgebungsvariable `HF_HOME` setzt. - -Wir können auf jedes Satzpaar in unserem `raw_datasets`-Objekt zugreifen, indem wir wie bei einem Dictionary einen Schlüsselwert als Index verwenden: - -```py -raw_train_dataset = raw_datasets["train"] -raw_train_dataset[0] -``` - -```python out -{'idx': 0, - 'label': 1, - 'sentence1': 'Amrozi accused his brother , whom he called " the witness " , of deliberately distorting his evidence .', - 'sentence2': 'Referring to him as only " the witness " , Amrozi accused his brother of deliberately distorting his evidence .'} -``` - -Wir stellen fest, dass die Labels bereits Ganzzahlen sind, sodass wir dort keine Vorverarbeitung durchführen müssen. Wir können die `features` von `raw_train_dataset` untersuchen, um zu erfahren, welche Ganzzahl welchem Label entspricht. Der folgende Befehl gibt uns den Variablentyp zurück: - -```py -raw_train_dataset.features -``` - -```python out -{'sentence1': Value(dtype='string', id=None), - 'sentence2': Value(dtype='string', id=None), - 'label': ClassLabel(num_classes=2, names=['not_equivalent', 'equivalent'], names_file=None, id=None), - 'idx': Value(dtype='int32', id=None)} -``` - -Hinter den Kulissen ist `label` vom Typ `ClassLabel`, und die Zuordnung von Ganzzahlen zum Labelnamen wird im Ordner *names* gespeichert. `0` entspricht `not_equivalent`, also "nicht äquivalent", und `1` entspricht `equivalent`, also "äquivalent". - -> [!TIP] -> ✏️ **Probier es aus!** Sieh dir das Element 15 der Trainingsdaten und Element 87 des Validierungsdaten an. Was sind ihre Labels? - -### Vorverarbeitung eines Datensatzes - -{#if fw === 'pt'} - -{:else} - -{/if} - -Um den Datensatz vorzubereiten, müssen wir den Text in Zahlen umwandeln, die das Modell sinnvoll verarbeiten kann. Im [vorherigen Kapitel](/course/chapter2) haben wir gesehen, dass dies mit einem Tokenizer gemacht wird. Wir können den Tokenizer mit einem Satz oder einer Liste von Sätzen füttern, sodass wir die ersten und zweiten Sätze jedes Paares wie folgt direkt tokenisieren können: - -```py -from transformers import AutoTokenizer - -checkpoint = "bert-base-uncased" -tokenizer = AutoTokenizer.from_pretrained(checkpoint) -tokenized_sentences_1 = tokenizer(raw_datasets["train"]["sentence1"]) -tokenized_sentences_2 = tokenizer(raw_datasets["train"]["sentence2"]) -``` - -Wir können jedoch nicht einfach zwei Sequenzen an das Modell übergeben und eine Vorhersage erhalten, ob die beiden Sätze paraphrasiert sind oder nicht. Wir müssen die beiden Sequenzen als Paar behandeln und die entsprechende Vorverarbeitung anwenden. Glücklicherweise kann der Tokenizer auch ein Sequenzpaar nehmen und es so vorbereiten, wie es unser BERT-Modell erwartet: - -```py -inputs = tokenizer("This is the first sentence.", "This is the second one.") -inputs -``` - -```python out -{ - 'input_ids': [101, 2023, 2003, 1996, 2034, 6251, 1012, 102, 2023, 2003, 1996, 2117, 2028, 1012, 102], - 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], - 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] -} -``` - -In [Kapitel 2](/course/chapter2) haben wir die Schlüsselwerte `input_ids` und `attention_mask` behandelt, allerdings haben wir es aufgeschoben, über `token_type_ids` zu sprechen. In diesem Beispiel teilt diese dem Modell mit, welcher Teil des Input der erste Satz und welcher der zweite Satz ist. - -> [!TIP] -> ✏️ **Probier es aus!** Nimm Element 15 der Trainingsdaten und tokenisiere die beiden Sätze separat und als Paar. Wo liegt der Unterschied zwischen den beiden Ergebnissen? - -Wenn wir die IDs in `input_ids` zurück in Worte dekodieren: - -```py -tokenizer.convert_ids_to_tokens(inputs["input_ids"]) -``` - -dann bekommen wir: - -```python out -['[CLS]', 'this', 'is', 'the', 'first', 'sentence', '.', '[SEP]', 'this', 'is', 'the', 'second', 'one', '.', '[SEP]'] -``` - -Wir sehen also wenn es zwei Sätze gibt, dass das Modell erwartet, dass die Inputs die Form "[CLS] Satz1 [SEP] Satz2 [SEP]" haben. Wenn wir dies mit den `token_type_ids` abgleichen, erhalten wir: - -```python out -['[CLS]', 'this', 'is', 'the', 'first', 'sentence', '.', '[SEP]', 'this', 'is', 'the', 'second', 'one', '.', '[SEP]'] -[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1] -``` - -Wie du sehen kannst, haben die Teile der Eingabe, die `[CLS] Satz1 [SEP]` entsprechen, alle eine Token-Typ-ID von `0`, während die anderen Teile, die `Satz2 [SEP]` entsprechen, alle einer Token-Typ-ID von `1` enthalten. - -Beachte, dass die Auswahl eines anderen Checkpoints nicht unbedingt die `token_type_ids` in Ihren tokenisierten Inputs haben (z.B. werden sie nicht zurückgegeben, wenn ein DistilBERT-Modell verwendet wird). Sie werden nur zurückgegeben, wenn das Modell weiß was damit zu tun ist, weil es die Toke-Typ-Ids während des Vortrainings gesehen hat. - -In diesem Fall ist BERT mit Token-Typ-IDs vortrainiert worden, und zusätzlich zu dem maskierten Sprachmodellierungsziel aud [Kapitel 1](/course/chapter1), hat es ein zusätzliches Vorhersageziel namens _next sentence prediction_ (d.h. Vorhersage des nächsten Satzes). Das Ziel dieser Aufgabe ist es, die Beziehung zwischen Satzpaaren zu modellieren. - -Bei der Vorhersage des nächsten Satzes werden dem Modell Satzpaare (mit zufällig maskierten Token) bereitgestellt und erwartet, vorherzusagen, ob auf den ersten Satz der zweite Satz folgt. Um die Aufgabe non-trivial zu machen, folgen sich die Hälfte der Sätze in dem Originaldokument, aus dem sie extrahiert wurden, aufeinander, und in der anderen Hälfte stammen die beiden Sätze aus zwei verschiedenen Dokumenten. - -Im Allgemeinen muss man sich keine Gedanken darüber machen, ob Ihre tokenisierten Inputs `token_type_ids` enthalten oder nicht: Solange du denselben Checkpoint für den Tokenizer und das Modell verwendest, ist alles in Ordnung, da der Tokenizer weiß, was er dem Modell bereitstellen soll. - -Nachdem wir nun gesehen haben, wie unser Tokenizer mit einem Satzpaar umgehen kann, können wir damit unseren gesamten Datensatz tokenisieren: Wie im [vorherigen Kapitel](/course/chapter2) können wir dem Tokenizer eine Liste von Satzpaaren einspeisen, indem du ihm die Liste der ersten Sätze und dann die Liste der zweiten Sätze gibst. Dies ist auch kompatibel mit den Optionen zum Padding und Trunkieren, die wir in [Kapitel 2](/course/chapter2) gesehen haben. Eine Möglichkeit, den Trainingsdatensatz vorzuverarbeiten, ist also: - -```py -tokenized_dataset = tokenizer( - raw_datasets["train"]["sentence1"], - raw_datasets["train"]["sentence2"], - padding=True, - truncation=True, -) -``` - -Das funktioniert gut, hat aber den Nachteil, dass ein Dictionary zurückgegeben wird (mit unseren Schlüsselwörtern `input_ids`, `attention_mask` und `token_type_ids` und Werten aus Listen von Listen). Es funktioniert auch nur, wenn du genügend RAM hast, um den gesamten Datensatz während der Tokenisierung zu im RAM zwischen zu speichern (während die Datensätze aus der Bibliothek 🤗 Datasets [Apache Arrow](https://arrow.apache.org/) Dateien sind, die auf der Festplatte gespeichert sind, sodass nur die gewünschten Samples im RAM geladen sind). - -Um die Daten als Datensatz zu speichern, verwenden wir die Methode [`Dataset.map()`](https://huggingface.co/docs/datasets/package_reference/main_classes#datasets.Dataset.map). Dies gewährt uns zusätzliche Flexibilität, wenn wir zusätzliche Vorverarbeitung als nur die Tokenisierung benötigen. Die `map()`-Methode funktioniert, indem sie eine Funktion auf jedes Element des Datensatzes anwendet, also definieren wir eine Funktion, die unsere Inputs tokenisiert: - -```py -def tokenize_function(example): - return tokenizer(example["sentence1"], example["sentence2"], truncation=True) -``` - -Diese Funktion nimmt ein Dictionary (wie die Elemente unseres Datensatzes) und gibt ein neues Dictionary mit den Schlüsselwerten `input_ids`, `attention_mask` und `token_type_ids` zurück. Beachte, dass es auch funktioniert, wenn das `example`-Dictionary mehrere Beispiele enthält (jeder Schlüsselwert als Liste von Sätzen), da der `Tokenizer`, wie zuvor gesehen, mit Listen von Satzpaaren arbeitet. Dadurch können wir die Option `batched=True` in unserem Aufruf von `map()` verwenden, was die Tokenisierung erheblich beschleunigt. Der `tokenizer` wurde in Rust geschriebenen und ist in der Bibliothek [🤗 Tokenizers](https://github.com/huggingface/tokenizers) verfügbar. Dieser Tokenizer kann sehr schnell arbeiten, wenn wir ihm viele Inputs auf einmal zum Verarbeiten geben. Note that we've left the `padding` argument out in our tokenization function for now. - -Beachte, dass wir das `padding`-Argument vorerst in unserer Tokenisierungsfunktion ausgelassen haben. Dies liegt daran, dass das Anwenden von Padding auf alle Elemente unserer Daten auf die maximale Länge nicht effizient ist: Es ist besser, die Proben aufzufüllen, wenn wir ein Batch erstellen, da wir dann nur auf die maximale Länge in diesem Batch auffüllen müssen und nicht auf die maximale Länge in den gesamten Datensatz. Dies kann viel Zeit und Rechenleistung sparen, besonders wenn die Eingaben stark variable Längen haben! - -So wenden wir die Tokenisierungsfunktion auf alle unsere Datensätze gleichzeitig an. In unserem Aufruf von `map` verwenden wir `batched=True`, damit die Funktion auf mehrere Elemente des Datensatzes gleichzeitig angewendet wird und nicht auf jedes Element separat. Dies ermöglicht eine schnellere Vorverarbeitung. - -```py -tokenized_datasets = raw_datasets.map(tokenize_function, batched=True) -tokenized_datasets -``` - -Die Bibliothek 🤗 Datasets verarbeitet Datensätzen indem sie neue Felder hinzuzufügen, eines für jeden Schlüssel im Dictionary, der von der Vorverarbeitungsfunktion zurückgegeben wird: - -```python out -DatasetDict({ - train: Dataset({ - features: ['attention_mask', 'idx', 'input_ids', 'label', 'sentence1', 'sentence2', 'token_type_ids'], - num_rows: 3668 - }) - validation: Dataset({ - features: ['attention_mask', 'idx', 'input_ids', 'label', 'sentence1', 'sentence2', 'token_type_ids'], - num_rows: 408 - }) - test: Dataset({ - features: ['attention_mask', 'idx', 'input_ids', 'label', 'sentence1', 'sentence2', 'token_type_ids'], - num_rows: 1725 - }) -}) -``` - -Du kannst sogar Multiprocessing verwenden, wenn du die Vorverarbeitungsfunktion mit `map()` anwendest, indem du ein `num_proc`-Argument übergiebst. Wir haben dies hier nicht getan, weil die 🤗 Tokenizers-Bibliothek bereits mehrere Threads verwendet, um unsere Samples schneller zu tokenisieren. Wenn du keinen schnellen Tokenizer verwendest, der von dieser Bibliothek unterstützt wird, würde dies allerdings die Vorverarbeitung beschleunigen. - -Unsere `tokenize_function` gibt ein Dictionary mit den Schlüsselwerten `input_ids`, `attention_mask` und `token_type_ids` zurück, also werden diese drei Felder zu allen Splits unseres Datensatzes hinzugefügt. Beachte, dass wir auch vorhandene Felder ändern könnten, wenn unsere Vorverarbeitungsfunktion einen neuen Wert für einen vorhandenen Schlüsselwert in dem Datensatz zurückgegeben hätte, auf den wir `map()` angewendet haben. - -Zuletzt, müssen wir alle Beispiele auf die Länge des längsten Elements aufzufüllen, wenn wir Elemente zusammenfassen – eine Technik, die wir als *Dynamisches Padding* bezeichnen. - -### Dynamisches Padding - - - -{#if fw === 'pt'} - -Die Funktion, die für das Zusammenstellen von Samples innerhalb eines Batches verantwortlich ist, wird als *Collate-Funktion* bezeichnet. Es ist ein Argument, das du übergeben kannst, wenn du einen `DataLoader` baust, wobei es standardmäßig eine Funktion ist, die die Daten in PyTorch-Tensoren umwandelt und zusammenfügt (rekursiv wenn die Elemente Listen, Tupel oder Dictionaries sind). Dies ist in unserem Fall nicht möglich, da die Inputs nicht alle gleich groß sind. Das Padding haben wir bewusst aufgeschoben, um es bei jedem Batch nur bei Bedarf anzuwenden und überlange Inputs mit massivem Padding zu vermeiden. Dies beschleunigt das Training zwar, aber beachte, dass das Training auf einer TPU Probleme verursachen kann – TPUs bevorzugen feste Formen, auch wenn das ein zusätzliches Padding erfordert. - -{:else} - -Die Funktion, die für das Zusammenstellen von Samples innerhalb eines Batches verantwortlich ist, wird als *Collate-Funktion* bezeichnet. Es ist ein Argument, das du übergeben kannst, wenn du einen `DataLoader` baust, wobei es standardmäßig eine Funktion ist, die die Daten in tf.Tensor umwandelt und zusammenfügt (rekursiv wenn die Elemente Listen, Tupel oder Dictionaries sind). Dies ist in unserem Fall nicht möglich, da die Inputs nicht alle gleich groß sind. Das Padding haben wir bewusst aufgeschoben, um es bei jedem Batch nur bei Bedarf anzuwenden und überlange Inputs mit massivem Padding zu vermeiden. Dies beschleunigt das Training zwar, aber beachte, dass das Training auf einer TPU Probleme verursachen kann – TPUs bevorzugen feste Formen, auch wenn das ein zusätzliches Padding erfordert. - -{/if} - -In der Praxis müssen wir eine Collate-Funktion definieren, die die korrekte Menge an Padding auf die Elemente des Datensatzes anwendet, die wir in einem Batch haben möchten. Glücklicherweise stellt uns die 🤗 Transformers-Bibliothek über `DataCollatorWithPadding` eine solche Funktion zur Verfügung. Wenn sie instanziert wird, braucht es einen Tokenizer (um zu wissen, welches Padding-token verwendet werden soll und ob das Modell erwartet, dass sich das Padding links oder rechts von den Inputs befindet) und übernimmt alles was wir brauchen: - -{#if fw === 'pt'} -```py -from transformers import DataCollatorWithPadding - -data_collator = DataCollatorWithPadding(tokenizer=tokenizer) -``` -{:else} -```py -from transformers import DataCollatorWithPadding - -data_collator = DataCollatorWithPadding(tokenizer=tokenizer, return_tensors="tf") -``` -{/if} - -Um dieses neue Werkzeug zu testen, nehmen wir einige Elemente aus den Trainingsdaten, die wir als Batch verwenden möchten. Hier entfernen wir die Spalten `idx`, `sentence1` und `sentence2`, da sie nicht benötigt werden und Strings enthalten (wir können keine Tensoren mit Strings erstellen) und sehen uns die Länge jedes Eintrags im Batch an: - -```py -samples = tokenized_datasets["train"][:8] -samples = {k: v for k, v in samples.items() if k not in ["idx", "sentence1", "sentence2"]} -[len(x) for x in samples["input_ids"]] -``` - -```python out -[50, 59, 47, 67, 59, 50, 62, 32] -``` - -Wenig überraschen erhalten wir Samples unterschiedlicher Länge von 32 bis 67. Dynamisches Padding bedeutet, dass die Elemente in diesem Batch alle auf eine Länge von 67 aufgefüllt werden, die maximale Länge innerhalb des Batches. Ohne dynamisches Auffüllen müssten alle Einträge auf die maximale Länge im gesamten Datensatz oder auf die maximale Länge die das Modell akzeptiert, aufgefüllt werden. Lass uns noch einmal überprüfen, ob unser `data_collator` den Stapel dynamisch richtig auffüllt: - -```py -batch = data_collator(samples) -{k: v.shape for k, v in batch.items()} -``` - -{#if fw === 'tf'} - -```python out -{'attention_mask': TensorShape([8, 67]), - 'input_ids': TensorShape([8, 67]), - 'token_type_ids': TensorShape([8, 67]), - 'labels': TensorShape([8])} -``` - -{:else} - -```python out -{'attention_mask': torch.Size([8, 67]), - 'input_ids': torch.Size([8, 67]), - 'token_type_ids': torch.Size([8, 67]), - 'labels': torch.Size([8])} -``` - -Das sieht gut aus! Jetzt, da wir vom Rohtext zu Batches übergegangen sind, mit denen unser Modell umgehen kann, sind wir bereit zum fein-tunen! - -{/if} - -> [!TIP] -> ✏️ **Probier es aus!** Repliziere die Vorverarbeitung auf dem GLUE SST-2-Datensatz. Es ist ein bisschen anders, da es aus einzelnen Sätzen statt aus Paaren besteht, aber der Rest von dem, was wir gemacht haben, sollte gleich aussehen. Alternative wäre eine schwierigere Herausforderung, eine Vorverarbeitungsfunktion zu schreiben, die bei allen GLUE-Aufgaben funktioniert. - -{#if fw === 'tf'} - -Jetzt, da wir unseren Datensatz und einen DataCollator haben, müssen wir sie verbinden. Wir könnten Batches manuell laden und sortieren, aber das ist eine Menge Arbeit und wahrscheinlich auch nicht sehr sonderlich performant. Stattdessen gibt es eine einfache Methode, die dieses Problem performant löst: `to_tf_dataset()`. Dadurch wird ein `tf.data.Dataset` um den Datensatz gewickelt, mit einer optionalen Kollatierungsfunktion. `tf.data.Dataset` ist ein natives TensorFlow-Format, das Keras für `model.fit()` verwenden kann. Diese Methode kann einen 🤗-Datensatz ohne Umstände in ein fürs Training vorbereitetes Format konvertieren. Sehen wir es uns nun mit unserem Datensatz in Aktion an! - -```py -tf_train_dataset = tokenized_datasets["train"].to_tf_dataset( - columns=["attention_mask", "input_ids", "token_type_ids"], - label_cols=["labels"], - shuffle=True, - collate_fn=data_collator, - batch_size=8, -) - -tf_validation_dataset = tokenized_datasets["validation"].to_tf_dataset( - columns=["attention_mask", "input_ids", "token_type_ids"], - label_cols=["labels"], - shuffle=False, - collate_fn=data_collator, - batch_size=8, -) -``` -Und das was's! Wir können Datensätze in das nächste Kapitel mitnehmen, wo das Training nach all der harten Arbeit der Datenvorverarbeitung angenehm unkompliziert sein wird. - -{/if} + + +# Vorbereitung der Daten + +{#if fw === 'pt'} + + + +{:else} + + + +{/if} + +{#if fw === 'pt'} +Wir fahren mit dem Beispiel aus dem [vorigen Kapitel](/course/chapter2) fort. Folgenderweise würden wir einen Sequenzklassifikator mit einem Batch in PyTorch trainieren: + +```python +import torch +from torch.optim import AdamW +from transformers import AutoTokenizer, AutoModelForSequenceClassification + +# Genau wie vorher +checkpoint = "bert-base-uncased" +tokenizer = AutoTokenizer.from_pretrained(checkpoint) +model = AutoModelForSequenceClassification.from_pretrained(checkpoint) +sequences = [ + "I've been waiting for a HuggingFace course my whole life.", # Ich habe mein ganzes Leben auf einen HuggingFace-Kurs gewartet. + "This course is amazing!", # Dieser Kurs ist fantastisch! +] +batch = tokenizer(sequences, padding=True, truncation=True, return_tensors="pt") + +# Dies ist neu +batch["labels"] = torch.tensor([1, 1]) + +optimizer = AdamW(model.parameters()) +loss = model(**batch).loss +loss.backward() +optimizer.step() +``` +{:else} +Wir fahren mit dem Beispiel aus dem [vorigen Kapitel](/course/chapter2) fort. Folgenderweise würden wir einen Sequenzklassifikator mit einem Batch in Tensorflow trainieren: + +```python +import tensorflow as tf +import numpy as np +from transformers import AutoTokenizer, TFAutoModelForSequenceClassification + +# Genau wie vorher +checkpoint = "bert-base-uncased" +tokenizer = AutoTokenizer.from_pretrained(checkpoint) +model = TFAutoModelForSequenceClassification.from_pretrained(checkpoint) +sequences = [ + "I've been waiting for a HuggingFace course my whole life.", # Ich habe mein ganzes Leben auf einen HuggingFace-Kurs gewartet. + "This course is amazing!", # Dieser Kurs ist fantastisch! +] +batch = dict(tokenizer(sequences, padding=True, truncation=True, return_tensors="tf")) + +# Dies ist neu +model.compile(optimizer="adam", loss="sparse_categorical_crossentropy") +labels = tf.convert_to_tensor([1, 1]) +model.train_on_batch(batch, labels) +``` +{/if} + +Natürlich würde das Training von Modellen mit nur zwei Sätzen keine sonderlich guten Ergebnisse liefern. Um bessere Ergebnisse zu erzielen, müssen wir einen größeren Datensatz vorbereiten. + +In diesem Abschnitt verwenden wir den MRPC-Datensatz (Microsoft Research Paraphrase Corpus) als Beispiel. Dieser wurde in einem [Paper](https://www.aclweb.org/anthology/I05-5002.pdf) von William B. Dolan und Chris Brockett veröffentlicht. Der Datensatz besteht aus insgesamt 5.801 Satzpaaren und enthält ein Label, das angibt, ob es sich bei einem Paar um Paraphrasen handelt (d.h. ob beide Sätze dasselbe bedeuten). Wir haben diesen Datensatz für dieses Kapitel ausgewählt, weil es sich um einen kleinen Datensatz handelt, sodass es einfach ist, während dem Training zu experimentieren. + +### Laden eines Datensatzes vom Hub + +{#if fw === 'pt'} + +{:else} + +{/if} + +Das Hub enthält nicht nur Modelle; Es hat auch mehrere Datensätze in vielen verschiedenen Sprachen. Du kannst die Datensätze [hier](https://huggingface.co/datasets) durchsuchen, und wir empfehlen, einen weiteren Datensatz zu laden und zu verarbeiten, sobald Sie diesen Abschnitt abgeschlossen haben (die Dokumentation befindet sich [hier](https://huggingface.co/docs/datasets/loading)). Aber jetzt konzentrieren wir uns auf den MRPC-Datensatz! Dies ist einer der 10 Datensätze, aus denen sich das [GLUE-Benchmark](https://gluebenchmark.com/) zusammensetzt. Dies ist ein akademisches Benchmark, das verwendet wird, um die Performance von ML-Modellen in 10 verschiedenen Textklassifizierungsaufgaben zu messen. + +Die Bibliothek 🤗 Datasets bietet einen leichten Befehl zum Herunterladen und Caching eines Datensatzes aus dem Hub. Wir können den MRPC-Datensatz wie folgt herunterladen: + +⚠️ ** Warnung** Stelle sicher, dass `datasets` installiert ist, indem du `pip install datasets` ausführst. Dann lade den MRPC-Datensatz und drucke ihn aus, um zu sehen, was er enthält. + + +```py +from datasets import load_dataset + +raw_datasets = load_dataset("glue", "mrpc") +raw_datasets +``` + +```python out +DatasetDict({ + train: Dataset({ + features: ['sentence1', 'sentence2', 'label', 'idx'], + num_rows: 3668 + }) + validation: Dataset({ + features: ['sentence1', 'sentence2', 'label', 'idx'], + num_rows: 408 + }) + test: Dataset({ + features: ['sentence1', 'sentence2', 'label', 'idx'], + num_rows: 1725 + }) +}) +``` + +Wie du sehen kannst, erhalten wir ein `DatasetDict`-Objekt, das die Trainingsdaten, die Validierungsdaten und die Testdaten enthält. Jedes Objekt enthält mehrere Spalten (`sentence1`, `sentence2`, `label` und `idx`) und eine unterschiedliche Anzahl an Zeilen, dies ist die Anzahl der Elemente in jedem Datensatz (also gibt es 3.668 Satzpaare in den Trainingsdaten, 408 in den Validierungsdaten und 1.725 in den Testdaten). + +Dieser Befehl lädt das Dataset herunter und speichert es im Cache, standardmäßig in *~/.cache/huggingface/dataset*. Wir Erinnern uns an Kapitel 2, dass der Cache-Ordner anpasst werden kann, indem man die Umgebungsvariable `HF_HOME` setzt. + +Wir können auf jedes Satzpaar in unserem `raw_datasets`-Objekt zugreifen, indem wir wie bei einem Dictionary einen Schlüsselwert als Index verwenden: + +```py +raw_train_dataset = raw_datasets["train"] +raw_train_dataset[0] +``` + +```python out +{'idx': 0, + 'label': 1, + 'sentence1': 'Amrozi accused his brother , whom he called " the witness " , of deliberately distorting his evidence .', + 'sentence2': 'Referring to him as only " the witness " , Amrozi accused his brother of deliberately distorting his evidence .'} +``` + +Wir stellen fest, dass die Labels bereits Ganzzahlen sind, sodass wir dort keine Vorverarbeitung durchführen müssen. Wir können die `features` von `raw_train_dataset` untersuchen, um zu erfahren, welche Ganzzahl welchem Label entspricht. Der folgende Befehl gibt uns den Variablentyp zurück: + +```py +raw_train_dataset.features +``` + +```python out +{'sentence1': Value(dtype='string', id=None), + 'sentence2': Value(dtype='string', id=None), + 'label': ClassLabel(num_classes=2, names=['not_equivalent', 'equivalent'], names_file=None, id=None), + 'idx': Value(dtype='int32', id=None)} +``` + +Hinter den Kulissen ist `label` vom Typ `ClassLabel`, und die Zuordnung von Ganzzahlen zum Labelnamen wird im Ordner *names* gespeichert. `0` entspricht `not_equivalent`, also "nicht äquivalent", und `1` entspricht `equivalent`, also "äquivalent". + +> [!TIP] +> ✏️ **Probier es aus!** Sieh dir das Element 15 der Trainingsdaten und Element 87 des Validierungsdaten an. Was sind ihre Labels? + +### Vorverarbeitung eines Datensatzes + +{#if fw === 'pt'} + +{:else} + +{/if} + +Um den Datensatz vorzubereiten, müssen wir den Text in Zahlen umwandeln, die das Modell sinnvoll verarbeiten kann. Im [vorherigen Kapitel](/course/chapter2) haben wir gesehen, dass dies mit einem Tokenizer gemacht wird. Wir können den Tokenizer mit einem Satz oder einer Liste von Sätzen füttern, sodass wir die ersten und zweiten Sätze jedes Paares wie folgt direkt tokenisieren können: + +```py +from transformers import AutoTokenizer + +checkpoint = "bert-base-uncased" +tokenizer = AutoTokenizer.from_pretrained(checkpoint) +tokenized_sentences_1 = tokenizer(raw_datasets["train"]["sentence1"]) +tokenized_sentences_2 = tokenizer(raw_datasets["train"]["sentence2"]) +``` + +Wir können jedoch nicht einfach zwei Sequenzen an das Modell übergeben und eine Vorhersage erhalten, ob die beiden Sätze paraphrasiert sind oder nicht. Wir müssen die beiden Sequenzen als Paar behandeln und die entsprechende Vorverarbeitung anwenden. Glücklicherweise kann der Tokenizer auch ein Sequenzpaar nehmen und es so vorbereiten, wie es unser BERT-Modell erwartet: + +```py +inputs = tokenizer("This is the first sentence.", "This is the second one.") +inputs +``` + +```python out +{ + 'input_ids': [101, 2023, 2003, 1996, 2034, 6251, 1012, 102, 2023, 2003, 1996, 2117, 2028, 1012, 102], + 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], + 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] +} +``` + +In [Kapitel 2](/course/chapter2) haben wir die Schlüsselwerte `input_ids` und `attention_mask` behandelt, allerdings haben wir es aufgeschoben, über `token_type_ids` zu sprechen. In diesem Beispiel teilt diese dem Modell mit, welcher Teil des Input der erste Satz und welcher der zweite Satz ist. + +> [!TIP] +> ✏️ **Probier es aus!** Nimm Element 15 der Trainingsdaten und tokenisiere die beiden Sätze separat und als Paar. Wo liegt der Unterschied zwischen den beiden Ergebnissen? + +Wenn wir die IDs in `input_ids` zurück in Worte dekodieren: + +```py +tokenizer.convert_ids_to_tokens(inputs["input_ids"]) +``` + +dann bekommen wir: + +```python out +['[CLS]', 'this', 'is', 'the', 'first', 'sentence', '.', '[SEP]', 'this', 'is', 'the', 'second', 'one', '.', '[SEP]'] +``` + +Wir sehen also wenn es zwei Sätze gibt, dass das Modell erwartet, dass die Inputs die Form "[CLS] Satz1 [SEP] Satz2 [SEP]" haben. Wenn wir dies mit den `token_type_ids` abgleichen, erhalten wir: + +```python out +['[CLS]', 'this', 'is', 'the', 'first', 'sentence', '.', '[SEP]', 'this', 'is', 'the', 'second', 'one', '.', '[SEP]'] +[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1] +``` + +Wie du sehen kannst, haben die Teile der Eingabe, die `[CLS] Satz1 [SEP]` entsprechen, alle eine Token-Typ-ID von `0`, während die anderen Teile, die `Satz2 [SEP]` entsprechen, alle einer Token-Typ-ID von `1` enthalten. + +Beachte, dass die Auswahl eines anderen Checkpoints nicht unbedingt die `token_type_ids` in Ihren tokenisierten Inputs haben (z.B. werden sie nicht zurückgegeben, wenn ein DistilBERT-Modell verwendet wird). Sie werden nur zurückgegeben, wenn das Modell weiß was damit zu tun ist, weil es die Toke-Typ-Ids während des Vortrainings gesehen hat. + +In diesem Fall ist BERT mit Token-Typ-IDs vortrainiert worden, und zusätzlich zu dem maskierten Sprachmodellierungsziel aud [Kapitel 1](/course/chapter1), hat es ein zusätzliches Vorhersageziel namens _next sentence prediction_ (d.h. Vorhersage des nächsten Satzes). Das Ziel dieser Aufgabe ist es, die Beziehung zwischen Satzpaaren zu modellieren. + +Bei der Vorhersage des nächsten Satzes werden dem Modell Satzpaare (mit zufällig maskierten Token) bereitgestellt und erwartet, vorherzusagen, ob auf den ersten Satz der zweite Satz folgt. Um die Aufgabe non-trivial zu machen, folgen sich die Hälfte der Sätze in dem Originaldokument, aus dem sie extrahiert wurden, aufeinander, und in der anderen Hälfte stammen die beiden Sätze aus zwei verschiedenen Dokumenten. + +Im Allgemeinen muss man sich keine Gedanken darüber machen, ob Ihre tokenisierten Inputs `token_type_ids` enthalten oder nicht: Solange du denselben Checkpoint für den Tokenizer und das Modell verwendest, ist alles in Ordnung, da der Tokenizer weiß, was er dem Modell bereitstellen soll. + +Nachdem wir nun gesehen haben, wie unser Tokenizer mit einem Satzpaar umgehen kann, können wir damit unseren gesamten Datensatz tokenisieren: Wie im [vorherigen Kapitel](/course/chapter2) können wir dem Tokenizer eine Liste von Satzpaaren einspeisen, indem du ihm die Liste der ersten Sätze und dann die Liste der zweiten Sätze gibst. Dies ist auch kompatibel mit den Optionen zum Padding und Trunkieren, die wir in [Kapitel 2](/course/chapter2) gesehen haben. Eine Möglichkeit, den Trainingsdatensatz vorzuverarbeiten, ist also: + +```py +tokenized_dataset = tokenizer( + raw_datasets["train"]["sentence1"], + raw_datasets["train"]["sentence2"], + padding=True, + truncation=True, +) +``` + +Das funktioniert gut, hat aber den Nachteil, dass ein Dictionary zurückgegeben wird (mit unseren Schlüsselwörtern `input_ids`, `attention_mask` und `token_type_ids` und Werten aus Listen von Listen). Es funktioniert auch nur, wenn du genügend RAM hast, um den gesamten Datensatz während der Tokenisierung zu im RAM zwischen zu speichern (während die Datensätze aus der Bibliothek 🤗 Datasets [Apache Arrow](https://arrow.apache.org/) Dateien sind, die auf der Festplatte gespeichert sind, sodass nur die gewünschten Samples im RAM geladen sind). + +Um die Daten als Datensatz zu speichern, verwenden wir die Methode [`Dataset.map()`](https://huggingface.co/docs/datasets/package_reference/main_classes#datasets.Dataset.map). Dies gewährt uns zusätzliche Flexibilität, wenn wir zusätzliche Vorverarbeitung als nur die Tokenisierung benötigen. Die `map()`-Methode funktioniert, indem sie eine Funktion auf jedes Element des Datensatzes anwendet, also definieren wir eine Funktion, die unsere Inputs tokenisiert: + +```py +def tokenize_function(example): + return tokenizer(example["sentence1"], example["sentence2"], truncation=True) +``` + +Diese Funktion nimmt ein Dictionary (wie die Elemente unseres Datensatzes) und gibt ein neues Dictionary mit den Schlüsselwerten `input_ids`, `attention_mask` und `token_type_ids` zurück. Beachte, dass es auch funktioniert, wenn das `example`-Dictionary mehrere Beispiele enthält (jeder Schlüsselwert als Liste von Sätzen), da der `Tokenizer`, wie zuvor gesehen, mit Listen von Satzpaaren arbeitet. Dadurch können wir die Option `batched=True` in unserem Aufruf von `map()` verwenden, was die Tokenisierung erheblich beschleunigt. Der `tokenizer` wurde in Rust geschriebenen und ist in der Bibliothek [🤗 Tokenizers](https://github.com/huggingface/tokenizers) verfügbar. Dieser Tokenizer kann sehr schnell arbeiten, wenn wir ihm viele Inputs auf einmal zum Verarbeiten geben. Note that we've left the `padding` argument out in our tokenization function for now. + +Beachte, dass wir das `padding`-Argument vorerst in unserer Tokenisierungsfunktion ausgelassen haben. Dies liegt daran, dass das Anwenden von Padding auf alle Elemente unserer Daten auf die maximale Länge nicht effizient ist: Es ist besser, die Proben aufzufüllen, wenn wir ein Batch erstellen, da wir dann nur auf die maximale Länge in diesem Batch auffüllen müssen und nicht auf die maximale Länge in den gesamten Datensatz. Dies kann viel Zeit und Rechenleistung sparen, besonders wenn die Eingaben stark variable Längen haben! + +So wenden wir die Tokenisierungsfunktion auf alle unsere Datensätze gleichzeitig an. In unserem Aufruf von `map` verwenden wir `batched=True`, damit die Funktion auf mehrere Elemente des Datensatzes gleichzeitig angewendet wird und nicht auf jedes Element separat. Dies ermöglicht eine schnellere Vorverarbeitung. + +```py +tokenized_datasets = raw_datasets.map(tokenize_function, batched=True) +tokenized_datasets +``` + +Die Bibliothek 🤗 Datasets verarbeitet Datensätzen indem sie neue Felder hinzuzufügen, eines für jeden Schlüssel im Dictionary, der von der Vorverarbeitungsfunktion zurückgegeben wird: + +```python out +DatasetDict({ + train: Dataset({ + features: ['attention_mask', 'idx', 'input_ids', 'label', 'sentence1', 'sentence2', 'token_type_ids'], + num_rows: 3668 + }) + validation: Dataset({ + features: ['attention_mask', 'idx', 'input_ids', 'label', 'sentence1', 'sentence2', 'token_type_ids'], + num_rows: 408 + }) + test: Dataset({ + features: ['attention_mask', 'idx', 'input_ids', 'label', 'sentence1', 'sentence2', 'token_type_ids'], + num_rows: 1725 + }) +}) +``` + +Du kannst sogar Multiprocessing verwenden, wenn du die Vorverarbeitungsfunktion mit `map()` anwendest, indem du ein `num_proc`-Argument übergiebst. Wir haben dies hier nicht getan, weil die 🤗 Tokenizers-Bibliothek bereits mehrere Threads verwendet, um unsere Samples schneller zu tokenisieren. Wenn du keinen schnellen Tokenizer verwendest, der von dieser Bibliothek unterstützt wird, würde dies allerdings die Vorverarbeitung beschleunigen. + +Unsere `tokenize_function` gibt ein Dictionary mit den Schlüsselwerten `input_ids`, `attention_mask` und `token_type_ids` zurück, also werden diese drei Felder zu allen Splits unseres Datensatzes hinzugefügt. Beachte, dass wir auch vorhandene Felder ändern könnten, wenn unsere Vorverarbeitungsfunktion einen neuen Wert für einen vorhandenen Schlüsselwert in dem Datensatz zurückgegeben hätte, auf den wir `map()` angewendet haben. + +Zuletzt, müssen wir alle Beispiele auf die Länge des längsten Elements aufzufüllen, wenn wir Elemente zusammenfassen – eine Technik, die wir als *Dynamisches Padding* bezeichnen. + +### Dynamisches Padding + + + +{#if fw === 'pt'} + +Die Funktion, die für das Zusammenstellen von Samples innerhalb eines Batches verantwortlich ist, wird als *Collate-Funktion* bezeichnet. Es ist ein Argument, das du übergeben kannst, wenn du einen `DataLoader` baust, wobei es standardmäßig eine Funktion ist, die die Daten in PyTorch-Tensoren umwandelt und zusammenfügt (rekursiv wenn die Elemente Listen, Tupel oder Dictionaries sind). Dies ist in unserem Fall nicht möglich, da die Inputs nicht alle gleich groß sind. Das Padding haben wir bewusst aufgeschoben, um es bei jedem Batch nur bei Bedarf anzuwenden und überlange Inputs mit massivem Padding zu vermeiden. Dies beschleunigt das Training zwar, aber beachte, dass das Training auf einer TPU Probleme verursachen kann – TPUs bevorzugen feste Formen, auch wenn das ein zusätzliches Padding erfordert. + +{:else} + +Die Funktion, die für das Zusammenstellen von Samples innerhalb eines Batches verantwortlich ist, wird als *Collate-Funktion* bezeichnet. Es ist ein Argument, das du übergeben kannst, wenn du einen `DataLoader` baust, wobei es standardmäßig eine Funktion ist, die die Daten in tf.Tensor umwandelt und zusammenfügt (rekursiv wenn die Elemente Listen, Tupel oder Dictionaries sind). Dies ist in unserem Fall nicht möglich, da die Inputs nicht alle gleich groß sind. Das Padding haben wir bewusst aufgeschoben, um es bei jedem Batch nur bei Bedarf anzuwenden und überlange Inputs mit massivem Padding zu vermeiden. Dies beschleunigt das Training zwar, aber beachte, dass das Training auf einer TPU Probleme verursachen kann – TPUs bevorzugen feste Formen, auch wenn das ein zusätzliches Padding erfordert. + +{/if} + +In der Praxis müssen wir eine Collate-Funktion definieren, die die korrekte Menge an Padding auf die Elemente des Datensatzes anwendet, die wir in einem Batch haben möchten. Glücklicherweise stellt uns die 🤗 Transformers-Bibliothek über `DataCollatorWithPadding` eine solche Funktion zur Verfügung. Wenn sie instanziert wird, braucht es einen Tokenizer (um zu wissen, welches Padding-token verwendet werden soll und ob das Modell erwartet, dass sich das Padding links oder rechts von den Inputs befindet) und übernimmt alles was wir brauchen: + +{#if fw === 'pt'} +```py +from transformers import DataCollatorWithPadding + +data_collator = DataCollatorWithPadding(tokenizer=tokenizer) +``` +{:else} +```py +from transformers import DataCollatorWithPadding + +data_collator = DataCollatorWithPadding(tokenizer=tokenizer, return_tensors="tf") +``` +{/if} + +Um dieses neue Werkzeug zu testen, nehmen wir einige Elemente aus den Trainingsdaten, die wir als Batch verwenden möchten. Hier entfernen wir die Spalten `idx`, `sentence1` und `sentence2`, da sie nicht benötigt werden und Strings enthalten (wir können keine Tensoren mit Strings erstellen) und sehen uns die Länge jedes Eintrags im Batch an: + +```py +samples = tokenized_datasets["train"][:8] +samples = {k: v for k, v in samples.items() if k not in ["idx", "sentence1", "sentence2"]} +[len(x) for x in samples["input_ids"]] +``` + +```python out +[50, 59, 47, 67, 59, 50, 62, 32] +``` + +Wenig überraschen erhalten wir Samples unterschiedlicher Länge von 32 bis 67. Dynamisches Padding bedeutet, dass die Elemente in diesem Batch alle auf eine Länge von 67 aufgefüllt werden, die maximale Länge innerhalb des Batches. Ohne dynamisches Auffüllen müssten alle Einträge auf die maximale Länge im gesamten Datensatz oder auf die maximale Länge die das Modell akzeptiert, aufgefüllt werden. Lass uns noch einmal überprüfen, ob unser `data_collator` den Stapel dynamisch richtig auffüllt: + +```py +batch = data_collator(samples) +{k: v.shape for k, v in batch.items()} +``` + +{#if fw === 'tf'} + +```python out +{'attention_mask': TensorShape([8, 67]), + 'input_ids': TensorShape([8, 67]), + 'token_type_ids': TensorShape([8, 67]), + 'labels': TensorShape([8])} +``` + +{:else} + +```python out +{'attention_mask': torch.Size([8, 67]), + 'input_ids': torch.Size([8, 67]), + 'token_type_ids': torch.Size([8, 67]), + 'labels': torch.Size([8])} +``` + +Das sieht gut aus! Jetzt, da wir vom Rohtext zu Batches übergegangen sind, mit denen unser Modell umgehen kann, sind wir bereit zum fein-tunen! + +{/if} + +> [!TIP] +> ✏️ **Probier es aus!** Repliziere die Vorverarbeitung auf dem GLUE SST-2-Datensatz. Es ist ein bisschen anders, da es aus einzelnen Sätzen statt aus Paaren besteht, aber der Rest von dem, was wir gemacht haben, sollte gleich aussehen. Alternative wäre eine schwierigere Herausforderung, eine Vorverarbeitungsfunktion zu schreiben, die bei allen GLUE-Aufgaben funktioniert. + +{#if fw === 'tf'} + +Jetzt, da wir unseren Datensatz und einen DataCollator haben, müssen wir sie verbinden. Wir könnten Batches manuell laden und sortieren, aber das ist eine Menge Arbeit und wahrscheinlich auch nicht sehr sonderlich performant. Stattdessen gibt es eine einfache Methode, die dieses Problem performant löst: `to_tf_dataset()`. Dadurch wird ein `tf.data.Dataset` um den Datensatz gewickelt, mit einer optionalen Kollatierungsfunktion. `tf.data.Dataset` ist ein natives TensorFlow-Format, das Keras für `model.fit()` verwenden kann. Diese Methode kann einen 🤗-Datensatz ohne Umstände in ein fürs Training vorbereitetes Format konvertieren. Sehen wir es uns nun mit unserem Datensatz in Aktion an! + +```py +tf_train_dataset = tokenized_datasets["train"].to_tf_dataset( + columns=["attention_mask", "input_ids", "token_type_ids"], + label_cols=["labels"], + shuffle=True, + collate_fn=data_collator, + batch_size=8, +) + +tf_validation_dataset = tokenized_datasets["validation"].to_tf_dataset( + columns=["attention_mask", "input_ids", "token_type_ids"], + label_cols=["labels"], + shuffle=False, + collate_fn=data_collator, + batch_size=8, +) +``` +Und das was's! Wir können Datensätze in das nächste Kapitel mitnehmen, wo das Training nach all der harten Arbeit der Datenvorverarbeitung angenehm unkompliziert sein wird. + +{/if} diff --git a/chapters/de/chapter3/3.mdx b/chapters/de/chapter3/3.mdx index ef20299a4..b248a578c 100644 --- a/chapters/de/chapter3/3.mdx +++ b/chapters/de/chapter3/3.mdx @@ -1,166 +1,166 @@ - - -# Fine-tuning eine Modells mit der Trainer API - - - - - -🤗 Transformers stellt eine `Trainer`-Klasse bereit, mit der du Modelle auf deinen Datensätzen fein-tunen kannst. Nachdem die Datenverarbeitung im letzten Abschnitt abgeschlossen ist, bleiben nur noch wenige Schritte, um den `Trainer` zu definieren. Der schwierigste Teil ist die Vorbereitung der Umgebung um `Trainer.train()` auszuführen, da dies auf einer CPU sehr langsam läuft. Wenn keine GPU verfügbar ist, kannst du bei [Google Colab] (https://colab.research.google.com/) auf kostenlose GPUs oder TPUs zugreifen. - -In den folgenden Code-Beispielen wird davon ausgegangen, dass du die Beispiele aus dem vorherigen Abschnitt bereits ausgeführt hast. Hier ist eine kurze Zusammenfassung, die dir zeigt, was erwartet wird: - -```py -from datasets import load_dataset -from transformers import AutoTokenizer, DataCollatorWithPadding - -raw_datasets = load_dataset("glue", "mrpc") -checkpoint = "bert-base-uncased" -tokenizer = AutoTokenizer.from_pretrained(checkpoint) - - -def tokenize_function(example): - return tokenizer(example["sentence1"], example["sentence2"], truncation=True) - - -tokenized_datasets = raw_datasets.map(tokenize_function, batched=True) -data_collator = DataCollatorWithPadding(tokenizer=tokenizer) -``` - -### Training - -Als erstes müssen wir eine Klasse `TrainingArguments` definieren, die alle Hyperparameter enthält, die der `Trainer` für das Training und die Evaluation verwendet. Das einzige Argument das hier angegeben werden muss, ist ein Verzeichnis in dem das trainierte Modell sowie die Checkpoints gespeichert werden. Für alles andere können die Standardeinstellungen verwendet werden. Diese sollten für ein grundlegendes Fein-tunen ausreichen. - -```py -from transformers import TrainingArguments - -training_args = TrainingArguments("test-trainer") -``` - -> [!TIP] -> 💡 Wenn du dein Modell während des Trainings automatisch in das Hub hochladen möchtest, kann in `TrainingArguments` das Argument `push_to_hub=True` angegeben werden. Darüber erfahren wir in [Kapitel 4](/course/chapter4/3) mehr. - -Der zweite Schritt ist die Definition unseres Modells. Wie im [vorherigen Kapitel](/course/chapter2) verwenden wir die Klasse `AutoModelForSequenceClassification` mit zwei Labels: - -```py -from transformers import AutoModelForSequenceClassification - -model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) -``` - -Du wirst feststellen, dass du im Gegensatz zu [Kapitel 2](/course/chapter2) eine Warnung erhältst, nachdem du dieses vortrainierte Modell instanziiert hast. Der Grund dafür ist, dass BERT nicht auf die Klassifizierung von Satzpaaren vortrainiert wurde. Deshalb wurde der Kopf des vortrainierten Modells verworfen und stattdessen ein neuer Kopf hinzugefügt, der für die Klassifizierung von Sequenzen geeignet ist. Diese Warnungen weisen darauf hin, dass Teile der Gewichtung nicht verwendet wurden (die Gewichte für den verworfenen Kopf) und dass einige andere zufällig initialisiert wurden (die Gewichte für den neuen Kopf). Abschließend werden wir aufgefordert, das Modell zu trainieren, und genau das werden wir jetzt tun. - -Sobald wir unser Modell haben, können wir einen `Trainer` definieren, indem wir alle bisher erstellten Objekte übergeben - das `Modell`, die `training_args`, die Trainings- und Validierungsdaten, unseren `data_collator` und unseren `tokenizer`: - -```py -from transformers import Trainer - -trainer = Trainer( - model, - training_args, - train_dataset=tokenized_datasets["train"], - eval_dataset=tokenized_datasets["validation"], - data_collator=data_collator, - tokenizer=tokenizer, -) -``` - -Merke: Wenn der `tokenizer` übergeben wird, wie wir es hier getan haben, wird der vom `Trainer` verwendete `data_collator` standardmäßig ein `DataCollatorWithPadding` sein, wie er zuvor definiert wurde. Deshalb kannst du die Zeile `data_collator=data_collator` in diesem Aufruf weglassen. Unabhängig davon war es trotzdem wichtig, diesen Teil der Verarbeitung in Abschnitt 2 zu zeigen! - -Um das Modell auf unserem Datensatz fein-tunen zu können, müssen wir nur die Methode `train()` unseres `Trainers` aufrufen: - -```py -trainer.train() -``` - -Dadurch wird das Fein-tunen gestartet (was auf einer GPU ein paar Minuten dauern sollte) und der Trainingsverlust wird alle 500 Schritte gemeldet. Es wird jedoch nicht zurückgegeben, wie gut (oder schlecht) das Modell funktioniert. Dies liegt an folgenden Punkten: - -1. Wir haben dem `Trainer` nicht mitgeteilt die Performance in der Trainingsschleife auszuwerten, indem wir `evaluation_strategy` entweder auf `"steps"` (alle `eval_steps` auswerten) oder `"epoch"` (am Ende jeder Epoche evaluieren) gesetzt haben. -2. Wir haben dem `Trainer` keine Funktion `compute_metrics()` zur Verfügung gestellt, um während der Evaluation eine Metrik zu berechnen (sonst hätte die Evaluation nur den Verlust ausgegeben, was keine sehr intuitive Zahl ist). - - -### Evaluation - -Im Folgenden wird gezeigt, wie wir eine `compute_metrics()`-Funktion erstellen und sie beim nächsten Training verwenden können. Die Funktion muss ein `EvalPrediction`-Objekt (ein bennantes Tupel mit einem `predictions`-Feld und einem `label_ids`-Feld) annehmen und ein Dictionary zurückgeben, das Strings auf Floats abbildet (die Strings sind die Namen der zurückgegebenen Metriken und die Floats ihre zugehörigen Werte). Um Vorhersagen von unserem Modell zu erhalten, können wir den Befehl "Trainer.predict()" verwenden: - -```py -predictions = trainer.predict(tokenized_datasets["validation"]) -print(predictions.predictions.shape, predictions.label_ids.shape) -``` - -```python out -(408, 2) (408,) -``` - -Die Ausgabe der `predict()`-Methode ist ein weiteres benanntes Tupel mit drei Feldern: `predictions`, `label_ids` und `metrics`. Das Feld `metrics` enthält den Verlust des übergebenen Datensatzes sowie Zeitangaben dazu, wie lange die Vorhersage insgesamt und im Durchschnitt gedauert hat. Sobald wir unsere Funktion `compute_metrics()` fertiggestellt haben und sie an den `Trainer` übergeben, enthält dieses Feld auch die von der `compute_metrics()`-Funktion zurückgegebenen Metriken. - -Die Vorhersagen in `predictions` sind ein zweidimensionales Array mit der Form 408 x 2 (408 ist die Anzahl der Elemente unseres Datensatzes). Das sind die Logits für jedes Element des Datensatzes, das wir an `predict()` übergeben haben (siehe [vorheriges Kapitel](/course/chapter2) dass alle Transformer Modelle Logits zurückgeben). Um diese in Vorhersagen umzuwandeln, die wir mit den Labels vergleichen können, müssen wir den Index mit dem höchsten Wert auf der zweiten Achse nehmen: - -```py -import numpy as np - -preds = np.argmax(predictions.predictions, axis=-1) -``` - -Jetzt können wir diese Vorhersagen in `preds` mit den Labels vergleichen. Wir greifen auf die Metriken aus der 🤗 Bibliothek [Evaluate](https://github.com/huggingface/evaluate/) zurück, um unsere Funktion `compute_metric()` zu erstellen. Die mit dem MRPC-Datensatz verbundenen Metriken können genauso einfach geladen werden, wie wir den Datensatz geladen haben, diesmal mit der Funktion `evaluate.load()`. Das zurückgegebene Objekt verfügt über eine Berechnungsmethode, mit der wir die Metrik auswerten können: - -```py -import evaluate - -metric = evaluate.load("glue", "mrpc") -metric.compute(predictions=preds, references=predictions.label_ids) -``` - -```python out -{'accuracy': 0.8578431372549019, 'f1': 0.8996539792387542} -``` - -Die genauen Ergebnisse können variieren, da die zufällige Initialisierung des Modellkopfes den Optimierungsverlauf und damit die Metriken verändern kann. Hier hat das Modell eine Genauigkeit von 85,78 % über die Validierungsdaten und eine F1-Maß von 89,97 erreicht hat. Dies sind die beiden Kennzahlen, die zur Bewertung der Ergebnisse des MRPC-Datensatzes für den GLUE-Benchmark verwendet werden. In der Tabelle im [BERT-Paper] (https://arxiv.org/pdf/1810.04805.pdf) wird für das Basismodell ein F1-Maß von 88,9 angegeben. Das Paper hat das `uncased` Modell verwendet, während wir derzeit das `cased` Modell verwenden, was das bessere Ergebnis erklärt. - -Zusammenfassend ergibt das unsere Funktion `compute_metrics()`: - -```py -def compute_metrics(eval_preds): - metric = evaluate.load("glue", "mrpc") - logits, labels = eval_preds - predictions = np.argmax(logits, axis=-1) - return metric.compute(predictions=predictions, references=labels) -``` - -Um diese Funktion in Aktion zu sehen, definieren wir einen neuen `Trainer` mit der Funktion "compute_metrics()", um am Ende jeder Epoche Metriken zu melden: - -```py -training_args = TrainingArguments("test-trainer", evaluation_strategy="epoch") -model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) - -trainer = Trainer( - model, - training_args, - train_dataset=tokenized_datasets["train"], - eval_dataset=tokenized_datasets["validation"], - data_collator=data_collator, - tokenizer=tokenizer, - compute_metrics=compute_metrics, -) -``` - -Hier ein Hinweis, dass wir ein neues `TrainingArguments` errstellen, dessen `evaluation_strategy` auf `"epoch"` gesetzt ist, und ein neues Modell definieren - andernfalls würden wir nur das Training des momentanen Modells fortführen, das wir bereits trainiert haben. Um einen neuen Trainingslauf zu starten, führen wir folgendes aus: - -``` -trainer.train() -``` - -Nun werden am Ende jeder Epoche zusätzlich zu den Trainingsverlusten auch die Validierungsverluste und -metriken gemeldet. Auch hier kann die Genauigkeit/F1-Maß aufgrund der zufälligen Initialisierung des Modells zu unserem Beispiel variieren, aber sie sollte in etwa gleich sein. - -Der `Trainer` funktioniert sofort auf mehreren GPUs oder TPUs und bietet zahlreiche Optionen, wie z. B. Training mit gemischter Genauigkeit (verwende `fp16 = True` in deinen Trainingsargumenten). In Kapitel 10 gehen wir auf alle Funktionen ein, die die `Trainer`-Klasse bereitstellt. - -Damit ist die Einführung in das Fein-tunen mit der `Trainer` API abgeschlossen. Beispiele für die gängigsten CL-Aufgaben werden in Kapitel 7 gegeben, aber jetzt schauen wir uns erst einmal an, wie man das Gleiche in PyTorch bewerkstelligen kann. - -> [!TIP] -> ✏️ **Probier es aus!** Fein-tune ein Modell mit dem GLUE SST-2 Datensatz, indem du die Datenverarbeitung aus Abschnitt 2 verwendest. - + + +# Fine-tuning eine Modells mit der Trainer API + + + + + +🤗 Transformers stellt eine `Trainer`-Klasse bereit, mit der du Modelle auf deinen Datensätzen fein-tunen kannst. Nachdem die Datenverarbeitung im letzten Abschnitt abgeschlossen ist, bleiben nur noch wenige Schritte, um den `Trainer` zu definieren. Der schwierigste Teil ist die Vorbereitung der Umgebung um `Trainer.train()` auszuführen, da dies auf einer CPU sehr langsam läuft. Wenn keine GPU verfügbar ist, kannst du bei [Google Colab] (https://colab.research.google.com/) auf kostenlose GPUs oder TPUs zugreifen. + +In den folgenden Code-Beispielen wird davon ausgegangen, dass du die Beispiele aus dem vorherigen Abschnitt bereits ausgeführt hast. Hier ist eine kurze Zusammenfassung, die dir zeigt, was erwartet wird: + +```py +from datasets import load_dataset +from transformers import AutoTokenizer, DataCollatorWithPadding + +raw_datasets = load_dataset("glue", "mrpc") +checkpoint = "bert-base-uncased" +tokenizer = AutoTokenizer.from_pretrained(checkpoint) + + +def tokenize_function(example): + return tokenizer(example["sentence1"], example["sentence2"], truncation=True) + + +tokenized_datasets = raw_datasets.map(tokenize_function, batched=True) +data_collator = DataCollatorWithPadding(tokenizer=tokenizer) +``` + +### Training + +Als erstes müssen wir eine Klasse `TrainingArguments` definieren, die alle Hyperparameter enthält, die der `Trainer` für das Training und die Evaluation verwendet. Das einzige Argument das hier angegeben werden muss, ist ein Verzeichnis in dem das trainierte Modell sowie die Checkpoints gespeichert werden. Für alles andere können die Standardeinstellungen verwendet werden. Diese sollten für ein grundlegendes Fein-tunen ausreichen. + +```py +from transformers import TrainingArguments + +training_args = TrainingArguments("test-trainer") +``` + +> [!TIP] +> 💡 Wenn du dein Modell während des Trainings automatisch in das Hub hochladen möchtest, kann in `TrainingArguments` das Argument `push_to_hub=True` angegeben werden. Darüber erfahren wir in [Kapitel 4](/course/chapter4/3) mehr. + +Der zweite Schritt ist die Definition unseres Modells. Wie im [vorherigen Kapitel](/course/chapter2) verwenden wir die Klasse `AutoModelForSequenceClassification` mit zwei Labels: + +```py +from transformers import AutoModelForSequenceClassification + +model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) +``` + +Du wirst feststellen, dass du im Gegensatz zu [Kapitel 2](/course/chapter2) eine Warnung erhältst, nachdem du dieses vortrainierte Modell instanziiert hast. Der Grund dafür ist, dass BERT nicht auf die Klassifizierung von Satzpaaren vortrainiert wurde. Deshalb wurde der Kopf des vortrainierten Modells verworfen und stattdessen ein neuer Kopf hinzugefügt, der für die Klassifizierung von Sequenzen geeignet ist. Diese Warnungen weisen darauf hin, dass Teile der Gewichtung nicht verwendet wurden (die Gewichte für den verworfenen Kopf) und dass einige andere zufällig initialisiert wurden (die Gewichte für den neuen Kopf). Abschließend werden wir aufgefordert, das Modell zu trainieren, und genau das werden wir jetzt tun. + +Sobald wir unser Modell haben, können wir einen `Trainer` definieren, indem wir alle bisher erstellten Objekte übergeben - das `Modell`, die `training_args`, die Trainings- und Validierungsdaten, unseren `data_collator` und unseren `tokenizer`: + +```py +from transformers import Trainer + +trainer = Trainer( + model, + training_args, + train_dataset=tokenized_datasets["train"], + eval_dataset=tokenized_datasets["validation"], + data_collator=data_collator, + tokenizer=tokenizer, +) +``` + +Merke: Wenn der `tokenizer` übergeben wird, wie wir es hier getan haben, wird der vom `Trainer` verwendete `data_collator` standardmäßig ein `DataCollatorWithPadding` sein, wie er zuvor definiert wurde. Deshalb kannst du die Zeile `data_collator=data_collator` in diesem Aufruf weglassen. Unabhängig davon war es trotzdem wichtig, diesen Teil der Verarbeitung in Abschnitt 2 zu zeigen! + +Um das Modell auf unserem Datensatz fein-tunen zu können, müssen wir nur die Methode `train()` unseres `Trainers` aufrufen: + +```py +trainer.train() +``` + +Dadurch wird das Fein-tunen gestartet (was auf einer GPU ein paar Minuten dauern sollte) und der Trainingsverlust wird alle 500 Schritte gemeldet. Es wird jedoch nicht zurückgegeben, wie gut (oder schlecht) das Modell funktioniert. Dies liegt an folgenden Punkten: + +1. Wir haben dem `Trainer` nicht mitgeteilt die Performance in der Trainingsschleife auszuwerten, indem wir `evaluation_strategy` entweder auf `"steps"` (alle `eval_steps` auswerten) oder `"epoch"` (am Ende jeder Epoche evaluieren) gesetzt haben. +2. Wir haben dem `Trainer` keine Funktion `compute_metrics()` zur Verfügung gestellt, um während der Evaluation eine Metrik zu berechnen (sonst hätte die Evaluation nur den Verlust ausgegeben, was keine sehr intuitive Zahl ist). + + +### Evaluation + +Im Folgenden wird gezeigt, wie wir eine `compute_metrics()`-Funktion erstellen und sie beim nächsten Training verwenden können. Die Funktion muss ein `EvalPrediction`-Objekt (ein bennantes Tupel mit einem `predictions`-Feld und einem `label_ids`-Feld) annehmen und ein Dictionary zurückgeben, das Strings auf Floats abbildet (die Strings sind die Namen der zurückgegebenen Metriken und die Floats ihre zugehörigen Werte). Um Vorhersagen von unserem Modell zu erhalten, können wir den Befehl "Trainer.predict()" verwenden: + +```py +predictions = trainer.predict(tokenized_datasets["validation"]) +print(predictions.predictions.shape, predictions.label_ids.shape) +``` + +```python out +(408, 2) (408,) +``` + +Die Ausgabe der `predict()`-Methode ist ein weiteres benanntes Tupel mit drei Feldern: `predictions`, `label_ids` und `metrics`. Das Feld `metrics` enthält den Verlust des übergebenen Datensatzes sowie Zeitangaben dazu, wie lange die Vorhersage insgesamt und im Durchschnitt gedauert hat. Sobald wir unsere Funktion `compute_metrics()` fertiggestellt haben und sie an den `Trainer` übergeben, enthält dieses Feld auch die von der `compute_metrics()`-Funktion zurückgegebenen Metriken. + +Die Vorhersagen in `predictions` sind ein zweidimensionales Array mit der Form 408 x 2 (408 ist die Anzahl der Elemente unseres Datensatzes). Das sind die Logits für jedes Element des Datensatzes, das wir an `predict()` übergeben haben (siehe [vorheriges Kapitel](/course/chapter2) dass alle Transformer Modelle Logits zurückgeben). Um diese in Vorhersagen umzuwandeln, die wir mit den Labels vergleichen können, müssen wir den Index mit dem höchsten Wert auf der zweiten Achse nehmen: + +```py +import numpy as np + +preds = np.argmax(predictions.predictions, axis=-1) +``` + +Jetzt können wir diese Vorhersagen in `preds` mit den Labels vergleichen. Wir greifen auf die Metriken aus der 🤗 Bibliothek [Evaluate](https://github.com/huggingface/evaluate/) zurück, um unsere Funktion `compute_metric()` zu erstellen. Die mit dem MRPC-Datensatz verbundenen Metriken können genauso einfach geladen werden, wie wir den Datensatz geladen haben, diesmal mit der Funktion `evaluate.load()`. Das zurückgegebene Objekt verfügt über eine Berechnungsmethode, mit der wir die Metrik auswerten können: + +```py +import evaluate + +metric = evaluate.load("glue", "mrpc") +metric.compute(predictions=preds, references=predictions.label_ids) +``` + +```python out +{'accuracy': 0.8578431372549019, 'f1': 0.8996539792387542} +``` + +Die genauen Ergebnisse können variieren, da die zufällige Initialisierung des Modellkopfes den Optimierungsverlauf und damit die Metriken verändern kann. Hier hat das Modell eine Genauigkeit von 85,78 % über die Validierungsdaten und eine F1-Maß von 89,97 erreicht hat. Dies sind die beiden Kennzahlen, die zur Bewertung der Ergebnisse des MRPC-Datensatzes für den GLUE-Benchmark verwendet werden. In der Tabelle im [BERT-Paper] (https://arxiv.org/pdf/1810.04805.pdf) wird für das Basismodell ein F1-Maß von 88,9 angegeben. Das Paper hat das `uncased` Modell verwendet, während wir derzeit das `cased` Modell verwenden, was das bessere Ergebnis erklärt. + +Zusammenfassend ergibt das unsere Funktion `compute_metrics()`: + +```py +def compute_metrics(eval_preds): + metric = evaluate.load("glue", "mrpc") + logits, labels = eval_preds + predictions = np.argmax(logits, axis=-1) + return metric.compute(predictions=predictions, references=labels) +``` + +Um diese Funktion in Aktion zu sehen, definieren wir einen neuen `Trainer` mit der Funktion "compute_metrics()", um am Ende jeder Epoche Metriken zu melden: + +```py +training_args = TrainingArguments("test-trainer", evaluation_strategy="epoch") +model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) + +trainer = Trainer( + model, + training_args, + train_dataset=tokenized_datasets["train"], + eval_dataset=tokenized_datasets["validation"], + data_collator=data_collator, + tokenizer=tokenizer, + compute_metrics=compute_metrics, +) +``` + +Hier ein Hinweis, dass wir ein neues `TrainingArguments` errstellen, dessen `evaluation_strategy` auf `"epoch"` gesetzt ist, und ein neues Modell definieren - andernfalls würden wir nur das Training des momentanen Modells fortführen, das wir bereits trainiert haben. Um einen neuen Trainingslauf zu starten, führen wir folgendes aus: + +``` +trainer.train() +``` + +Nun werden am Ende jeder Epoche zusätzlich zu den Trainingsverlusten auch die Validierungsverluste und -metriken gemeldet. Auch hier kann die Genauigkeit/F1-Maß aufgrund der zufälligen Initialisierung des Modells zu unserem Beispiel variieren, aber sie sollte in etwa gleich sein. + +Der `Trainer` funktioniert sofort auf mehreren GPUs oder TPUs und bietet zahlreiche Optionen, wie z. B. Training mit gemischter Genauigkeit (verwende `fp16 = True` in deinen Trainingsargumenten). In Kapitel 10 gehen wir auf alle Funktionen ein, die die `Trainer`-Klasse bereitstellt. + +Damit ist die Einführung in das Fein-tunen mit der `Trainer` API abgeschlossen. Beispiele für die gängigsten CL-Aufgaben werden in Kapitel 7 gegeben, aber jetzt schauen wir uns erst einmal an, wie man das Gleiche in PyTorch bewerkstelligen kann. + +> [!TIP] +> ✏️ **Probier es aus!** Fein-tune ein Modell mit dem GLUE SST-2 Datensatz, indem du die Datenverarbeitung aus Abschnitt 2 verwendest. + diff --git a/chapters/de/chapter3/3_tf.mdx b/chapters/de/chapter3/3_tf.mdx index 4d4cbb18b..f4e9f80c7 100644 --- a/chapters/de/chapter3/3_tf.mdx +++ b/chapters/de/chapter3/3_tf.mdx @@ -1,180 +1,180 @@ - - -# Modell mit Keras fein-tunen - - - -Wenn du die Datenvorverarbeitung im letzten Abschnitt abgeschlossen hast, brauchst es nur noch wenige Schritte, um das Modell zu trainieren. Beachte jedoch, dass der Befehl `model.fit()` auf einer CPU sehr langsam läuft. Wenn du keinen GPU hast, kannst du auf [Google Colab] (https://colab.research.google.com/) kostenlos auf GPUs und TPUs zugreifen. - -Bei den folgenden Codebeispielen wird davon ausgegangen, dass du die Beispiele aus dem vorherigen Abschnitt bereits ausgeführt hast. Hier ist eine kurze Zusammenfassung, die aufzeigt was erwartet wird: - -```py -from datasets import load_dataset -from transformers import AutoTokenizer, DataCollatorWithPadding -import numpy as np - -raw_datasets = load_dataset("glue", "mrpc") -checkpoint = "bert-base-uncased" -tokenizer = AutoTokenizer.from_pretrained(checkpoint) - - -def tokenize_function(example): - return tokenizer(example["sentence1"], example["sentence2"], truncation=True) - - -tokenized_datasets = raw_datasets.map(tokenize_function, batched=True) - -data_collator = DataCollatorWithPadding(tokenizer=tokenizer, return_tensors="tf") - -tf_train_dataset = tokenized_datasets["train"].to_tf_dataset( - columns=["attention_mask", "input_ids", "token_type_ids"], - label_cols=["labels"], - shuffle=True, - collate_fn=data_collator, - batch_size=8, -) - -tf_validation_dataset = tokenized_datasets["validation"].to_tf_dataset( - columns=["attention_mask", "input_ids", "token_type_ids"], - label_cols=["labels"], - shuffle=False, - collate_fn=data_collator, - batch_size=8, -) -``` - -### Training - -Tensorflow Modelle, die von 🤗 Transformers importiert werden, sind bereits Keras Modelle. Hier ist eine kurze Einführung in Keras. - - - -Sobald wir die Daten haben, braucht es nur noch sehr wenig Arbeit, um mit dem Training zu beginnen. - - - -Wie im [vorherigen Kapitel](/course/chapter2) verwenden wir die Klasse `TFAutoModelForSequenceClassification` mit zwei Labels: - -```py -from transformers import TFAutoModelForSequenceClassification - -model = TFAutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) -``` - -Im Gegensatz zu [Kapitel 2](/course/chapter2) wird eine Warnung angezeigt, nachdem das Modell instanziiert wurde. Das liegt daran, dass BERT nicht auf die Klassifizierung von Satzpaaren vortrainiert wurde. Deshalb wurde der Kopf des vortrainierten Modells verworfen und stattdessen ein neuer Kopf eingefügt, der für die Klassifizierung von Sequenzen geeignet ist. Die Warnungen zeigen an, dass Teil der Gewichtung nicht verwendet wurden (die Gewichte für den verworfenen Kopf) und dass einige andere zufällig initialisiert wurden (die Gewichte für den neuen Kopf). Abschließend wirst du aufgefordert, das Modell zu trainieren, und genau das werden wir jetzt tun. - -Um das Modell mit unserem Datensatz fein-tunen zu können, müssen wir das Modell `kompilieren()` und unsere Daten an die `fit()`-Methode übergeben. Damit wird das Fein-tuning gestartet (dies sollte auf einer GPU ein paar Minuten dauern) und der Trainingsverlust sowie der Validierungsverlust am Ende jeder Epoche gemeldet. - -> [!TIP] -> 🤗 Transformer Modelle haben eine besondere Fähigkeit, die die meisten Keras Modelle nicht haben - sie können automatisch einen geeigneten Verlust verwenden, der intern berechnet wird. Dieser Verlust wird standardmäßig verwendet, wenn in `compile()` kein Verlustargument angegeben wird. Um den internen Verlust zu verwenden, musst du deine Labels als Teil des Input übergeben und nicht als separates Label, wie es normalerweise bei Keras-Modellen der Fall ist. Beispiele dafür gibt es in Teil 2 des Kurses, wobei die Definition der richtigen Verlustfunktion schwierig sein kann. Für die Klassifizierung von Sequenzen eignet sich jedoch eine der Standardverlustfunktionen von Keras, die wir hier verwenden werden. - -```py -from tensorflow.keras.losses import SparseCategoricalCrossentropy - -model.compile( - optimizer="adam", - loss=SparseCategoricalCrossentropy(from_logits=True), - metrics=["accuracy"], -) -model.fit( - tf_train_dataset, - validation_data=tf_validation_dataset, -) -``` - -> [!WARNING] -> Hier gibt es einen sehr häufigen Stolperstein - du *kannst* Keras einfach den Namen des Verlusts als String übergeben, aber standardmäßig geht Keras davon aus, dass du bereits einen Softmax auf die Outputs angewendet hast. Viele Modelle geben jedoch die Werte direkt vor der Anwendung des Softmax als *Logits* aus. Hier ist es wichtig der Keras Verlustfunktion mitzuteilen, dass unser Modell genau diess tut, und das geht nur indem sie direkt aufgerufen wird, und nicht über den Namen mit einem String. - - -### Verbesserung der Trainingsperformance - - - -Wenn du den obigen Code ausprobierst, läuft er zwar, aber du wirst feststellen, dass der Verlust nur langsam oder sporadisch zurückgeht. Die Ursache hierfür ist die *Lernrate*. Wenn der Namen eines Optimierers als String an Keras übergeben wird, initialisiert Keras diesen Optimierer mit Standardwerten für alle Parameter, einschließlich der Lernrate. Aus langjähriger Erfahrung wissen wir, dass Transformer Modelle von einer wesentlich niedrigeren Lernrate profitieren als der Standardwert für Adam. Dieser Standardwert liegt bei 1e-3, auch geschrieben als 10 hoch -3 oder 0,001. Für Transformer ist 5e-5 (0,00005), was etwa zwanzigmal niedriger ist, ist ein viel besserer Ausgangspunkt. - -Zusätzlich zur Senkung der Lernrate haben wir noch einen zweiten Trick in petto: Wir können die Lernrate langsam im Laufe des Trainings verringern. In der Literatur wird dies manchmal als *Decay* oder *Annealing* der Lernrate bezeichnet. In Keras kannst das am besten mit dem *Lernraten-Scheduler* umgesetzt werden. Ein guter Scheduler ist `PolynomialDecay` - trotz des Namens lässt er die Lernrate in den Standardeinstellungen einfach linear vom Anfangswert bis zum Endwert abfallen. Dies ist genau was wir wollen. Um einen Scheduler richtig zu nutzen, müssen wir ihm allerdings sagen, wie lange das Training dauern soll. Das berechnen wir im Folgenden als `num_train_steps`. - -```py -from tensorflow.keras.optimizers.schedules import PolynomialDecay - -batch_size = 8 -num_epochs = 3 -# The number of training steps is the number of samples in the dataset, divided by the batch size then multiplied -# by the total number of epochs. Note that the tf_train_dataset here is a batched tf.data.Dataset, -# not the original Hugging Face Dataset, so its len() is already num_samples // batch_size. -num_train_steps = len(tf_train_dataset) * num_epochs -lr_scheduler = PolynomialDecay( - initial_learning_rate=5e-5, end_learning_rate=0.0, decay_steps=num_train_steps -) -from tensorflow.keras.optimizers import Adam - -opt = Adam(learning_rate=lr_scheduler) -``` - -> [!TIP] -> Die 🤗 Transformer Bibliothek hat eine `create_optimizer()`-Funktion, die einen `AdamW`-Optimierer mit Lernratenabfall erzeugt. Das ist eine praktisches Tool, auf das wir in den nächsten Abschnitten des Kurses im Detail eingehen werden. - -Somit haben wir einen neuen Optimierer definiert und können ihn zum Training verwenden. Zuerst laden wir das Modell neu, um die Änderungen an der Gewichtung aus dem letzten Trainingslauf zurückzusetzen, und dann können wir es mit dem neuen Optimierer kompilieren: - -```py -import tensorflow as tf - -model = TFAutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) -loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) -model.compile(optimizer=opt, loss=loss, metrics=["accuracy"]) -``` - -Jetzt starten wir einen erneuten Trainingslauf mit `fit`: - -```py -model.fit(tf_train_dataset, validation_data=tf_validation_dataset, epochs=3) -``` - -> [!TIP] -> 💡 Wenn du dein Modell während des Trainings automatisch in den Hub hochladen möchtest, kannst du in der Methode `model.fit()` einen `PushToHubCallback` mitgeben. Mehr darüber erfahren wir in [Kapitel 4](/course/chapter4/3) - -### Modell-Vorhersagen - - - - -Trainieren und zusehen, wie der Verlust sinkt, ist ja ganz nett, aber was ist, wenn wir tatsächlich die Ergebnisse des trainierten Modells erhalten wollen? Entweder um Metriken zu berechnen oder um das Modell in der Produktion einzusetzen. Dafür können wir einfach die Methode `predict()` verwenden. Sie liefert uns die *Logits* aus dem Ausgabekopf des Modells, und zwar eine pro Klasse. - -```py -preds = model.predict(tf_validation_dataset)["logits"] -``` - -Wir können diese Logits in die Klassenvorhersagen des Modells umwandeln, indem wir `argmax` verwenden, um den höchsten Logit zu finden, der der wahrscheinlichsten Klasse entspricht: - -```py -class_preds = np.argmax(preds, axis=1) -print(preds.shape, class_preds.shape) -``` - -```python out -(408, 2) (408,) -``` - -Nun können wir diese Vorhersagen in `preds` nutzen, um einige Metriken zu berechnen! Wir können die Metriken, die mit dem MRPC-Datensatz verbunden sind, genauso einfach laden, wie wir den Datensatz geladen haben, in diesem Fall mit der Funktion "evaluate.load()". Das zurückgegebene Objekt verfügt über eine Berechnungsmethode, mit der wir die Metrik berechnen können: - -```py -import evaluate - -metric = evaluate.load("glue", "mrpc") -metric.compute(predictions=class_preds, references=raw_datasets["validation"]["label"]) -``` - -```python out -{'accuracy': 0.8578431372549019, 'f1': 0.8996539792387542} -``` -Die genauen Ergebnisse können variieren, da die zufällige Initialisierung des Modellkopfes die errechneten Metriken verändern kann. Das Modell erreicht über den Validierungsdaten eine Genauigkeit von 85,78 % und ein F1-Maß von 89,97. Dies sind die beiden Kennzahlen, die zur Bewertung der Ergebnisse des MRPC-Datensatzes für das GLUE-Benchmark verwendet werden. In der Tabelle im [BERT-Paper] (https://arxiv.org/pdf/1810.04805.pdf) wird für das Basismodell ein F1-Maß von 88,9 angegeben. Dort wurde das `uncased` Modell verwendet, während wir hier das `cased` Modell verwenden, was das bessere Ergebnis erklärt. - -Damit ist die Einführung in das Fein-tunen mit der Keras-API abgeschlossen. Beispiele für die gängigsten CL-Aufgaben findest du in Kapitel 7. - -> [!TIP] -> ✏️ **Probier es aus!** Fein-tune ein Modell mit dem GLUE SST-2 Datensatz, indem du die Datenverarbeitung aus Abschnitt 2 verwendest. + + +# Modell mit Keras fein-tunen + + + +Wenn du die Datenvorverarbeitung im letzten Abschnitt abgeschlossen hast, brauchst es nur noch wenige Schritte, um das Modell zu trainieren. Beachte jedoch, dass der Befehl `model.fit()` auf einer CPU sehr langsam läuft. Wenn du keinen GPU hast, kannst du auf [Google Colab] (https://colab.research.google.com/) kostenlos auf GPUs und TPUs zugreifen. + +Bei den folgenden Codebeispielen wird davon ausgegangen, dass du die Beispiele aus dem vorherigen Abschnitt bereits ausgeführt hast. Hier ist eine kurze Zusammenfassung, die aufzeigt was erwartet wird: + +```py +from datasets import load_dataset +from transformers import AutoTokenizer, DataCollatorWithPadding +import numpy as np + +raw_datasets = load_dataset("glue", "mrpc") +checkpoint = "bert-base-uncased" +tokenizer = AutoTokenizer.from_pretrained(checkpoint) + + +def tokenize_function(example): + return tokenizer(example["sentence1"], example["sentence2"], truncation=True) + + +tokenized_datasets = raw_datasets.map(tokenize_function, batched=True) + +data_collator = DataCollatorWithPadding(tokenizer=tokenizer, return_tensors="tf") + +tf_train_dataset = tokenized_datasets["train"].to_tf_dataset( + columns=["attention_mask", "input_ids", "token_type_ids"], + label_cols=["labels"], + shuffle=True, + collate_fn=data_collator, + batch_size=8, +) + +tf_validation_dataset = tokenized_datasets["validation"].to_tf_dataset( + columns=["attention_mask", "input_ids", "token_type_ids"], + label_cols=["labels"], + shuffle=False, + collate_fn=data_collator, + batch_size=8, +) +``` + +### Training + +Tensorflow Modelle, die von 🤗 Transformers importiert werden, sind bereits Keras Modelle. Hier ist eine kurze Einführung in Keras. + + + +Sobald wir die Daten haben, braucht es nur noch sehr wenig Arbeit, um mit dem Training zu beginnen. + + + +Wie im [vorherigen Kapitel](/course/chapter2) verwenden wir die Klasse `TFAutoModelForSequenceClassification` mit zwei Labels: + +```py +from transformers import TFAutoModelForSequenceClassification + +model = TFAutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) +``` + +Im Gegensatz zu [Kapitel 2](/course/chapter2) wird eine Warnung angezeigt, nachdem das Modell instanziiert wurde. Das liegt daran, dass BERT nicht auf die Klassifizierung von Satzpaaren vortrainiert wurde. Deshalb wurde der Kopf des vortrainierten Modells verworfen und stattdessen ein neuer Kopf eingefügt, der für die Klassifizierung von Sequenzen geeignet ist. Die Warnungen zeigen an, dass Teil der Gewichtung nicht verwendet wurden (die Gewichte für den verworfenen Kopf) und dass einige andere zufällig initialisiert wurden (die Gewichte für den neuen Kopf). Abschließend wirst du aufgefordert, das Modell zu trainieren, und genau das werden wir jetzt tun. + +Um das Modell mit unserem Datensatz fein-tunen zu können, müssen wir das Modell `kompilieren()` und unsere Daten an die `fit()`-Methode übergeben. Damit wird das Fein-tuning gestartet (dies sollte auf einer GPU ein paar Minuten dauern) und der Trainingsverlust sowie der Validierungsverlust am Ende jeder Epoche gemeldet. + +> [!TIP] +> 🤗 Transformer Modelle haben eine besondere Fähigkeit, die die meisten Keras Modelle nicht haben - sie können automatisch einen geeigneten Verlust verwenden, der intern berechnet wird. Dieser Verlust wird standardmäßig verwendet, wenn in `compile()` kein Verlustargument angegeben wird. Um den internen Verlust zu verwenden, musst du deine Labels als Teil des Input übergeben und nicht als separates Label, wie es normalerweise bei Keras-Modellen der Fall ist. Beispiele dafür gibt es in Teil 2 des Kurses, wobei die Definition der richtigen Verlustfunktion schwierig sein kann. Für die Klassifizierung von Sequenzen eignet sich jedoch eine der Standardverlustfunktionen von Keras, die wir hier verwenden werden. + +```py +from tensorflow.keras.losses import SparseCategoricalCrossentropy + +model.compile( + optimizer="adam", + loss=SparseCategoricalCrossentropy(from_logits=True), + metrics=["accuracy"], +) +model.fit( + tf_train_dataset, + validation_data=tf_validation_dataset, +) +``` + +> [!WARNING] +> Hier gibt es einen sehr häufigen Stolperstein - du *kannst* Keras einfach den Namen des Verlusts als String übergeben, aber standardmäßig geht Keras davon aus, dass du bereits einen Softmax auf die Outputs angewendet hast. Viele Modelle geben jedoch die Werte direkt vor der Anwendung des Softmax als *Logits* aus. Hier ist es wichtig der Keras Verlustfunktion mitzuteilen, dass unser Modell genau diess tut, und das geht nur indem sie direkt aufgerufen wird, und nicht über den Namen mit einem String. + + +### Verbesserung der Trainingsperformance + + + +Wenn du den obigen Code ausprobierst, läuft er zwar, aber du wirst feststellen, dass der Verlust nur langsam oder sporadisch zurückgeht. Die Ursache hierfür ist die *Lernrate*. Wenn der Namen eines Optimierers als String an Keras übergeben wird, initialisiert Keras diesen Optimierer mit Standardwerten für alle Parameter, einschließlich der Lernrate. Aus langjähriger Erfahrung wissen wir, dass Transformer Modelle von einer wesentlich niedrigeren Lernrate profitieren als der Standardwert für Adam. Dieser Standardwert liegt bei 1e-3, auch geschrieben als 10 hoch -3 oder 0,001. Für Transformer ist 5e-5 (0,00005), was etwa zwanzigmal niedriger ist, ist ein viel besserer Ausgangspunkt. + +Zusätzlich zur Senkung der Lernrate haben wir noch einen zweiten Trick in petto: Wir können die Lernrate langsam im Laufe des Trainings verringern. In der Literatur wird dies manchmal als *Decay* oder *Annealing* der Lernrate bezeichnet. In Keras kannst das am besten mit dem *Lernraten-Scheduler* umgesetzt werden. Ein guter Scheduler ist `PolynomialDecay` - trotz des Namens lässt er die Lernrate in den Standardeinstellungen einfach linear vom Anfangswert bis zum Endwert abfallen. Dies ist genau was wir wollen. Um einen Scheduler richtig zu nutzen, müssen wir ihm allerdings sagen, wie lange das Training dauern soll. Das berechnen wir im Folgenden als `num_train_steps`. + +```py +from tensorflow.keras.optimizers.schedules import PolynomialDecay + +batch_size = 8 +num_epochs = 3 +# The number of training steps is the number of samples in the dataset, divided by the batch size then multiplied +# by the total number of epochs. Note that the tf_train_dataset here is a batched tf.data.Dataset, +# not the original Hugging Face Dataset, so its len() is already num_samples // batch_size. +num_train_steps = len(tf_train_dataset) * num_epochs +lr_scheduler = PolynomialDecay( + initial_learning_rate=5e-5, end_learning_rate=0.0, decay_steps=num_train_steps +) +from tensorflow.keras.optimizers import Adam + +opt = Adam(learning_rate=lr_scheduler) +``` + +> [!TIP] +> Die 🤗 Transformer Bibliothek hat eine `create_optimizer()`-Funktion, die einen `AdamW`-Optimierer mit Lernratenabfall erzeugt. Das ist eine praktisches Tool, auf das wir in den nächsten Abschnitten des Kurses im Detail eingehen werden. + +Somit haben wir einen neuen Optimierer definiert und können ihn zum Training verwenden. Zuerst laden wir das Modell neu, um die Änderungen an der Gewichtung aus dem letzten Trainingslauf zurückzusetzen, und dann können wir es mit dem neuen Optimierer kompilieren: + +```py +import tensorflow as tf + +model = TFAutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) +loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) +model.compile(optimizer=opt, loss=loss, metrics=["accuracy"]) +``` + +Jetzt starten wir einen erneuten Trainingslauf mit `fit`: + +```py +model.fit(tf_train_dataset, validation_data=tf_validation_dataset, epochs=3) +``` + +> [!TIP] +> 💡 Wenn du dein Modell während des Trainings automatisch in den Hub hochladen möchtest, kannst du in der Methode `model.fit()` einen `PushToHubCallback` mitgeben. Mehr darüber erfahren wir in [Kapitel 4](/course/chapter4/3) + +### Modell-Vorhersagen + + + + +Trainieren und zusehen, wie der Verlust sinkt, ist ja ganz nett, aber was ist, wenn wir tatsächlich die Ergebnisse des trainierten Modells erhalten wollen? Entweder um Metriken zu berechnen oder um das Modell in der Produktion einzusetzen. Dafür können wir einfach die Methode `predict()` verwenden. Sie liefert uns die *Logits* aus dem Ausgabekopf des Modells, und zwar eine pro Klasse. + +```py +preds = model.predict(tf_validation_dataset)["logits"] +``` + +Wir können diese Logits in die Klassenvorhersagen des Modells umwandeln, indem wir `argmax` verwenden, um den höchsten Logit zu finden, der der wahrscheinlichsten Klasse entspricht: + +```py +class_preds = np.argmax(preds, axis=1) +print(preds.shape, class_preds.shape) +``` + +```python out +(408, 2) (408,) +``` + +Nun können wir diese Vorhersagen in `preds` nutzen, um einige Metriken zu berechnen! Wir können die Metriken, die mit dem MRPC-Datensatz verbunden sind, genauso einfach laden, wie wir den Datensatz geladen haben, in diesem Fall mit der Funktion "evaluate.load()". Das zurückgegebene Objekt verfügt über eine Berechnungsmethode, mit der wir die Metrik berechnen können: + +```py +import evaluate + +metric = evaluate.load("glue", "mrpc") +metric.compute(predictions=class_preds, references=raw_datasets["validation"]["label"]) +``` + +```python out +{'accuracy': 0.8578431372549019, 'f1': 0.8996539792387542} +``` +Die genauen Ergebnisse können variieren, da die zufällige Initialisierung des Modellkopfes die errechneten Metriken verändern kann. Das Modell erreicht über den Validierungsdaten eine Genauigkeit von 85,78 % und ein F1-Maß von 89,97. Dies sind die beiden Kennzahlen, die zur Bewertung der Ergebnisse des MRPC-Datensatzes für das GLUE-Benchmark verwendet werden. In der Tabelle im [BERT-Paper] (https://arxiv.org/pdf/1810.04805.pdf) wird für das Basismodell ein F1-Maß von 88,9 angegeben. Dort wurde das `uncased` Modell verwendet, während wir hier das `cased` Modell verwenden, was das bessere Ergebnis erklärt. + +Damit ist die Einführung in das Fein-tunen mit der Keras-API abgeschlossen. Beispiele für die gängigsten CL-Aufgaben findest du in Kapitel 7. + +> [!TIP] +> ✏️ **Probier es aus!** Fein-tune ein Modell mit dem GLUE SST-2 Datensatz, indem du die Datenverarbeitung aus Abschnitt 2 verwendest. diff --git a/chapters/de/chapter3/4.mdx b/chapters/de/chapter3/4.mdx index 6395de2e0..cfcfff345 100644 --- a/chapters/de/chapter3/4.mdx +++ b/chapters/de/chapter3/4.mdx @@ -1,357 +1,357 @@ -# Komplettes Training - - - - - -In diesem Abschnitt befassen wir uns damit, wie wir die gleichen Ergebnisse wie im letzten Abschnitt erzielen können, ohne die Klasse `Trainer` zu verwenden. Auch hier gehen wir davon aus, dass du die Datenverarbeitung in Abschnitt 2 durchgeführt hast. Hier ist eine kurze Zusammenfassung mit allem, was du brauchst: - -```py -from datasets import load_dataset -from transformers import AutoTokenizer, DataCollatorWithPadding - -raw_datasets = load_dataset("glue", "mrpc") -checkpoint = "bert-base-uncased" -tokenizer = AutoTokenizer.from_pretrained(checkpoint) - - -def tokenize_function(example): - return tokenizer(example["sentence1"], example["sentence2"], truncation=True) - - -tokenized_datasets = raw_datasets.map(tokenize_function, batched=True) -data_collator = DataCollatorWithPadding(tokenizer=tokenizer) -``` - -### Vorbereitung für das Training - -Bevor wir unsere Trainingsschleife schreiben, müssen wir noch einige Objekte definieren. Zunächst müssen wir die Datalader definieren, mit denen wir über die Batches iterieren werden. Doch bevor wir diese Dataloader definieren können, müssen wir unsere `tokenized_datasets` nachbearbeiten, um einige Dinge zu erledigen, die der `Trainer` automatisch für uns erledigt hat. Konkret heißt das, dass wir: - -- Die Spalten entfernen, die Werte enthalten, die das Modell nicht erwartet (wie die Spalten `sentence1` und `sentence2`). -- Die Spalte `label` in `labels` umbenennen (weil das Modell erwartet, dass das Argument `labels` heißt). -- Das Format der Datensätze anpassen, so dass sie PyTorch-Tensoren statt Listen zurückgeben. - -Das `tokenized_datasets` hat eine Methode für jeden dieser Schritte: - -```py -tokenized_datasets = tokenized_datasets.remove_columns(["sentence1", "sentence2", "idx"]) -tokenized_datasets = tokenized_datasets.rename_column("label", "labels") -tokenized_datasets.set_format("torch") -tokenized_datasets["train"].column_names -``` - -Anschließend können wir überprüfen, ob der Output nur Spalten enthält, die unser Modell akzeptiert: - -```python -["attention_mask", "input_ids", "labels", "token_type_ids"] -``` - -Jetzt können wir ganz einfach unsere Dataloader definieren: - -```py -from torch.utils.data import DataLoader - -train_dataloader = DataLoader( - tokenized_datasets["train"], shuffle=True, batch_size=8, collate_fn=data_collator -) -eval_dataloader = DataLoader( - tokenized_datasets["validation"], batch_size=8, collate_fn=data_collator -) -``` - -Um sicher zu gehen, überprüfen wir ein Batch auf Fehler in der Datenverarbeitung: - -```py -for batch in train_dataloader: - break -{k: v.shape for k, v in batch.items()} -``` - -```python out -{'attention_mask': torch.Size([8, 65]), - 'input_ids': torch.Size([8, 65]), - 'labels': torch.Size([8]), - 'token_type_ids': torch.Size([8, 65])} -``` - -Beachte, dass die Dimensionen der Tensoren wahrscheinlich etwas anders aussehen werden, da wir für den Trainingsdatenlader `shuffle=True` eingestellt haben und innerhalb des Batches auf die maximale Länge auffüllen. - -Da wir nun mit der Datenvorverarbeitung fertig sind (ein zufriedenstellendes aber schwer erreichbares Ziel für jeden ML-Experten), können wir uns nun dem Modell zuwenden. Wir instanziieren es genauso wie im vorherigen Abschnitt: - -```py -from transformers import AutoModelForSequenceClassification - -model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) -``` - -Als weitere Sicherheitsmaßnahme übergeben wir unseren Batch an das Modell, um sicherzustellen, dass beim Training alles glatt läuft: - -```py -outputs = model(**batch) -print(outputs.loss, outputs.logits.shape) -``` - -```python out -tensor(0.5441, grad_fn=) torch.Size([8, 2]) -``` - -Alle 🤗 Transformer Modelle geben den Verlust zurück, wenn `labels` angegeben werden, und wir erhalten zusätzlich die Logits (zwei für jede Eingabe in unserem Batch, also einen Tensor der Größe 8 x 2). - -Wir sind fast so weit, unsere Trainingsschleife zu schreiben! Es fehlen nur noch zwei Dinge: ein Optimierer und ein Scheduler für die Lernrate. Da wir versuchen, das zu wiederholen, was der `Trainer` automatisch gemacht hat, werden wir die gleichen Standardwerte verwenden. Der Optimierer, den der `Trainer` verwendet, heißt "AdamW" und ist größtenteils derselbe wie Adam, abgesehen von einer Abwandlung für die "Weight Decay Regularization" (siehe ["Decoupled Weight Decay Regularization"] (https://arxiv.org/abs/1711.05101) von Ilya Loshchilov und Frank Hutter): - -```py -from torch.optim import AdamW - -optimizer = AdamW(model.parameters(), lr=5e-5) -``` - -Der standardmäßig verwendete Scheduler für die Lernrate ist ein linearer Abstieg vom Maximalwert (5e-5) auf 0. Um ihn richtig zu definieren, müssen wir die Anzahl der Trainingsschritte kennen, d.h. die Anzahl der Epochen, die die Trainingsschleife durchlaufen soll, multipliziert mit der Anzahl der Trainingsbatches (der Länge unseres Trainingsdatenordners). Der `Trainer` verwendet standardmäßig drei Epochen, woran wir uns hier orientieren werden: - -```py -from transformers import get_scheduler - -num_epochs = 3 -num_training_steps = num_epochs * len(train_dataloader) -lr_scheduler = get_scheduler( - "linear", - optimizer=optimizer, - num_warmup_steps=0, - num_training_steps=num_training_steps, -) -print(num_training_steps) -``` - -```python out -1377 -``` - -### Die Trainingsschleife - -Ein letzter Hinweis: Wir wollen die GPU zum Training nutzen, wenn wir Zugang zu einer haben (auf einer CPU kann das Training mehrere Stunden statt ein paar Minuten dauern). Dazu definieren wir `device` als Gerät auf dem wir unser Modell und unsere Batches speichern: - -```py -import torch - -device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") -model.to(device) -device -``` - -```python out -device(type='cuda') -``` - -Wir sind jetzt bereit für das Training! Um ein Gefühl dafür zu bekommen, wann das Training abgeschlossen sein wird, fügen wir mit der Bibliothek `tqdm` einen Fortschrittsbalken über die Anzahl der Trainingsschritte ein: - -```py -from tqdm.auto import tqdm - -progress_bar = tqdm(range(num_training_steps)) - -model.train() -for epoch in range(num_epochs): - for batch in train_dataloader: - batch = {k: v.to(device) for k, v in batch.items()} - outputs = model(**batch) - loss = outputs.loss - loss.backward() - - optimizer.step() - lr_scheduler.step() - optimizer.zero_grad() - progress_bar.update(1) -``` - -Der Kern der Trainingsschleife sieht ähnlich aus wie in der Einleitung. Da wir keine Berichte angefordert haben, gibt die Trainingsschleife nichts über die Performance des Modells zurück. Dafür müssen wir eine Evaluationsschleife einfügen. - -### Die Evaluationsschleife - -Wie schon zuvor verwenden wir eine Metrik, die von der 🤗 Evaluate-Bibliothek bereitgestellt wird. Wir haben bereits die Methode `metric.compute()` gesehen, aber Metriken können auch Batches für uns akkumulieren, wenn wir die Vorhersageschleife mit der Methode `add_batch()` durchlaufen. Sobald wir alle Batches gesammelt haben, können wir das Endergebnis mit der Methode `metric.compute()` ermitteln. So implementierst du all das in eine Evaluationsschleife: - -```py -import evaluate - -metric = evaluate.load("glue", "mrpc") -model.eval() -for batch in eval_dataloader: - batch = {k: v.to(device) for k, v in batch.items()} - with torch.no_grad(): - outputs = model(**batch) - - logits = outputs.logits - predictions = torch.argmax(logits, dim=-1) - metric.add_batch(predictions=predictions, references=batch["labels"]) - -metric.compute() -``` - -```python out -{'accuracy': 0.8431372549019608, 'f1': 0.8907849829351535} -``` - -Auch hier werden deine Ergebnisse wegen der Zufälligkeit bei der Initialisierung des Modellkopfes und der Datenverteilung etwas anders ausfallen, aber sie sollten in etwa gleich sein. - -> [!TIP] -> ✏️ **Probier es selbt!** Ändere die vorherige Trainingsschleife, um dein Modell auf dem SST-2-Datensatz fein zu tunen. - -### Verbessere deine Trainingsschleife mit 🤗 Accelerate - - - -Die Trainingsschleife, die wir zuvor definiert haben, funktioniert gut auf einer einzelnen CPU oder GPU. Aber mit der Bibliothek [🤗 Accelerate](https://github.com/huggingface/accelerate) können wir mit wenigen Anpassungen verteiltes Training auf mehreren GPUs oder TPUs implementieren. Beginnend mit der Erstellung der Trainings- und Validierungsdaten, sieht unsere manuelle Trainingsschleife nun folgendermaßen aus: - -```py -from torch.optim import AdamW -from transformers import AutoModelForSequenceClassification, get_scheduler - -model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) -optimizer = AdamW(model.parameters(), lr=3e-5) - -device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") -model.to(device) - -num_epochs = 3 -num_training_steps = num_epochs * len(train_dataloader) -lr_scheduler = get_scheduler( - "linear", - optimizer=optimizer, - num_warmup_steps=0, - num_training_steps=num_training_steps, -) - -progress_bar = tqdm(range(num_training_steps)) - -model.train() -for epoch in range(num_epochs): - for batch in train_dataloader: - batch = {k: v.to(device) for k, v in batch.items()} - outputs = model(**batch) - loss = outputs.loss - loss.backward() - - optimizer.step() - lr_scheduler.step() - optimizer.zero_grad() - progress_bar.update(1) -``` - -Und hier sind die Änderungen: - -```diff -+ from accelerate import Accelerator - from torch.optim import AdamW - from transformers import AutoModelForSequenceClassification, get_scheduler - -+ accelerator = Accelerator() - - model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) - optimizer = AdamW(model.parameters(), lr=3e-5) - -- device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") -- model.to(device) - -+ train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare( -+ train_dataloader, eval_dataloader, model, optimizer -+ ) - - num_epochs = 3 - num_training_steps = num_epochs * len(train_dataloader) - lr_scheduler = get_scheduler( - "linear", - optimizer=optimizer, - num_warmup_steps=0, - num_training_steps=num_training_steps - ) - - progress_bar = tqdm(range(num_training_steps)) - - model.train() - for epoch in range(num_epochs): - for batch in train_dataloader: -- batch = {k: v.to(device) for k, v in batch.items()} - outputs = model(**batch) - loss = outputs.loss -- loss.backward() -+ accelerator.backward(loss) - - optimizer.step() - lr_scheduler.step() - optimizer.zero_grad() - progress_bar.update(1) -``` - -Die erste Zeile, die hinzugefügt werden muss, ist die Import-Zeile. Die zweite Zeile instanziiert ein `Accelerator`-Objekt, das die Hardware analysiert und die richtige verteilte Umgebung initialisiert. Accelerate kümmert sich um die Anordnung der Geräte, du kannst also die Zeilen entfernen, die das Modell auf dem Gerät platzieren (oder, wenn du das möchtest, sie so ändern, dass sie `accelerator.device` anstelle von `device` verwenden). - -Der Hauptteil der Arbeit wird dann in der Zeile erledigt, die die Dataloader, das Modell und den Optimierer an `accelerator.prepare()` sendet. Dadurch werden diese Objekte in den richtigen Container verpackt, damit das verteilte Training wie vorgesehen funktioniert. Die verbleibenden Änderungen sind das Entfernen der Zeile, die das Batch auf dem Gerät mit `device` ablegt (wenn du das beibehalten willst, kannst du es einfach in `accelerator.device` ändern) und das Ersetzen von `loss.backward()` durch `accelerator.backward(loss)`. - -> [!TIP] -> ⚠️ Um von dem Geschwindigkeitsvorteil der Cloud TPUs zu profitieren, empfehlen wir, deine Samples mit den Argumenten `padding="max_length"` und `max_length` des Tokenizers auf eine feste Länge aufzufüllen. - -Wenn du damit experimentieren möchtest, siehst du hier, wie die komplette Trainingsschleife mit 🤗 Accelerate aussieht: - -```py -from accelerate import Accelerator -from torch.optim import AdamW -from transformers import AutoModelForSequenceClassification, get_scheduler - -accelerator = Accelerator() - -model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) -optimizer = AdamW(model.parameters(), lr=3e-5) - -train_dl, eval_dl, model, optimizer = accelerator.prepare( - train_dataloader, eval_dataloader, model, optimizer -) - -num_epochs = 3 -num_training_steps = num_epochs * len(train_dl) -lr_scheduler = get_scheduler( - "linear", - optimizer=optimizer, - num_warmup_steps=0, - num_training_steps=num_training_steps, -) - -progress_bar = tqdm(range(num_training_steps)) - -model.train() -for epoch in range(num_epochs): - for batch in train_dl: - outputs = model(**batch) - loss = outputs.loss - accelerator.backward(loss) - - optimizer.step() - lr_scheduler.step() - optimizer.zero_grad() - progress_bar.update(1) -``` - -Wenn dies in das Script `train.py` eingefügt wird, kann das Script auf jeder Art von verteilter Hardware ausgeführt werden. Um es auf deiner verteilten Hardware auszuprobieren, führe den folgenden Befehl aus: - -```bash -accelerate config -``` - -Du wirst dann aufgefordert werden, einige Fragen zu beantworten und die Antworten in eine Konfigurationsdatei zu schreiben, die von diesem Befehl verwendet wird: - -``` -accelerate launch train.py -``` - -Damit wird das verteilte Training gestartet. - -Wenn du das in einem Notebook ausprobieren möchtest (z. B. um es mit TPUs auf Colab zu testen), füge den Code einfach in eine `training_function()` ein und führe eine letzte Zelle mit aus: - -```python -from accelerate import notebook_launcher - -notebook_launcher(training_function) -``` - -Weitere Beispiele findest du in dem [🤗 Accelerate Repo](https://github.com/huggingface/accelerate/tree/main/examples). +# Komplettes Training + + + + + +In diesem Abschnitt befassen wir uns damit, wie wir die gleichen Ergebnisse wie im letzten Abschnitt erzielen können, ohne die Klasse `Trainer` zu verwenden. Auch hier gehen wir davon aus, dass du die Datenverarbeitung in Abschnitt 2 durchgeführt hast. Hier ist eine kurze Zusammenfassung mit allem, was du brauchst: + +```py +from datasets import load_dataset +from transformers import AutoTokenizer, DataCollatorWithPadding + +raw_datasets = load_dataset("glue", "mrpc") +checkpoint = "bert-base-uncased" +tokenizer = AutoTokenizer.from_pretrained(checkpoint) + + +def tokenize_function(example): + return tokenizer(example["sentence1"], example["sentence2"], truncation=True) + + +tokenized_datasets = raw_datasets.map(tokenize_function, batched=True) +data_collator = DataCollatorWithPadding(tokenizer=tokenizer) +``` + +### Vorbereitung für das Training + +Bevor wir unsere Trainingsschleife schreiben, müssen wir noch einige Objekte definieren. Zunächst müssen wir die Datalader definieren, mit denen wir über die Batches iterieren werden. Doch bevor wir diese Dataloader definieren können, müssen wir unsere `tokenized_datasets` nachbearbeiten, um einige Dinge zu erledigen, die der `Trainer` automatisch für uns erledigt hat. Konkret heißt das, dass wir: + +- Die Spalten entfernen, die Werte enthalten, die das Modell nicht erwartet (wie die Spalten `sentence1` und `sentence2`). +- Die Spalte `label` in `labels` umbenennen (weil das Modell erwartet, dass das Argument `labels` heißt). +- Das Format der Datensätze anpassen, so dass sie PyTorch-Tensoren statt Listen zurückgeben. + +Das `tokenized_datasets` hat eine Methode für jeden dieser Schritte: + +```py +tokenized_datasets = tokenized_datasets.remove_columns(["sentence1", "sentence2", "idx"]) +tokenized_datasets = tokenized_datasets.rename_column("label", "labels") +tokenized_datasets.set_format("torch") +tokenized_datasets["train"].column_names +``` + +Anschließend können wir überprüfen, ob der Output nur Spalten enthält, die unser Modell akzeptiert: + +```python +["attention_mask", "input_ids", "labels", "token_type_ids"] +``` + +Jetzt können wir ganz einfach unsere Dataloader definieren: + +```py +from torch.utils.data import DataLoader + +train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, batch_size=8, collate_fn=data_collator +) +eval_dataloader = DataLoader( + tokenized_datasets["validation"], batch_size=8, collate_fn=data_collator +) +``` + +Um sicher zu gehen, überprüfen wir ein Batch auf Fehler in der Datenverarbeitung: + +```py +for batch in train_dataloader: + break +{k: v.shape for k, v in batch.items()} +``` + +```python out +{'attention_mask': torch.Size([8, 65]), + 'input_ids': torch.Size([8, 65]), + 'labels': torch.Size([8]), + 'token_type_ids': torch.Size([8, 65])} +``` + +Beachte, dass die Dimensionen der Tensoren wahrscheinlich etwas anders aussehen werden, da wir für den Trainingsdatenlader `shuffle=True` eingestellt haben und innerhalb des Batches auf die maximale Länge auffüllen. + +Da wir nun mit der Datenvorverarbeitung fertig sind (ein zufriedenstellendes aber schwer erreichbares Ziel für jeden ML-Experten), können wir uns nun dem Modell zuwenden. Wir instanziieren es genauso wie im vorherigen Abschnitt: + +```py +from transformers import AutoModelForSequenceClassification + +model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) +``` + +Als weitere Sicherheitsmaßnahme übergeben wir unseren Batch an das Modell, um sicherzustellen, dass beim Training alles glatt läuft: + +```py +outputs = model(**batch) +print(outputs.loss, outputs.logits.shape) +``` + +```python out +tensor(0.5441, grad_fn=) torch.Size([8, 2]) +``` + +Alle 🤗 Transformer Modelle geben den Verlust zurück, wenn `labels` angegeben werden, und wir erhalten zusätzlich die Logits (zwei für jede Eingabe in unserem Batch, also einen Tensor der Größe 8 x 2). + +Wir sind fast so weit, unsere Trainingsschleife zu schreiben! Es fehlen nur noch zwei Dinge: ein Optimierer und ein Scheduler für die Lernrate. Da wir versuchen, das zu wiederholen, was der `Trainer` automatisch gemacht hat, werden wir die gleichen Standardwerte verwenden. Der Optimierer, den der `Trainer` verwendet, heißt "AdamW" und ist größtenteils derselbe wie Adam, abgesehen von einer Abwandlung für die "Weight Decay Regularization" (siehe ["Decoupled Weight Decay Regularization"] (https://arxiv.org/abs/1711.05101) von Ilya Loshchilov und Frank Hutter): + +```py +from torch.optim import AdamW + +optimizer = AdamW(model.parameters(), lr=5e-5) +``` + +Der standardmäßig verwendete Scheduler für die Lernrate ist ein linearer Abstieg vom Maximalwert (5e-5) auf 0. Um ihn richtig zu definieren, müssen wir die Anzahl der Trainingsschritte kennen, d.h. die Anzahl der Epochen, die die Trainingsschleife durchlaufen soll, multipliziert mit der Anzahl der Trainingsbatches (der Länge unseres Trainingsdatenordners). Der `Trainer` verwendet standardmäßig drei Epochen, woran wir uns hier orientieren werden: + +```py +from transformers import get_scheduler + +num_epochs = 3 +num_training_steps = num_epochs * len(train_dataloader) +lr_scheduler = get_scheduler( + "linear", + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=num_training_steps, +) +print(num_training_steps) +``` + +```python out +1377 +``` + +### Die Trainingsschleife + +Ein letzter Hinweis: Wir wollen die GPU zum Training nutzen, wenn wir Zugang zu einer haben (auf einer CPU kann das Training mehrere Stunden statt ein paar Minuten dauern). Dazu definieren wir `device` als Gerät auf dem wir unser Modell und unsere Batches speichern: + +```py +import torch + +device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") +model.to(device) +device +``` + +```python out +device(type='cuda') +``` + +Wir sind jetzt bereit für das Training! Um ein Gefühl dafür zu bekommen, wann das Training abgeschlossen sein wird, fügen wir mit der Bibliothek `tqdm` einen Fortschrittsbalken über die Anzahl der Trainingsschritte ein: + +```py +from tqdm.auto import tqdm + +progress_bar = tqdm(range(num_training_steps)) + +model.train() +for epoch in range(num_epochs): + for batch in train_dataloader: + batch = {k: v.to(device) for k, v in batch.items()} + outputs = model(**batch) + loss = outputs.loss + loss.backward() + + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + progress_bar.update(1) +``` + +Der Kern der Trainingsschleife sieht ähnlich aus wie in der Einleitung. Da wir keine Berichte angefordert haben, gibt die Trainingsschleife nichts über die Performance des Modells zurück. Dafür müssen wir eine Evaluationsschleife einfügen. + +### Die Evaluationsschleife + +Wie schon zuvor verwenden wir eine Metrik, die von der 🤗 Evaluate-Bibliothek bereitgestellt wird. Wir haben bereits die Methode `metric.compute()` gesehen, aber Metriken können auch Batches für uns akkumulieren, wenn wir die Vorhersageschleife mit der Methode `add_batch()` durchlaufen. Sobald wir alle Batches gesammelt haben, können wir das Endergebnis mit der Methode `metric.compute()` ermitteln. So implementierst du all das in eine Evaluationsschleife: + +```py +import evaluate + +metric = evaluate.load("glue", "mrpc") +model.eval() +for batch in eval_dataloader: + batch = {k: v.to(device) for k, v in batch.items()} + with torch.no_grad(): + outputs = model(**batch) + + logits = outputs.logits + predictions = torch.argmax(logits, dim=-1) + metric.add_batch(predictions=predictions, references=batch["labels"]) + +metric.compute() +``` + +```python out +{'accuracy': 0.8431372549019608, 'f1': 0.8907849829351535} +``` + +Auch hier werden deine Ergebnisse wegen der Zufälligkeit bei der Initialisierung des Modellkopfes und der Datenverteilung etwas anders ausfallen, aber sie sollten in etwa gleich sein. + +> [!TIP] +> ✏️ **Probier es selbt!** Ändere die vorherige Trainingsschleife, um dein Modell auf dem SST-2-Datensatz fein zu tunen. + +### Verbessere deine Trainingsschleife mit 🤗 Accelerate + + + +Die Trainingsschleife, die wir zuvor definiert haben, funktioniert gut auf einer einzelnen CPU oder GPU. Aber mit der Bibliothek [🤗 Accelerate](https://github.com/huggingface/accelerate) können wir mit wenigen Anpassungen verteiltes Training auf mehreren GPUs oder TPUs implementieren. Beginnend mit der Erstellung der Trainings- und Validierungsdaten, sieht unsere manuelle Trainingsschleife nun folgendermaßen aus: + +```py +from torch.optim import AdamW +from transformers import AutoModelForSequenceClassification, get_scheduler + +model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) +optimizer = AdamW(model.parameters(), lr=3e-5) + +device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") +model.to(device) + +num_epochs = 3 +num_training_steps = num_epochs * len(train_dataloader) +lr_scheduler = get_scheduler( + "linear", + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=num_training_steps, +) + +progress_bar = tqdm(range(num_training_steps)) + +model.train() +for epoch in range(num_epochs): + for batch in train_dataloader: + batch = {k: v.to(device) for k, v in batch.items()} + outputs = model(**batch) + loss = outputs.loss + loss.backward() + + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + progress_bar.update(1) +``` + +Und hier sind die Änderungen: + +```diff ++ from accelerate import Accelerator + from torch.optim import AdamW + from transformers import AutoModelForSequenceClassification, get_scheduler + ++ accelerator = Accelerator() + + model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) + optimizer = AdamW(model.parameters(), lr=3e-5) + +- device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") +- model.to(device) + ++ train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare( ++ train_dataloader, eval_dataloader, model, optimizer ++ ) + + num_epochs = 3 + num_training_steps = num_epochs * len(train_dataloader) + lr_scheduler = get_scheduler( + "linear", + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=num_training_steps + ) + + progress_bar = tqdm(range(num_training_steps)) + + model.train() + for epoch in range(num_epochs): + for batch in train_dataloader: +- batch = {k: v.to(device) for k, v in batch.items()} + outputs = model(**batch) + loss = outputs.loss +- loss.backward() ++ accelerator.backward(loss) + + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + progress_bar.update(1) +``` + +Die erste Zeile, die hinzugefügt werden muss, ist die Import-Zeile. Die zweite Zeile instanziiert ein `Accelerator`-Objekt, das die Hardware analysiert und die richtige verteilte Umgebung initialisiert. Accelerate kümmert sich um die Anordnung der Geräte, du kannst also die Zeilen entfernen, die das Modell auf dem Gerät platzieren (oder, wenn du das möchtest, sie so ändern, dass sie `accelerator.device` anstelle von `device` verwenden). + +Der Hauptteil der Arbeit wird dann in der Zeile erledigt, die die Dataloader, das Modell und den Optimierer an `accelerator.prepare()` sendet. Dadurch werden diese Objekte in den richtigen Container verpackt, damit das verteilte Training wie vorgesehen funktioniert. Die verbleibenden Änderungen sind das Entfernen der Zeile, die das Batch auf dem Gerät mit `device` ablegt (wenn du das beibehalten willst, kannst du es einfach in `accelerator.device` ändern) und das Ersetzen von `loss.backward()` durch `accelerator.backward(loss)`. + +> [!TIP] +> ⚠️ Um von dem Geschwindigkeitsvorteil der Cloud TPUs zu profitieren, empfehlen wir, deine Samples mit den Argumenten `padding="max_length"` und `max_length` des Tokenizers auf eine feste Länge aufzufüllen. + +Wenn du damit experimentieren möchtest, siehst du hier, wie die komplette Trainingsschleife mit 🤗 Accelerate aussieht: + +```py +from accelerate import Accelerator +from torch.optim import AdamW +from transformers import AutoModelForSequenceClassification, get_scheduler + +accelerator = Accelerator() + +model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) +optimizer = AdamW(model.parameters(), lr=3e-5) + +train_dl, eval_dl, model, optimizer = accelerator.prepare( + train_dataloader, eval_dataloader, model, optimizer +) + +num_epochs = 3 +num_training_steps = num_epochs * len(train_dl) +lr_scheduler = get_scheduler( + "linear", + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=num_training_steps, +) + +progress_bar = tqdm(range(num_training_steps)) + +model.train() +for epoch in range(num_epochs): + for batch in train_dl: + outputs = model(**batch) + loss = outputs.loss + accelerator.backward(loss) + + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + progress_bar.update(1) +``` + +Wenn dies in das Script `train.py` eingefügt wird, kann das Script auf jeder Art von verteilter Hardware ausgeführt werden. Um es auf deiner verteilten Hardware auszuprobieren, führe den folgenden Befehl aus: + +```bash +accelerate config +``` + +Du wirst dann aufgefordert werden, einige Fragen zu beantworten und die Antworten in eine Konfigurationsdatei zu schreiben, die von diesem Befehl verwendet wird: + +``` +accelerate launch train.py +``` + +Damit wird das verteilte Training gestartet. + +Wenn du das in einem Notebook ausprobieren möchtest (z. B. um es mit TPUs auf Colab zu testen), füge den Code einfach in eine `training_function()` ein und führe eine letzte Zelle mit aus: + +```python +from accelerate import notebook_launcher + +notebook_launcher(training_function) +``` + +Weitere Beispiele findest du in dem [🤗 Accelerate Repo](https://github.com/huggingface/accelerate/tree/main/examples). diff --git a/chapters/de/chapter3/5.mdx b/chapters/de/chapter3/5.mdx index a017a1189..c585f17fa 100644 --- a/chapters/de/chapter3/5.mdx +++ b/chapters/de/chapter3/5.mdx @@ -1,25 +1,25 @@ - - -# Fein-tunen, Check! - - - -Das hat Spaß gemacht! In den ersten beiden Kapiteln hast du etwas über Modelle und Tokenizer gelernt, und jetzt weißt du, wie du sie auf deine eigenen Daten fein-tunen kannst. Rekapitulieren wir, was du in diesem Kapitel gelernt hast: - -{#if fw === 'pt'} -* Über Datensätze im [Hub](https://huggingface.co/datasets) -* Wie du Datensätze lädst und vorverarbeitest, einschließlich der Verwendung von dynamischem Padding und Collators -* Implementierung des eigenen Fein-tunings und der Evaluierung eines Modells -* Eine Trainingsschleife auf niedriger Ebene implementiert -* Mit 🤗 Accelerate die Trainingsschleife so anpassen, dass sie für mehrere GPUs oder TPUs funktioniert - -{:else} -* Über Datensätze im [Hub](https://huggingface.co/datasets) -* Wie man Datensätze lädt und vorverarbeitet -* Wie man ein Modell mit Keras fein-tunet und auswertet -* Eine eigene Metrik implementiert - -{/if} + + +# Fein-tunen, Check! + + + +Das hat Spaß gemacht! In den ersten beiden Kapiteln hast du etwas über Modelle und Tokenizer gelernt, und jetzt weißt du, wie du sie auf deine eigenen Daten fein-tunen kannst. Rekapitulieren wir, was du in diesem Kapitel gelernt hast: + +{#if fw === 'pt'} +* Über Datensätze im [Hub](https://huggingface.co/datasets) +* Wie du Datensätze lädst und vorverarbeitest, einschließlich der Verwendung von dynamischem Padding und Collators +* Implementierung des eigenen Fein-tunings und der Evaluierung eines Modells +* Eine Trainingsschleife auf niedriger Ebene implementiert +* Mit 🤗 Accelerate die Trainingsschleife so anpassen, dass sie für mehrere GPUs oder TPUs funktioniert + +{:else} +* Über Datensätze im [Hub](https://huggingface.co/datasets) +* Wie man Datensätze lädt und vorverarbeitet +* Wie man ein Modell mit Keras fein-tunet und auswertet +* Eine eigene Metrik implementiert + +{/if} diff --git a/chapters/de/chapter3/6.mdx b/chapters/de/chapter3/6.mdx index cd37e7f5c..fef9f12c8 100644 --- a/chapters/de/chapter3/6.mdx +++ b/chapters/de/chapter3/6.mdx @@ -1,301 +1,301 @@ - - - - -# Quiz am Ende des Kapitels - - - -Teste, was du in diesem Kapitel gelernt hast! - -### 1. Der Datensatz `emotion` enthält Twitter-Nachrichten, die mit Emotionen gelabelt sind. Suche im [Hub](https://huggingface.co/datasets) nach dem Datensatz und lies die Datensatzkarte. Welche der folgenden Emotionen gehört nicht zu den grundlegenden Emotionen? - - - -### 2. Suche im [Hub](https://huggingface.co/datasets) nach dem Datensatz `ar_sarcasm`. Welche Aufgabe unterstützt er? - -Datensatzkarte an!" - }, - { - text: "Named entity recognition (Eigennamenerkennung )", - explain: "Das war's noch nicht - schau dir noch mal die Datensatzkarte an!" - }, - { - text: "Question answering (Fragenbeantwortung)", - explain: "Leider wurde diese Frage nicht richtig beantwortet. Versuche es noch einmal!" - } - ]} -/> - -### 3. Wie erwartet das BERT Modell, dass ein Satzpaar verarbeitet wird? - -[SEP] spezielles Token wird benötigt, um die beiden Sätze zu trennen, aber das ist nicht das Einzige!" - }, - { - text: "[CLS] Satztoken_1 Satztoken_2", - explain: "Ein [CLS] spezielles Token ist am Anfang erforderlich, aber das ist nicht das Einzige!" - }, - { - text: "[CLS] Satztoken_1 [SEP] Satztoken_2 [SEP]", - explain: "Das ist richtig!", - correct: true - }, - { - text: "[CLS] Satztoken_1 [SEP] Satztoken_2", - explain: "Ein [CLS] spezielles Token wird am Anfang benötigt, sowie ein [SEP] spezielles Token, um die beiden Sätze zu trennen, aber das ist noch nicht alles!" - } - ]} -/> - -{#if fw === 'pt'} -### 4. Was sind die Vorteile der Methode `Dataset.map()`? - - - -### 5. Was bedeutet dynamisches Padding? - - - -### 6. Welchen Zweck hat die Funktion collate? - -DataCollatorWithPadding im Speziellen." - }, - { - text: "Er stellt alle Proben in einem Batch zusammen.", - explain: "Richtig! Du kannst die collate Funktion als Argument eines DataLoaders übergeben. Wir haben die Funktion DataCollatorWithPadding verwendet, die alle Elemente in einem Batch auffüllt, damit sie die gleiche Länge haben.", - correct: true - }, - { - text: "Es wird der gesamte Datensatz vorverarbeitet.", - explain: "Das wäre eine Vorverarbeitungsfunktion, keine Zusammenfassungsfunktion wie collate." - }, - { - text: "Sie schneidet die Sequenzen im Datensatz ab.", - explain: "Eine collate Funktion behandelt einzelne Batches, nicht den gesamten Datensatz. Wenn du am Abschneiden interessiert bist, kannst du das truncate Argument von dem tokenizer verwenden." - } - ]} -/> - -### 7. Was passiert, wenn du eine der Klassen `AutoModelForXxx` mit einem vortrainierten Sprachmodell (z. B. `bert-base-uncased`) instanziierst, das einer anderen Aufgabe entspricht als der, für die es trainiert wurde? - -AutoModelForSequenceClassification mit bert-base-uncased verwendet haben, bekamen wir beim Instanziieren des Modells Warnungen. Der trainierte Kopf wird nicht für die Sequenzklassifizierung verwendet, also wird er verworfen und ein neuer Kopf mit zufälliger Gewichtung wird instanziiert.", - correct: true - }, - { - text: "Der Kopf des vorher trainierten Modells wird verworfen.", - explain: "Es muss etwas anderes passieren. Versuch es noch einmal!" - }, - { - text: "Nichts, da das Modell noch für die andere Aufgabe fein-tunen kann.", - explain: "Der Kopf des trainierten Modells wurde nicht für die Lösung dieser Aufgabe trainiert, also sollte der Kopf verworfen werden!" - } - ]} -/> - -### 8. Was ist der Zweck von `TrainingArguments`? - -Trainer verwendet werden.", - explain: "Richtig!", - correct: true - }, - { - text: "Hier wird die Größe des Modells angegeben.", - explain: "Die Größe des Modells wird durch die Konfiguration des Modells festgelegt, nicht durch die Klasse TrainingArguments." - }, - { - text: "Sie enthält nur die Hyperparameter, die für die Auswertung verwendet werden.", - explain: "In unserem Beispiel haben wir angegeben, wo das Modell und seine Kontrollpunkte gespeichert werden sollen. Versuche es noch einmal!" - }, - { - text: "Er enthält nur die Hyperparameter, die für das Training verwendet werden.", - explain: "In unserem Beispiel haben wir auch eine Auswertungsstrategie verwendet, was sich auf die Auswertung auswirkt. Versuche es noch einmal!" - } - ]} -/> - -### 9. Warum solltest du die 🤗 Accelerate Bibliothek benutzen? - -Trainer gemacht, nicht mit der 🤗 Accelerate Bibliothek. Versuch es noch einmal!" - }, - { - text: "Damit funktionieren unsere Trainingsschleifen bei verteilten Strategien.", - explain: "Richtig! Mit 🤗 Accelerate funktionieren deine Trainingsschleifen für mehrere verteilte GPUs und TPUs.", - correct: true - }, - { - text: "Es bietet mehr Funktionen zur Optimierung.", - explain: "Nein, die 🤗 Accelerate Bibliothek stellt keine Optimierungsfunktionen zur Verfügung." - } - ]} -/> - -{:else} -### 4. Was passiert, wenn du eine der Klassen `TFAutoModelForXxx` mit einem vortrainierten Sprachmodell (z. B. `bert-base-uncased`) instanziierst, das einer anderen Aufgabe entspricht als der, für die es trainiert wurde? - -TFAutoModelForSequenceClassification mit bert-base-uncased verwendet haben, bekamen wir beim Instanziieren des Modells Warnungen. Der trainierte Kopf wird nicht für die Sequenzklassifizierung verwendet, also wird er verworfen und ein neuer Kopf mit zufälligen Gewichten instanziiert.", - correct: true - }, - { - text: "Der Kopf des vorher trainierten Modells wird verworfen.", - explain: "Es muss etwas anderes passieren. Versuch es noch einmal!" - }, - { - text: "Nichts, da das Modell noch für die andere Aufgabe fein-tunen kann.", - explain: "Der Kopf des trainierten Modells wurde nicht für die Lösung dieser Aufgabe trainiert, also sollten wir den Kopf verwerfen!" - } - ]} -/> - -### 5. Die Tensorflow Modelle von `transformers` sind bereits Keras Modelle. Welchen Vorteil bietet das? - -TPUStrategy-Bereich ausführen, einschließlich der Initialisierung des Modells." - }, - { - text: "Du kannst bestehende Methoden wie compile(), fit() und predict() nutzen.", - erklären: "Richtig! Wenn du erst einmal die Daten hast, erfordert das Training mit ihnen nur noch wenig Arbeit.", - correct: true - }, - { - text: "Du lernst sowohl Keras als auch Transformer kennen.", - explain: "Korrekt, aber wir suchen nach etwas anderem :)", - correct: true - }, - { - text: "Du kannst ganz einfach Metriken für den Datensatz berechnen.", - explain: "Keras hilft uns beim Training und der Auswertung des Modells, nicht bei der Berechnung von datensatzbezogenen Metriken." - } - ]} -/> - -### 6. Wie kannst du deine eigene benutzerdefinierte Metrik definieren? - -tf.keras.metrics.Metric erstellen.", - explain: "Großartig!", - correct: true - }, - { - text: "Durch Verwendung der funktionalen Keras-API.", - explain: "Versuch es noch einmal!" - }, - { - text: "Durch die Verwendung einer Callable mit der Signatur metric_fn(y_true, y_pred).", - explain: "Korrekt!", - correct: true - }, - { - text: "Indem du es googelst.", - explain: "Das ist nicht die Antwort, nach der wir suchen, aber es sollte dir helfen, sie zu finden.", - correct: true - } - ]} -/> - -{/if} + + + + +# Quiz am Ende des Kapitels + + + +Teste, was du in diesem Kapitel gelernt hast! + +### 1. Der Datensatz `emotion` enthält Twitter-Nachrichten, die mit Emotionen gelabelt sind. Suche im [Hub](https://huggingface.co/datasets) nach dem Datensatz und lies die Datensatzkarte. Welche der folgenden Emotionen gehört nicht zu den grundlegenden Emotionen? + + + +### 2. Suche im [Hub](https://huggingface.co/datasets) nach dem Datensatz `ar_sarcasm`. Welche Aufgabe unterstützt er? + +Datensatzkarte an!" + }, + { + text: "Named entity recognition (Eigennamenerkennung )", + explain: "Das war's noch nicht - schau dir noch mal die Datensatzkarte an!" + }, + { + text: "Question answering (Fragenbeantwortung)", + explain: "Leider wurde diese Frage nicht richtig beantwortet. Versuche es noch einmal!" + } + ]} +/> + +### 3. Wie erwartet das BERT Modell, dass ein Satzpaar verarbeitet wird? + +[SEP] spezielles Token wird benötigt, um die beiden Sätze zu trennen, aber das ist nicht das Einzige!" + }, + { + text: "[CLS] Satztoken_1 Satztoken_2", + explain: "Ein [CLS] spezielles Token ist am Anfang erforderlich, aber das ist nicht das Einzige!" + }, + { + text: "[CLS] Satztoken_1 [SEP] Satztoken_2 [SEP]", + explain: "Das ist richtig!", + correct: true + }, + { + text: "[CLS] Satztoken_1 [SEP] Satztoken_2", + explain: "Ein [CLS] spezielles Token wird am Anfang benötigt, sowie ein [SEP] spezielles Token, um die beiden Sätze zu trennen, aber das ist noch nicht alles!" + } + ]} +/> + +{#if fw === 'pt'} +### 4. Was sind die Vorteile der Methode `Dataset.map()`? + + + +### 5. Was bedeutet dynamisches Padding? + + + +### 6. Welchen Zweck hat die Funktion collate? + +DataCollatorWithPadding im Speziellen." + }, + { + text: "Er stellt alle Proben in einem Batch zusammen.", + explain: "Richtig! Du kannst die collate Funktion als Argument eines DataLoaders übergeben. Wir haben die Funktion DataCollatorWithPadding verwendet, die alle Elemente in einem Batch auffüllt, damit sie die gleiche Länge haben.", + correct: true + }, + { + text: "Es wird der gesamte Datensatz vorverarbeitet.", + explain: "Das wäre eine Vorverarbeitungsfunktion, keine Zusammenfassungsfunktion wie collate." + }, + { + text: "Sie schneidet die Sequenzen im Datensatz ab.", + explain: "Eine collate Funktion behandelt einzelne Batches, nicht den gesamten Datensatz. Wenn du am Abschneiden interessiert bist, kannst du das truncate Argument von dem tokenizer verwenden." + } + ]} +/> + +### 7. Was passiert, wenn du eine der Klassen `AutoModelForXxx` mit einem vortrainierten Sprachmodell (z. B. `bert-base-uncased`) instanziierst, das einer anderen Aufgabe entspricht als der, für die es trainiert wurde? + +AutoModelForSequenceClassification mit bert-base-uncased verwendet haben, bekamen wir beim Instanziieren des Modells Warnungen. Der trainierte Kopf wird nicht für die Sequenzklassifizierung verwendet, also wird er verworfen und ein neuer Kopf mit zufälliger Gewichtung wird instanziiert.", + correct: true + }, + { + text: "Der Kopf des vorher trainierten Modells wird verworfen.", + explain: "Es muss etwas anderes passieren. Versuch es noch einmal!" + }, + { + text: "Nichts, da das Modell noch für die andere Aufgabe fein-tunen kann.", + explain: "Der Kopf des trainierten Modells wurde nicht für die Lösung dieser Aufgabe trainiert, also sollte der Kopf verworfen werden!" + } + ]} +/> + +### 8. Was ist der Zweck von `TrainingArguments`? + +Trainer verwendet werden.", + explain: "Richtig!", + correct: true + }, + { + text: "Hier wird die Größe des Modells angegeben.", + explain: "Die Größe des Modells wird durch die Konfiguration des Modells festgelegt, nicht durch die Klasse TrainingArguments." + }, + { + text: "Sie enthält nur die Hyperparameter, die für die Auswertung verwendet werden.", + explain: "In unserem Beispiel haben wir angegeben, wo das Modell und seine Kontrollpunkte gespeichert werden sollen. Versuche es noch einmal!" + }, + { + text: "Er enthält nur die Hyperparameter, die für das Training verwendet werden.", + explain: "In unserem Beispiel haben wir auch eine Auswertungsstrategie verwendet, was sich auf die Auswertung auswirkt. Versuche es noch einmal!" + } + ]} +/> + +### 9. Warum solltest du die 🤗 Accelerate Bibliothek benutzen? + +Trainer gemacht, nicht mit der 🤗 Accelerate Bibliothek. Versuch es noch einmal!" + }, + { + text: "Damit funktionieren unsere Trainingsschleifen bei verteilten Strategien.", + explain: "Richtig! Mit 🤗 Accelerate funktionieren deine Trainingsschleifen für mehrere verteilte GPUs und TPUs.", + correct: true + }, + { + text: "Es bietet mehr Funktionen zur Optimierung.", + explain: "Nein, die 🤗 Accelerate Bibliothek stellt keine Optimierungsfunktionen zur Verfügung." + } + ]} +/> + +{:else} +### 4. Was passiert, wenn du eine der Klassen `TFAutoModelForXxx` mit einem vortrainierten Sprachmodell (z. B. `bert-base-uncased`) instanziierst, das einer anderen Aufgabe entspricht als der, für die es trainiert wurde? + +TFAutoModelForSequenceClassification mit bert-base-uncased verwendet haben, bekamen wir beim Instanziieren des Modells Warnungen. Der trainierte Kopf wird nicht für die Sequenzklassifizierung verwendet, also wird er verworfen und ein neuer Kopf mit zufälligen Gewichten instanziiert.", + correct: true + }, + { + text: "Der Kopf des vorher trainierten Modells wird verworfen.", + explain: "Es muss etwas anderes passieren. Versuch es noch einmal!" + }, + { + text: "Nichts, da das Modell noch für die andere Aufgabe fein-tunen kann.", + explain: "Der Kopf des trainierten Modells wurde nicht für die Lösung dieser Aufgabe trainiert, also sollten wir den Kopf verwerfen!" + } + ]} +/> + +### 5. Die Tensorflow Modelle von `transformers` sind bereits Keras Modelle. Welchen Vorteil bietet das? + +TPUStrategy-Bereich ausführen, einschließlich der Initialisierung des Modells." + }, + { + text: "Du kannst bestehende Methoden wie compile(), fit() und predict() nutzen.", + erklären: "Richtig! Wenn du erst einmal die Daten hast, erfordert das Training mit ihnen nur noch wenig Arbeit.", + correct: true + }, + { + text: "Du lernst sowohl Keras als auch Transformer kennen.", + explain: "Korrekt, aber wir suchen nach etwas anderem :)", + correct: true + }, + { + text: "Du kannst ganz einfach Metriken für den Datensatz berechnen.", + explain: "Keras hilft uns beim Training und der Auswertung des Modells, nicht bei der Berechnung von datensatzbezogenen Metriken." + } + ]} +/> + +### 6. Wie kannst du deine eigene benutzerdefinierte Metrik definieren? + +tf.keras.metrics.Metric erstellen.", + explain: "Großartig!", + correct: true + }, + { + text: "Durch Verwendung der funktionalen Keras-API.", + explain: "Versuch es noch einmal!" + }, + { + text: "Durch die Verwendung einer Callable mit der Signatur metric_fn(y_true, y_pred).", + explain: "Korrekt!", + correct: true + }, + { + text: "Indem du es googelst.", + explain: "Das ist nicht die Antwort, nach der wir suchen, aber es sollte dir helfen, sie zu finden.", + correct: true + } + ]} +/> + +{/if} diff --git a/chapters/de/chapter4/1.mdx b/chapters/de/chapter4/1.mdx index d0130e5f3..3fbb8da19 100644 --- a/chapters/de/chapter4/1.mdx +++ b/chapters/de/chapter4/1.mdx @@ -1,18 +1,18 @@ -# Der Hugging Face Hub - -Der [Hugging Face Hub](https://huggingface.co/) –- unsere Hauptwebseite –- ist eine zentrale Platform, wo Nutzer*innen "state-of-the-art" Modelle und Datensätze entdecken, benutzen und dazu beitragen können. Eine große Vielfalt an Modellen steht öffentlich zur Verfügung auf der Platform – insgesamt mehr als 10000 Modelle. In diesem Kapitel fokusieren wir uns auf die Modelle und die Datensätze werden wir uns im Kapitel 5 anschauen. - -Die Modelle auf dem Hub sind nicht auf 🤗 Transformers bzw. NLP eingeschränkt. -Es gibt Modelle von [Flair](https://github.com/flairNLP/flair) und [AllenNLP](https://github.com/allenai/allennlp) für NLP, [Asteroid](https://github.com/asteroid-team/asteroid) und [pyannote](https://github.com/pyannote/pyannote-audio) für Spracherkennung, und [timm](https://github.com/rwightman/pytorch-image-models) für Computer Vision, um ein paar Beispiele zu nennen. - -Jedes Modell wird als Git-Repository gehosted, was Versionierung und Reproduzierbarkeit ermöglicht. Durch das Teilen eines Modells wird dieses der Community zur Verfügung gestellt. Somit wird das Teilen und die Anwendung vom Modell einfacher und jede/r hat die Möglichkeit, das Modell zu Verwenden, ohne es selbst trainieren zu müssen. - -Dazu löst das Teilen eines Modells auf dem Hub automatisch das Deployment einer Hosted-Inferenz-API für das Modell aus. Jede/r in der Communinity kann das Modell direkt auf der Modellsseite mit benutzerdefinierten Inputs und passenden Widgets ausprobieren. - -Das Beste ist, dass sowohl das Teilen als auch das Nutzen von öffentlichen Modellen auf dem Hub völlig kostenlos erfolgt! [Bezahlte Pläne](https://huggingface.co/pricing) gibt es auch, falls du Modelle privat teilen möchtest. - -Das folgende Video zeigt, wie man auf dem Hub navigieren kann. - - - -Ein huggingface.co Account ist für den folgenden Teil erforderlich, da wir Repositories auf dem Hugging Face Hub erstellen und verwalten werden: [Account erstellen](https://huggingface.co/join) +# Der Hugging Face Hub + +Der [Hugging Face Hub](https://huggingface.co/) –- unsere Hauptwebseite –- ist eine zentrale Platform, wo Nutzer*innen "state-of-the-art" Modelle und Datensätze entdecken, benutzen und dazu beitragen können. Eine große Vielfalt an Modellen steht öffentlich zur Verfügung auf der Platform – insgesamt mehr als 10000 Modelle. In diesem Kapitel fokusieren wir uns auf die Modelle und die Datensätze werden wir uns im Kapitel 5 anschauen. + +Die Modelle auf dem Hub sind nicht auf 🤗 Transformers bzw. NLP eingeschränkt. +Es gibt Modelle von [Flair](https://github.com/flairNLP/flair) und [AllenNLP](https://github.com/allenai/allennlp) für NLP, [Asteroid](https://github.com/asteroid-team/asteroid) und [pyannote](https://github.com/pyannote/pyannote-audio) für Spracherkennung, und [timm](https://github.com/rwightman/pytorch-image-models) für Computer Vision, um ein paar Beispiele zu nennen. + +Jedes Modell wird als Git-Repository gehosted, was Versionierung und Reproduzierbarkeit ermöglicht. Durch das Teilen eines Modells wird dieses der Community zur Verfügung gestellt. Somit wird das Teilen und die Anwendung vom Modell einfacher und jede/r hat die Möglichkeit, das Modell zu Verwenden, ohne es selbst trainieren zu müssen. + +Dazu löst das Teilen eines Modells auf dem Hub automatisch das Deployment einer Hosted-Inferenz-API für das Modell aus. Jede/r in der Communinity kann das Modell direkt auf der Modellsseite mit benutzerdefinierten Inputs und passenden Widgets ausprobieren. + +Das Beste ist, dass sowohl das Teilen als auch das Nutzen von öffentlichen Modellen auf dem Hub völlig kostenlos erfolgt! [Bezahlte Pläne](https://huggingface.co/pricing) gibt es auch, falls du Modelle privat teilen möchtest. + +Das folgende Video zeigt, wie man auf dem Hub navigieren kann. + + + +Ein huggingface.co Account ist für den folgenden Teil erforderlich, da wir Repositories auf dem Hugging Face Hub erstellen und verwalten werden: [Account erstellen](https://huggingface.co/join) diff --git a/chapters/de/chapter4/2.mdx b/chapters/de/chapter4/2.mdx index 082e5040c..bc1a9a049 100644 --- a/chapters/de/chapter4/2.mdx +++ b/chapters/de/chapter4/2.mdx @@ -1,95 +1,95 @@ - - -# Verwendung vortrainierter Modelle - -{#if fw === 'pt'} - - - -{:else} - - - -{/if} - - -Der Model Hub erleichtert das Auswählen des passenden Modells, sodass es von downstream Libraries mit wenigen Codezeilen benutzt werden kann. Lass uns anschauen, wie genau man solche Modelle verwendet und wie man der Communinity zurück beitragen kann. - -Nehmen wir an, wir suchen nach einem französichbasierten Modell, das die "mask filling" Aufgabe kann. - -
-Selecting the Camembert model. -
- -Wir wählen den `camembert-base` Checkpoint aus, um es zu auszuprobieren. Das Kennzeichen `camembert-base` ist alles, was wir brauchen, um loszulegen! Wie in früheren Kapiteln gezeigt wurde, können wir das Modell mit der `pipeline()` Funktion instanziieren: - -```py -from transformers import pipeline - -camembert_fill_mask = pipeline("fill-mask", model="camembert-base") -results = camembert_fill_mask("Le camembert est :)") -``` - -```python out -[ - {'sequence': 'Le camembert est délicieux :)', 'score': 0.49091005325317383, 'token': 7200, 'token_str': 'délicieux'}, - {'sequence': 'Le camembert est excellent :)', 'score': 0.1055697426199913, 'token': 2183, 'token_str': 'excellent'}, - {'sequence': 'Le camembert est succulent :)', 'score': 0.03453313186764717, 'token': 26202, 'token_str': 'succulent'}, - {'sequence': 'Le camembert est meilleur :)', 'score': 0.0330314114689827, 'token': 528, 'token_str': 'meilleur'}, - {'sequence': 'Le camembert est parfait :)', 'score': 0.03007650189101696, 'token': 1654, 'token_str': 'parfait'} -] -``` -So einfach kann man mit einer Pipeline ein Modell laden. Dabei muss man nur darauf achten, den passenden Checkpoint für die gewünschte Aufgabe zu selektieren. Zum Beispiel: Wir laden hier den `camembert-base` Checkpoint in die `fill-mask` Pipeline, was schon korrekt ist. Aber würden wir diesen Checkpoint in die `text-classification` Pipeline laden, wären die Ergebnisse völlig sinnlos, weil der "head" von `camembert-base` für diese Aufgabe einfach nicht passt! Wir empfehlen, den "Task Selector" auf der Hugging Face Hub Seite zu benutzen, um die richtigen Checkpoints auszuwählen: - -
-The task selector on the web interface. -
- -Du kannst auch den Checkpoint mit der Modell-Architektur direkt instanziieren: - -{#if fw === 'pt'} -```py -from transformers import CamembertTokenizer, CamembertForMaskedLM - -tokenizer = CamembertTokenizer.from_pretrained("camembert-base") -model = CamembertForMaskedLM.from_pretrained("camembert-base") -``` - -Dennoch empfehlen wir, dass man die [`Auto*` classes](https://huggingface.co/transformers/model_doc/auto?highlight=auto#auto-classes) stattdessen benutzt, da diese architekturunabhängig sind. Das vorherige Code-Beispiel gilt nur für Checkpoints, die in die CamemBERT Architektur zu laden sind, aber mit den `Auto*` Klassen kann man Checkpoints ziemlich einfach tauschen: - -```py -from transformers import AutoTokenizer, AutoModelForMaskedLM - -tokenizer = AutoTokenizer.from_pretrained("camembert-base") -model = AutoModelForMaskedLM.from_pretrained("camembert-base") -``` -{:else} -```py -from transformers import CamembertTokenizer, TFCamembertForMaskedLM - -tokenizer = CamembertTokenizer.from_pretrained("camembert-base") -model = TFCamembertForMaskedLM.from_pretrained("camembert-base") -``` - -Hier empfehlen wir auch, dass man stattdessen die [`TFAuto*` classes](https://huggingface.co/transformers/model_doc/auto?highlight=auto#auto-classes) benutzt, da diese architekturunabhängig sind. Das vorherige Code-Beispiel gilt nur für Checkpoints, die in die CamemBERT Architektur zu laden sind, aber mit den `TFAuto*` Klassen kann man Checkpoints einfach tauschen: - -```py -from transformers import AutoTokenizer, TFAutoModelForMaskedLM - -tokenizer = AutoTokenizer.from_pretrained("camembert-base") -model = TFAutoModelForMaskedLM.from_pretrained("camembert-base") -``` -{/if} - -> [!TIP] -> Wenn du ein vortrainiertes Modell verwendest, prüf erstmal, wie genau das traininert wurde, mit welchen Datensätzen, sowie seine Einschränkungen und Biases. All diese Informationen sollten auf der Modellbeschreibungskarte stehen. + + +# Verwendung vortrainierter Modelle + +{#if fw === 'pt'} + + + +{:else} + + + +{/if} + + +Der Model Hub erleichtert das Auswählen des passenden Modells, sodass es von downstream Libraries mit wenigen Codezeilen benutzt werden kann. Lass uns anschauen, wie genau man solche Modelle verwendet und wie man der Communinity zurück beitragen kann. + +Nehmen wir an, wir suchen nach einem französichbasierten Modell, das die "mask filling" Aufgabe kann. + +
+Selecting the Camembert model. +
+ +Wir wählen den `camembert-base` Checkpoint aus, um es zu auszuprobieren. Das Kennzeichen `camembert-base` ist alles, was wir brauchen, um loszulegen! Wie in früheren Kapiteln gezeigt wurde, können wir das Modell mit der `pipeline()` Funktion instanziieren: + +```py +from transformers import pipeline + +camembert_fill_mask = pipeline("fill-mask", model="camembert-base") +results = camembert_fill_mask("Le camembert est :)") +``` + +```python out +[ + {'sequence': 'Le camembert est délicieux :)', 'score': 0.49091005325317383, 'token': 7200, 'token_str': 'délicieux'}, + {'sequence': 'Le camembert est excellent :)', 'score': 0.1055697426199913, 'token': 2183, 'token_str': 'excellent'}, + {'sequence': 'Le camembert est succulent :)', 'score': 0.03453313186764717, 'token': 26202, 'token_str': 'succulent'}, + {'sequence': 'Le camembert est meilleur :)', 'score': 0.0330314114689827, 'token': 528, 'token_str': 'meilleur'}, + {'sequence': 'Le camembert est parfait :)', 'score': 0.03007650189101696, 'token': 1654, 'token_str': 'parfait'} +] +``` +So einfach kann man mit einer Pipeline ein Modell laden. Dabei muss man nur darauf achten, den passenden Checkpoint für die gewünschte Aufgabe zu selektieren. Zum Beispiel: Wir laden hier den `camembert-base` Checkpoint in die `fill-mask` Pipeline, was schon korrekt ist. Aber würden wir diesen Checkpoint in die `text-classification` Pipeline laden, wären die Ergebnisse völlig sinnlos, weil der "head" von `camembert-base` für diese Aufgabe einfach nicht passt! Wir empfehlen, den "Task Selector" auf der Hugging Face Hub Seite zu benutzen, um die richtigen Checkpoints auszuwählen: + +
+The task selector on the web interface. +
+ +Du kannst auch den Checkpoint mit der Modell-Architektur direkt instanziieren: + +{#if fw === 'pt'} +```py +from transformers import CamembertTokenizer, CamembertForMaskedLM + +tokenizer = CamembertTokenizer.from_pretrained("camembert-base") +model = CamembertForMaskedLM.from_pretrained("camembert-base") +``` + +Dennoch empfehlen wir, dass man die [`Auto*` classes](https://huggingface.co/transformers/model_doc/auto?highlight=auto#auto-classes) stattdessen benutzt, da diese architekturunabhängig sind. Das vorherige Code-Beispiel gilt nur für Checkpoints, die in die CamemBERT Architektur zu laden sind, aber mit den `Auto*` Klassen kann man Checkpoints ziemlich einfach tauschen: + +```py +from transformers import AutoTokenizer, AutoModelForMaskedLM + +tokenizer = AutoTokenizer.from_pretrained("camembert-base") +model = AutoModelForMaskedLM.from_pretrained("camembert-base") +``` +{:else} +```py +from transformers import CamembertTokenizer, TFCamembertForMaskedLM + +tokenizer = CamembertTokenizer.from_pretrained("camembert-base") +model = TFCamembertForMaskedLM.from_pretrained("camembert-base") +``` + +Hier empfehlen wir auch, dass man stattdessen die [`TFAuto*` classes](https://huggingface.co/transformers/model_doc/auto?highlight=auto#auto-classes) benutzt, da diese architekturunabhängig sind. Das vorherige Code-Beispiel gilt nur für Checkpoints, die in die CamemBERT Architektur zu laden sind, aber mit den `TFAuto*` Klassen kann man Checkpoints einfach tauschen: + +```py +from transformers import AutoTokenizer, TFAutoModelForMaskedLM + +tokenizer = AutoTokenizer.from_pretrained("camembert-base") +model = TFAutoModelForMaskedLM.from_pretrained("camembert-base") +``` +{/if} + +> [!TIP] +> Wenn du ein vortrainiertes Modell verwendest, prüf erstmal, wie genau das traininert wurde, mit welchen Datensätzen, sowie seine Einschränkungen und Biases. All diese Informationen sollten auf der Modellbeschreibungskarte stehen. diff --git a/chapters/de/chapter4/3.mdx b/chapters/de/chapter4/3.mdx index 6a9b99441..99eee5a85 100644 --- a/chapters/de/chapter4/3.mdx +++ b/chapters/de/chapter4/3.mdx @@ -1,632 +1,632 @@ - - -# Vortrainierte Modelle teilen - -{#if fw === 'pt'} - - - -{:else} - - - -{/if} - -Demnächst schauen wir uns an, wie man am einfachsten vortrainierte Modelle auf dem 🤗 Hub teilen kann. -Es gibt schon Tools und Hilfsmittel, die das Teilen und Updaten von Modellen auf dem Hub vereinfachen. Die werden wir gleich unten explorieren. - - - -Wir empfehlen allen Nutzer:innen, die Modelle trainieren, dass sie der Communinity beitragen, indem sie Modelle teilen. Selbst die Modelle, die auf sehr spezifische Datensätze trainiert wurden, werden anderen Nutzer:innen helfen, weil man Zeit und Rechenressourcen spart und Zugang zu nützlichen Trainingsartifakten bekommt. Also eventuell kannst du auch von der Arbeit anderer Nutzer:innen auch profitieren! - -Es gibt drei Wege, um Repositories zu neuen Modellen zu kreieren: - -- Mittels der `push_to_hub` API -- Mittels der `huggingface_hub` Python Bibliothek -- Mittels der Web-Oberfläche - -Nachdem du einen Repository erstellst hast, kannst du die Dateien über git und git-lfs hochladen. Demnächst zeigen wir dir die genauen Schritte, um Modell-Repositories zu erstellenund Dateien hochzuladen. - - -## Hochladen mit der `push_to_hub` API - -{#if fw === 'pt'} - - - -{:else} - - - -{/if} - -Die einfachste Variante, um Dateien auf den Hub hochzuladen, ist mittels der `push_to_hub` API. Bevor du weitermachst, must du einen Autentifizierungstoken generieren, damit die `huggingface_hub` API weißt, wer du bist und auf welche Namespaces du zugreifen darfst. Stell sicher, dass du in einer Umgebung mit `transformers` installiert bist (siehe [Setup](/course/chapter0)). Wenn du auf einem Notebook bist, kannst du diese Funktion benutzen, um dich einzuloggen: - -```python -from huggingface_hub import notebook_login - -notebook_login() -``` - -Im Terminal kannst folgendes ausführen: - -```bash -huggingface-cli login -``` - -In beiden Fällen solltest du nach deinem Username und Passwort gefragt werden. Das sind die selben, mit denen du dich auf dem Hub einloggst. Solltest du noch kein Hub-Profil haben, musst du erstmal eins [hier](https://huggingface.co/join) erstellen. - -Großartig! Nun hast du deinen Autentifizierungstoken in deinem Cache-Ordner gespeichert. Lass uns ein paar Repositories erstellen! - -{#if fw === 'pt'} - -Wenn du schon Modelle mit der `Trainer` API trainiert hast, dann ist der einfachste Weg, um Modelle hochzuladen, das Argument `push_to_hub=True` in `TrainingArguments` einzustellen. - -```py -from transformers import TrainingArguments - -training_args = TrainingArguments( - "bert-finetuned-mrpc", save_strategy="epoch", push_to_hub=True -) -``` - -Wenn du `trainer.train()` aufrufst, lädt der `Trainer` das Modell auf den Hub zu dem Repository in deinem Namespace hoch. Das passiert jedes Mal, wenn das Modell gespeichert wird (in diesem Beispiel jede Epoche). Der Repository wird so benannt werden, wie der Output-Ordner, den du gewählt hast (hier `bert-finetuned-mrpc`). Natürlich kannst du dir aber einen anderen Namen ausdenken und mit `hub_model_id = "a_different_name"` setzen. - -Um dein Modell zu einer Organisation, wovon du Mitglied bist, hochzuladen, kannst du einfach `hub_model_id = "my_organization/my_repo_name"` mit eingeben. - -Wenn das Training durch ist, must du noch einmal `trainer.push_to_hub()` ausführen, um die letzte Version deines Modells hochzuladen. Das wird auch eine Modell-Karte generieren, auf der die relevanten Metadaten mit den benutzten Hyperparametern und Evaluierungsergebnissen! Hier ist ein Beispiel von dem Inhalt, den du auf so einer Modell-Karte finden kannst: - -
- An example of an auto-generated model card. -
- -{:else} - -Wenn du für das Modell-Training Keras benutzt, ist der einfachste Weg, um das Modell aud den Hub hochzuladen, den `PushToHubCallback` zu setzen, wenn du `model.fit()` aufrufst. - -```py -from transformers import PushToHubCallback - -callback = PushToHubCallback( - "bert-finetuned-mrpc", save_strategy="epoch", tokenizer=tokenizer -) -``` - -Danach must du noch `callbacks=[callback]` beim `model.fit()` Aufruf setzen. -Der Callback wird das Modell auf den Hub hochladen und zwar zu einem Repository in deinem Namespace. Das passiert jedes Mal, wenn das Modell gespeichert wird (in diesem Beispiel jede Epoche). Der Repository wird so benannt werden, wie der Output-Ordner, den du gewählt hast (hier `bert-finetuned-mrpc`). Natürlich kannst du dir aber einen anderen Namen ausdenken und mit `hub_model_id = "a_different_name"` setzen. - -Um dein Modell zu einer Organisation, wovon du Mitglied bist, hochzuladen, kannst du einfach `hub_model_id = "my_organization/my_repo_name"` mit eingeben. - - -{/if} - -Auf einer tieferen Ebene kann man auf Modelle, Tokenizers und Konfigurationen auf dem Model-Hub direkt zugreifen, indem man die Methode `push_to_hub()` benutzt. -Diese Methode kümmert sich sowohl um das Erstellen vom Repository als auch das Pushen (Hochladen) von Modell- und Tokenizer-Dateien auf den Repository. Also da ist kein manueller Schritt notwendig (im Gegensatz zu den APIs, die wir demnächst sehen werden). - -Um uns eine Vorstellung zu schaffen, wie es funktioniert, lass uns zuerst ein Modell und einen Tokenizer initialisieren: - -{#if fw === 'pt'} -```py -from transformers import AutoModelForMaskedLM, AutoTokenizer - -checkpoint = "camembert-base" - -model = AutoModelForMaskedLM.from_pretrained(checkpoint) -tokenizer = AutoTokenizer.from_pretrained(checkpoint) -``` -{:else} -```py -from transformers import TFAutoModelForMaskedLM, AutoTokenizer - -checkpoint = "camembert-base" - -model = TFAutoModelForMaskedLM.from_pretrained(checkpoint) -tokenizer = AutoTokenizer.from_pretrained(checkpoint) -``` -{/if} - -Dir steht frei, was du mit diesen machst, z.B. Tokens zum Tokenizer hinzuzufügen, das Modell zu trainineren oder zu finetunen. Wenn du mit dem Modell, Gewichten und Tokenizer zufrieden bist, kannst du die Methode `push_to_hub()` vom `model` Objekt benutzten: - -```py -model.push_to_hub("dummy-model") -``` -Das wird den neuen Repository `dummy-model` in deinem Profil erstellen und den mit deinen Model-Dateien befüllen. Mach das gliche mit dem Tokenizer, sodass jetzt alle Dateien in diesem Repository verfügbar sind. - -```py -tokenizer.push_to_hub("dummy-model") -``` -Wenn du Teil einer Organisation bist, kannst du einfach das Argument `organization` mit eingeben, um die Artifakte auf den Namespace dieser Organisation hochzuladen. - -```py -tokenizer.push_to_hub("dummy-model", organization="huggingface") -``` - -Wenn du einen bestimmten Hugging Face Token benutzten möchtest, kannst du ihn auch in der Methode `push_to_hub()` spezifizieren: - -```py -tokenizer.push_to_hub("dummy-model", organization="huggingface", use_auth_token="") -``` - -Nun geh auf den Model Hub, um dein hochgeladenes Modell zu finden: *https://huggingface.co/user-or-organization/dummy-model*. - -Click auf den Tab "Files and versions" und da solltest du die Dateien finden, die auf diesem Screenshot zu sehen sind: - -{#if fw === 'pt'} -
-Dummy model containing both the tokenizer and model files. -
-{:else} -
-Dummy model containing both the tokenizer and model files. -
-{/if} - -> [!TIP] -> ✏️ **Probier das selber aus!** Lade das Modell und den Tokenizer vom Checkpoint `bert-base-cased` mit der Methode `push_to_hub()` hoch. Überprüfe, dass der Repository auf deiner Seite richtig erscheint, bevor du den löschst. - -Wie du schon gesehen hast, akzeptiert die Methode `push_to_hub()` mehrere Argumente. Dies erlaub das Hochladen auf den Namespace eines spezifischen Repositorys oder einer Organisation, sowie die Möglichkeit, einen anderen API Token zu benutzten. Wir empfehlen dir, die Dokumentation der Methode direkt auf [🤗 Transformers documentation](https://huggingface.co/transformers/model_sharing.html) zu lesen, um dir eine Vorstellung zu schaffen, was alles damit möglich ist. - -Die `push_to_hub()` Methode funktioniert im Hintergrund mit der Python Bibliothek [`huggingface_hub`](https://github.com/huggingface/huggingface_hub), die eine direkte API zum Hugging Face Hub anbietet. Sie ist auch drin in der 🤗 Transformers Bibliothek und mehreren anderen Machine Learning Bibliotheken, z.B. [`allenlp`](https://github.com/allenai/allennlp). Obwohl wir in diesem Kapitel den Fokus auf die Integration mit 🤗 Transformers legen, kannst du es in deinen eigenen Code bzw. eigene Bibliothek relativ einfach integrieren. Spring auf den letzten Part, um zu erfahren, wie man Dateien auf einen frisch erstellten Repository hochladen kann! - -## Verwendung der `huggingface_hub` Python Bibliothek -Die `huggingface_hub` Python Bibliothek ist ein Python Packet, das einige Werkzeuge für das Nutzen von Modell- und Datasethub anbietet. Es bietet simple Methoden und Klassen für gängige Aufgaben, z.B. um Information zu Repositories auf dem Hub zu bekommen oder um sie zu Verwalten. Es bietet auch simple auf git basierende APIs, um die Inhalte von solchen Repositories zu verwalten sowie um den Hub in deine Projekte und Bibliotheken zu integrieren. - -Ähnlich wie bei der Verwendung der`push_to_hub` API ist es bei diesen Aktionen erforderlich, dass dein API Token schon in deinem Cache gespeichert ist. Dafür musst du den `login` Befehl aus der CLI ausführen so wie in dem vorherigen Teil erklärt wurde (nochmal: Vergiss nicht, das `!` Zeichen vor die Befehle zu setzen, wenn du im Google Colab arbeitest). - -```bash -huggingface-cli login -``` - -Die `huggingface_hub` Bibliothek bietet mehrere nützliche Methoden und Klassen an. Erstens gibt es einige Methoden, um das Erstellen, Löschen, usw. von Repositories durchzuführen: - - -```python no-format -from huggingface_hub import ( - # User-Management - login, - logout, - whoami, - - # Repository erstellen und managen - create_repo, - delete_repo, - update_repo_visibility, - - # Methoden, um inhaltliche Information abzufragen/abzuändern - list_models, - list_datasets, - list_metrics, - list_repo_files, - upload_file, - delete_file, -) -``` - -Außerdem gibt es die sehr mächtige `Repository` Klasse, um einen lokalen Repository zu managen. Demnächst werden wir uns mit diesen Methoden und dieser Klasse beschäftigen, um zu verstehen, wie man die am besten nutzt. - -Mit der `create_repo` Methode kann ein neuer Repository auf dem Hub erstellt werden: - -```py -from huggingface_hub import create_repo - -create_repo("dummy-model") -``` - -Das erstellt den Repository `dummy-model` unter deinem Namespace. Wenn du möchtest, kannst du auch die Organisation spezifizieren, zu der der Repository gehören sollte, indem du das `organization` Argument setzt: - -```py -from huggingface_hub import create_repo - -create_repo("dummy-model", organization="huggingface") -``` - -Das erstellt den Repository `dummy-model` unter dem `huggingface` Namespace – angenommen du gehörst zu dieser Organisation. -Andere eventuell nützliche Argumente sind: - -- `private`: um zu spezifizieren, ob der Repository für andere sichtbar sein sollte oder nicht. -- `token`: um den Token, der im Zwischenspeicher (Cache) liegt, mit einem neuen Token zu überscheiben. -- `repo_type`: zum Auswählen, ob du einen `dataset` oder einen `space` anstatt von einem Modell kreieren möchtest. Erlaubte Werte sind `"dataset"` und `"space"`. - -Nachdem der Repository erstellt wurde, können wir Dateien hinzufügen! Spring zum nächsten Abschnitt, um drei Varianten dazu zu lernen, wie man das machen kann. - -## Mit der Webinterface - -Die Webinterface bietet Tools an, um Repositories direkt auf dem Hub zu managen. Damit kannst du ganz einfach Repositories erstellen, Dateien hinzufügen (sogar große Dateien), Modelle explorieren, Unterschiede ("diffs") visualisieren und viel mehr. - -Um einen Repository zu erstellen, geh auf [huggingface.co/new](https://huggingface.co/new): - -
-Beispiel vom Modell, mit dem man einen Repository erstellen kann. -
- -Erstens muss man den Besitzer vom Repository eingeben: Das kannst entweder du selbst oder jede andere Person von der Organisation sein, zu der du gehörst. Wenn du eine Organisation auswählst, wird das Modell auf der Seite der Organisation präsentiert und jedes Mitglied der Organisation wird zu diesem Repository beitragen können. - -Als nächstes gib den Namen deines Modells ein. So wird der Repository auch heißen. Zuletzt kannst du spezifizieren, ob das Modell öffentlich oder privat sein soll. Private Modelle sind von der Öffentlichkeit unsichtbar. - -Nach der Erstellung des Repositorys solltest du so eine Seite sehen können: - -
-Leeres Modell nach der Erstellung des Repositorys. -
- -Hier wird dein Modell gehostet. Um mit dem Auffüllen zu beginnen, kannst du direkt über die Weboberfläche eine README-Datei hinzufügen. - -
-The README file showing the Markdown capabilities. -
- -Die README-Datei ist im Markdown Format — du kannst dich damit gerne austoben! -Der dritte Teil dieses Kapitels zielt darauf hin, eine "model card" (Steckbrief) zu bauen. Steckbriefe haben eine entscheidende Relevanz, um dein Modell wertvoll zu machen, denn du kannst dort anderen erzählen, was das Modell kann. - -Wenn du dir den "Files and versions" Tab anschaust, wirst du sehen, dass noch nicht viele Dateien darauf sind – nämlich nur die von dir eben kreierte *README.md* und die *.gitattributes* (wo große Dateien geloggt werden). - - -
-The 'Files and versions' tab only shows the .gitattributes and README.md files. -
- -Gleich werden wir sehen, wie wir neue Dateien hinzufügen können. - -## Hochladen von Modell-Dateien - -Das System zum Managen der Dateien auf Hugging Face Hub basiert auf git für normale Dateien und auf git-lfs ([Git Large File Storage](https://git-lfs.github.com/)) für größere Dateien. - -Im nächsten Teil schauen wir uns drei Möglichkeitein an, um Dateien mittels `huggingface_hub` und git-Befehle auf den Hub hochzuladen. - -### Die `upload_file` Variante - -Um `upload_file` zu verwenden, muss man nicht unbedingt git und git-lfs installiert haben. Die Funktion lädt Dateien auf den 🤗 Hub mittels HTTP POST Anfragen. Eine Einschränkunf dieser Variante ist, dass man nur mit Dateien unter 5GB groß arbeiten kann. -Wenn deine Dateien größer als 5GB sind, nutz eine von den folgenden zwei Methoden. - -Die API kann folgendermaßen benutzt werden: - -```py -from huggingface_hub import upload_file - -upload_file( - "/config.json", - path_in_repo="config.json", - repo_id="/dummy-model", -) -``` -Das wird die `config.json` Datei in `` auf das Root-Verzeichnis vom Repository als `config.json` vom `dummy-model` Repository. -Andere nützliche Argumente : - -- `token`, um den Token zu überscheiben, der in deinem Cache gespeichert ist -- `repo_type`, wenn du anstatt von einem Modell Dateien auf einen `dataset` oder `space` hochladen möchtest. Valide Werte sind `"dataset"` und `"space"`. - - -### Die `Repository` Klasse - -Die `Repository` Klasse verwaltet einen lokalen Repository so wie git. Sie abstrahiert aber die meisten schwierigen Punkte, auf die man stoßen würde, wenn man eine ähnliche Funktionalität mit git erreichen möchte. - -Diese Klasse braucht git und git-lfs im System schon installiert. Also stell sicher, dass du git-lfs installiert hast (siehe [hier](https://git-lfs.github.com/) für Installationsanweisungen) und richte alles ein, bevor du loslegst. - -Um mit dem Repository rumspielen zu starten, können wir den in einem lokalen Ordner initialisieren, in dem wir den Remote-Repository klonen: - -```py -from huggingface_hub import Repository - -repo = Repository("", clone_from="/dummy-model") -``` - -Das hat den Ordner `` in unserem Arbeitsverzeichnis erstellt. Dieser Ordner enthält bisher nur die `.gitattributes` Datel, da diese die einzige Datei ist, die wir mit `create_repo` kreiert haben. - -Ab jetzt können mehrere gängige Methoden benutzten: - -```py -repo.git_pull() -repo.git_add() -repo.git_commit() -repo.git_push() -repo.git_tag() -``` - -Und andere Optionen auch! Wir empfehlen, dass du dir die Dokumentation zu `Repository`, die dir [hier](https://github.com/huggingface/huggingface_hub/tree/main/src/huggingface_hub#advanced-programmatic-repository-management) zur Verfügung steht, anschaust, um dir eine Übersicht aller verfügbaren Methoden zu verschaffen. - -Bisher haben wir ein Modell und einen Tokenizer, die wir gerne auf den Hub pushen würden. Wir haben auch den Repository geklont, sodass wir die Dateien in dem Repository speichern können. - -Zuerst stellen wir sicher, dass unser lokaler Repository einen aktuellen Stand hat, in dem wir die letzten Änderungen pullen: - -```py -repo.git_pull() -``` - -Wenn das durch ist, speichern wir die Dateien vom Modell und Tokenizer: - -```py -model.save_pretrained("") -tokenizer.save_pretrained("") -``` - -Der Pfad `` beinhaltet jetzt alle Modell- und Tokenizerdateien. Wir folgen dem gängigen Git-Workflow, indem wir die Dateien in die "staging area" bringen, wir committen und pushen sie auf den hub: - -```py -repo.git_add() -repo.git_commit("Add model and tokenizer files") -repo.git_push() -``` - -Glückwunsch! Du hast gerade deine ersten Dateien auf den Hub hochgeladen. - -### Die git-basierte Variante - -Das ist der einfachste Weg zum Hochladen von Dateien: Wir werden es direkt mit git und git-lfs tun. Der Größtenteil der Schwierigkeit wird durch die früheren Ansätze abstrahiert, aber es gibt ein paar Vorbehalte bei der folgenden Methode, deswegen werden wir einem komplexeren Anwendungsfall folgen. - -Um diese Klasse zu benutzten, mussen wir git und git-lfs installiert haben. Also stell sicher, dass du [git-lfs](https://git-lfs.github.com/) installiert und aufgesetzt hast, bevor du beginst. - -Zuerst initialisiere git-lfs: - -```bash -git lfs install -``` - -```bash -Updated git hooks. -Git LFS initialized. -``` - -Danach musst du den Modell-Repository klonen: - -```bash -git clone https://huggingface.co// -``` - -Mein Username ist `lysandre` und ich habe den Modellnamen `dummy` benutzt. Also bei bei sieht der Befehl so aus: - -``` -git clone https://huggingface.co/lysandre/dummy -``` - -Ich habe jetzt einen Ordner namens *dummy* in meinem Arbeitsverzeichnis. Ich kann jetzt `cd` in den Ordner und mir den Inhalt anschauen: - -```bash -cd dummy && ls -``` - -```bash -README.md -``` - -Wenn du eben einen Repository mit der Hugging Face Hubs Methode `create_repo` erstellt hast, dann sollte dieser Ordner nur eine versteckte `.gitattributes` Datei enthalten. Wenn du es nach den Anweisungen in dem vorherigen Abschnitt mittels der Webinterface gemacht hast, dann sollte der Ordner eine einzige README.md Datei neben der `.gitattributes` enthalten – so wie hier angezeigt wird. - -Das Hinzufügen einer Datei mit normaler Größe, z.B. Konfiguration- oder Vokabulardatei, wird so gemach wie in einem git-basierten System. Aber größere Dateien müssen mit git-lfs registriert werden, um sie zu *huggingface.co* zu pushen. - -Lass uns kurz zurück zu Python, um ein Modell und einen Tokenizer zu generieren, die wir zu unserem dummy repository committen möchten: - -{#if fw === 'pt'} -```py -from transformers import AutoModelForMaskedLM, AutoTokenizer - -checkpoint = "camembert-base" - -model = AutoModelForMaskedLM.from_pretrained(checkpoint) -tokenizer = AutoTokenizer.from_pretrained(checkpoint) - -# Mach was du möchtest mit dem Modell, z.B. trainieren, fine-tunen. - -model.save_pretrained("") -tokenizer.save_pretrained("") -``` -{:else} -```py -from transformers import TFAutoModelForMaskedLM, AutoTokenizer - -checkpoint = "camembert-base" - -model = TFAutoModelForMaskedLM.from_pretrained(checkpoint) -tokenizer = AutoTokenizer.from_pretrained(checkpoint) - -# Mach was du möchtest mit dem Modell, z.B. trainieren, fine-tunen. - -model.save_pretrained("") -tokenizer.save_pretrained("") -``` -{/if} - -Jetzt haben wir die Modell- und Tokenizer-Artifakte gespeichert und können wir uns nochmal den *dummy* Ordner anschauen: - -```bash -ls -``` - -{#if fw === 'pt'} -```bash -config.json pytorch_model.bin README.md sentencepiece.bpe.model special_tokens_map.json tokenizer_config.json tokenizer.json -``` - -Wenn du dir die Dateigrößen anschaust (z.B. mit `ls -lh`), solltest du sehen, dass die Modell-Statedict Datei (*pytorch_model.bin*) der einzige Ausreißer ist mit über 400 MB. - -{:else} -```bash -config.json README.md sentencepiece.bpe.model special_tokens_map.json tf_model.h5 tokenizer_config.json tokenizer.json -``` - -Wenn du dir die Dateigrößen anschaust (z.B. mit `ls -lh`), solltest du sehen, dass die Modell-Statedict Datei (*t5_model.h5*) der einzige Ausreißer ist mit über 400 MB. - -{/if} - -> [!TIP] -> ✏️ Wenn ein Repository mittels der Webinterface kreiert wird, wird die *.gitattributes* Datei automatisch gesetzt, um bestimmte Dateiendungen wie *.bin* und *.h5* als große Dateien zu betrachten, sodass git-lfs sie tracken kann, ohne dass du weiteres konfigurieren musst. - -Nun können wir weitermachen und so arbeiten wie wir es mit normalen Git Repositories machen. Wir können die Dateien stagen mit dem Git-Befehl `git add`: - -```bash -git add . -``` - -Jetzt schauen wir, welche Dateien gestaged wurden: - -```bash -git status -``` - -{#if fw === 'pt'} -```bash -On branch main -Your branch is up to date with 'origin/main'. - -Changes to be committed: - (use "git restore --staged ..." to unstage) - modified: .gitattributes - new file: config.json - new file: pytorch_model.bin - new file: sentencepiece.bpe.model - new file: special_tokens_map.json - new file: tokenizer.json - new file: tokenizer_config.json -``` -{:else} -```bash -On branch main -Your branch is up to date with 'origin/main'. - -Changes to be committed: - (use "git restore --staged ..." to unstage) - modified: .gitattributes - new file: config.json - new file: sentencepiece.bpe.model - new file: special_tokens_map.json - new file: tf_model.h5 - new file: tokenizer.json - new file: tokenizer_config.json -``` -{/if} - -Ähnlicherweise können wir sicherstellen, dass git-lfs die richtigen Dateien trackt mit dem `status` Befehl: - -```bash -git lfs status -``` - -{#if fw === 'pt'} -```bash -On branch main -Objects to be pushed to origin/main: - - -Objects to be committed: - - config.json (Git: bc20ff2) - pytorch_model.bin (LFS: 35686c2) - sentencepiece.bpe.model (LFS: 988bc5a) - special_tokens_map.json (Git: cb23931) - tokenizer.json (Git: 851ff3e) - tokenizer_config.json (Git: f0f7783) - -Objects not staged for commit: - - -``` - -Da sehen wir, dass alle Dateien `Git` als Handler haben. Nur die *pytorch_model.bin* und *sentencepiece.bpe.model* Dateien haben `LFS`. Toll! - -{:else} -```bash -On branch main -Objects to be pushed to origin/main: - - -Objects to be committed: - - config.json (Git: bc20ff2) - sentencepiece.bpe.model (LFS: 988bc5a) - special_tokens_map.json (Git: cb23931) - tf_model.h5 (LFS: 86fce29) - tokenizer.json (Git: 851ff3e) - tokenizer_config.json (Git: f0f7783) - -Objects not staged for commit: - - -``` - -Da sehen wir, dass alle Dateien `Git` als Handler haben. Nur die *t5_model.h5* hat `LFS`. Sehr gut! - -{/if} - -Lass uns mit den letzten Schritten weitermachen, indem wir die Änderungen commiten und zum *huggingface.co* Remote-Repository pushen: - -```bash -git commit -m "First model version" -``` - -{#if fw === 'pt'} -```bash -[main b08aab1] First model version - 7 files changed, 29027 insertions(+) - 6 files changed, 36 insertions(+) - create mode 100644 config.json - create mode 100644 pytorch_model.bin - create mode 100644 sentencepiece.bpe.model - create mode 100644 special_tokens_map.json - create mode 100644 tokenizer.json - create mode 100644 tokenizer_config.json -``` -{:else} -```bash -[main b08aab1] First model version - 6 files changed, 36 insertions(+) - create mode 100644 config.json - create mode 100644 sentencepiece.bpe.model - create mode 100644 special_tokens_map.json - create mode 100644 tf_model.h5 - create mode 100644 tokenizer.json - create mode 100644 tokenizer_config.json -``` -{/if} - -Das Pushen kann ein bisschen dauern, je nach dem wie schnell deine Internetverbindung ist und wie groß deine Dateien sind: - -```bash -git push -``` - -```bash -Uploading LFS objects: 100% (1/1), 433 MB | 1.3 MB/s, done. -Enumerating objects: 11, done. -Counting objects: 100% (11/11), done. -Delta compression using up to 12 threads -Compressing objects: 100% (9/9), done. -Writing objects: 100% (9/9), 288.27 KiB | 6.27 MiB/s, done. -Total 9 (delta 1), reused 0 (delta 0), pack-reused 0 -To https://huggingface.co/lysandre/dummy - 891b41d..b08aab1 main -> main -``` - -{#if fw === 'pt'} -Wenn alles durch ist, können wir uns den Repository anschauen und die eben hinzugefügten Dateien finden: - -
-The 'Files and versions' tab now contains all the recently uploaded files. -
- -Mit der UI kannst du die Modell-Dateien und die Commits explorieren, um die Differenz bei jedem Commit zu sehen: - -
-The diff introduced by the recent commit. -
-{:else} - -Wenn alles durch ist, können wir uns den Repository anschauen und die eben hinzugefügten Dateien finden: - -
-The 'Files and versions' tab now contains all the recently uploaded files. -
- -Mit der UI kannst du die Modell-Dateien und die Commits explorieren, um die Differenz bei jedem Commit zu sehen: - -
-The diff introduced by the recent commit. -
-{/if} + + +# Vortrainierte Modelle teilen + +{#if fw === 'pt'} + + + +{:else} + + + +{/if} + +Demnächst schauen wir uns an, wie man am einfachsten vortrainierte Modelle auf dem 🤗 Hub teilen kann. +Es gibt schon Tools und Hilfsmittel, die das Teilen und Updaten von Modellen auf dem Hub vereinfachen. Die werden wir gleich unten explorieren. + + + +Wir empfehlen allen Nutzer:innen, die Modelle trainieren, dass sie der Communinity beitragen, indem sie Modelle teilen. Selbst die Modelle, die auf sehr spezifische Datensätze trainiert wurden, werden anderen Nutzer:innen helfen, weil man Zeit und Rechenressourcen spart und Zugang zu nützlichen Trainingsartifakten bekommt. Also eventuell kannst du auch von der Arbeit anderer Nutzer:innen auch profitieren! + +Es gibt drei Wege, um Repositories zu neuen Modellen zu kreieren: + +- Mittels der `push_to_hub` API +- Mittels der `huggingface_hub` Python Bibliothek +- Mittels der Web-Oberfläche + +Nachdem du einen Repository erstellst hast, kannst du die Dateien über git und git-lfs hochladen. Demnächst zeigen wir dir die genauen Schritte, um Modell-Repositories zu erstellenund Dateien hochzuladen. + + +## Hochladen mit der `push_to_hub` API + +{#if fw === 'pt'} + + + +{:else} + + + +{/if} + +Die einfachste Variante, um Dateien auf den Hub hochzuladen, ist mittels der `push_to_hub` API. Bevor du weitermachst, must du einen Autentifizierungstoken generieren, damit die `huggingface_hub` API weißt, wer du bist und auf welche Namespaces du zugreifen darfst. Stell sicher, dass du in einer Umgebung mit `transformers` installiert bist (siehe [Setup](/course/chapter0)). Wenn du auf einem Notebook bist, kannst du diese Funktion benutzen, um dich einzuloggen: + +```python +from huggingface_hub import notebook_login + +notebook_login() +``` + +Im Terminal kannst folgendes ausführen: + +```bash +huggingface-cli login +``` + +In beiden Fällen solltest du nach deinem Username und Passwort gefragt werden. Das sind die selben, mit denen du dich auf dem Hub einloggst. Solltest du noch kein Hub-Profil haben, musst du erstmal eins [hier](https://huggingface.co/join) erstellen. + +Großartig! Nun hast du deinen Autentifizierungstoken in deinem Cache-Ordner gespeichert. Lass uns ein paar Repositories erstellen! + +{#if fw === 'pt'} + +Wenn du schon Modelle mit der `Trainer` API trainiert hast, dann ist der einfachste Weg, um Modelle hochzuladen, das Argument `push_to_hub=True` in `TrainingArguments` einzustellen. + +```py +from transformers import TrainingArguments + +training_args = TrainingArguments( + "bert-finetuned-mrpc", save_strategy="epoch", push_to_hub=True +) +``` + +Wenn du `trainer.train()` aufrufst, lädt der `Trainer` das Modell auf den Hub zu dem Repository in deinem Namespace hoch. Das passiert jedes Mal, wenn das Modell gespeichert wird (in diesem Beispiel jede Epoche). Der Repository wird so benannt werden, wie der Output-Ordner, den du gewählt hast (hier `bert-finetuned-mrpc`). Natürlich kannst du dir aber einen anderen Namen ausdenken und mit `hub_model_id = "a_different_name"` setzen. + +Um dein Modell zu einer Organisation, wovon du Mitglied bist, hochzuladen, kannst du einfach `hub_model_id = "my_organization/my_repo_name"` mit eingeben. + +Wenn das Training durch ist, must du noch einmal `trainer.push_to_hub()` ausführen, um die letzte Version deines Modells hochzuladen. Das wird auch eine Modell-Karte generieren, auf der die relevanten Metadaten mit den benutzten Hyperparametern und Evaluierungsergebnissen! Hier ist ein Beispiel von dem Inhalt, den du auf so einer Modell-Karte finden kannst: + +
+ An example of an auto-generated model card. +
+ +{:else} + +Wenn du für das Modell-Training Keras benutzt, ist der einfachste Weg, um das Modell aud den Hub hochzuladen, den `PushToHubCallback` zu setzen, wenn du `model.fit()` aufrufst. + +```py +from transformers import PushToHubCallback + +callback = PushToHubCallback( + "bert-finetuned-mrpc", save_strategy="epoch", tokenizer=tokenizer +) +``` + +Danach must du noch `callbacks=[callback]` beim `model.fit()` Aufruf setzen. +Der Callback wird das Modell auf den Hub hochladen und zwar zu einem Repository in deinem Namespace. Das passiert jedes Mal, wenn das Modell gespeichert wird (in diesem Beispiel jede Epoche). Der Repository wird so benannt werden, wie der Output-Ordner, den du gewählt hast (hier `bert-finetuned-mrpc`). Natürlich kannst du dir aber einen anderen Namen ausdenken und mit `hub_model_id = "a_different_name"` setzen. + +Um dein Modell zu einer Organisation, wovon du Mitglied bist, hochzuladen, kannst du einfach `hub_model_id = "my_organization/my_repo_name"` mit eingeben. + + +{/if} + +Auf einer tieferen Ebene kann man auf Modelle, Tokenizers und Konfigurationen auf dem Model-Hub direkt zugreifen, indem man die Methode `push_to_hub()` benutzt. +Diese Methode kümmert sich sowohl um das Erstellen vom Repository als auch das Pushen (Hochladen) von Modell- und Tokenizer-Dateien auf den Repository. Also da ist kein manueller Schritt notwendig (im Gegensatz zu den APIs, die wir demnächst sehen werden). + +Um uns eine Vorstellung zu schaffen, wie es funktioniert, lass uns zuerst ein Modell und einen Tokenizer initialisieren: + +{#if fw === 'pt'} +```py +from transformers import AutoModelForMaskedLM, AutoTokenizer + +checkpoint = "camembert-base" + +model = AutoModelForMaskedLM.from_pretrained(checkpoint) +tokenizer = AutoTokenizer.from_pretrained(checkpoint) +``` +{:else} +```py +from transformers import TFAutoModelForMaskedLM, AutoTokenizer + +checkpoint = "camembert-base" + +model = TFAutoModelForMaskedLM.from_pretrained(checkpoint) +tokenizer = AutoTokenizer.from_pretrained(checkpoint) +``` +{/if} + +Dir steht frei, was du mit diesen machst, z.B. Tokens zum Tokenizer hinzuzufügen, das Modell zu trainineren oder zu finetunen. Wenn du mit dem Modell, Gewichten und Tokenizer zufrieden bist, kannst du die Methode `push_to_hub()` vom `model` Objekt benutzten: + +```py +model.push_to_hub("dummy-model") +``` +Das wird den neuen Repository `dummy-model` in deinem Profil erstellen und den mit deinen Model-Dateien befüllen. Mach das gliche mit dem Tokenizer, sodass jetzt alle Dateien in diesem Repository verfügbar sind. + +```py +tokenizer.push_to_hub("dummy-model") +``` +Wenn du Teil einer Organisation bist, kannst du einfach das Argument `organization` mit eingeben, um die Artifakte auf den Namespace dieser Organisation hochzuladen. + +```py +tokenizer.push_to_hub("dummy-model", organization="huggingface") +``` + +Wenn du einen bestimmten Hugging Face Token benutzten möchtest, kannst du ihn auch in der Methode `push_to_hub()` spezifizieren: + +```py +tokenizer.push_to_hub("dummy-model", organization="huggingface", use_auth_token="") +``` + +Nun geh auf den Model Hub, um dein hochgeladenes Modell zu finden: *https://huggingface.co/user-or-organization/dummy-model*. + +Click auf den Tab "Files and versions" und da solltest du die Dateien finden, die auf diesem Screenshot zu sehen sind: + +{#if fw === 'pt'} +
+Dummy model containing both the tokenizer and model files. +
+{:else} +
+Dummy model containing both the tokenizer and model files. +
+{/if} + +> [!TIP] +> ✏️ **Probier das selber aus!** Lade das Modell und den Tokenizer vom Checkpoint `bert-base-cased` mit der Methode `push_to_hub()` hoch. Überprüfe, dass der Repository auf deiner Seite richtig erscheint, bevor du den löschst. + +Wie du schon gesehen hast, akzeptiert die Methode `push_to_hub()` mehrere Argumente. Dies erlaub das Hochladen auf den Namespace eines spezifischen Repositorys oder einer Organisation, sowie die Möglichkeit, einen anderen API Token zu benutzten. Wir empfehlen dir, die Dokumentation der Methode direkt auf [🤗 Transformers documentation](https://huggingface.co/transformers/model_sharing.html) zu lesen, um dir eine Vorstellung zu schaffen, was alles damit möglich ist. + +Die `push_to_hub()` Methode funktioniert im Hintergrund mit der Python Bibliothek [`huggingface_hub`](https://github.com/huggingface/huggingface_hub), die eine direkte API zum Hugging Face Hub anbietet. Sie ist auch drin in der 🤗 Transformers Bibliothek und mehreren anderen Machine Learning Bibliotheken, z.B. [`allenlp`](https://github.com/allenai/allennlp). Obwohl wir in diesem Kapitel den Fokus auf die Integration mit 🤗 Transformers legen, kannst du es in deinen eigenen Code bzw. eigene Bibliothek relativ einfach integrieren. Spring auf den letzten Part, um zu erfahren, wie man Dateien auf einen frisch erstellten Repository hochladen kann! + +## Verwendung der `huggingface_hub` Python Bibliothek +Die `huggingface_hub` Python Bibliothek ist ein Python Packet, das einige Werkzeuge für das Nutzen von Modell- und Datasethub anbietet. Es bietet simple Methoden und Klassen für gängige Aufgaben, z.B. um Information zu Repositories auf dem Hub zu bekommen oder um sie zu Verwalten. Es bietet auch simple auf git basierende APIs, um die Inhalte von solchen Repositories zu verwalten sowie um den Hub in deine Projekte und Bibliotheken zu integrieren. + +Ähnlich wie bei der Verwendung der`push_to_hub` API ist es bei diesen Aktionen erforderlich, dass dein API Token schon in deinem Cache gespeichert ist. Dafür musst du den `login` Befehl aus der CLI ausführen so wie in dem vorherigen Teil erklärt wurde (nochmal: Vergiss nicht, das `!` Zeichen vor die Befehle zu setzen, wenn du im Google Colab arbeitest). + +```bash +huggingface-cli login +``` + +Die `huggingface_hub` Bibliothek bietet mehrere nützliche Methoden und Klassen an. Erstens gibt es einige Methoden, um das Erstellen, Löschen, usw. von Repositories durchzuführen: + + +```python no-format +from huggingface_hub import ( + # User-Management + login, + logout, + whoami, + + # Repository erstellen und managen + create_repo, + delete_repo, + update_repo_visibility, + + # Methoden, um inhaltliche Information abzufragen/abzuändern + list_models, + list_datasets, + list_metrics, + list_repo_files, + upload_file, + delete_file, +) +``` + +Außerdem gibt es die sehr mächtige `Repository` Klasse, um einen lokalen Repository zu managen. Demnächst werden wir uns mit diesen Methoden und dieser Klasse beschäftigen, um zu verstehen, wie man die am besten nutzt. + +Mit der `create_repo` Methode kann ein neuer Repository auf dem Hub erstellt werden: + +```py +from huggingface_hub import create_repo + +create_repo("dummy-model") +``` + +Das erstellt den Repository `dummy-model` unter deinem Namespace. Wenn du möchtest, kannst du auch die Organisation spezifizieren, zu der der Repository gehören sollte, indem du das `organization` Argument setzt: + +```py +from huggingface_hub import create_repo + +create_repo("dummy-model", organization="huggingface") +``` + +Das erstellt den Repository `dummy-model` unter dem `huggingface` Namespace – angenommen du gehörst zu dieser Organisation. +Andere eventuell nützliche Argumente sind: + +- `private`: um zu spezifizieren, ob der Repository für andere sichtbar sein sollte oder nicht. +- `token`: um den Token, der im Zwischenspeicher (Cache) liegt, mit einem neuen Token zu überscheiben. +- `repo_type`: zum Auswählen, ob du einen `dataset` oder einen `space` anstatt von einem Modell kreieren möchtest. Erlaubte Werte sind `"dataset"` und `"space"`. + +Nachdem der Repository erstellt wurde, können wir Dateien hinzufügen! Spring zum nächsten Abschnitt, um drei Varianten dazu zu lernen, wie man das machen kann. + +## Mit der Webinterface + +Die Webinterface bietet Tools an, um Repositories direkt auf dem Hub zu managen. Damit kannst du ganz einfach Repositories erstellen, Dateien hinzufügen (sogar große Dateien), Modelle explorieren, Unterschiede ("diffs") visualisieren und viel mehr. + +Um einen Repository zu erstellen, geh auf [huggingface.co/new](https://huggingface.co/new): + +
+Beispiel vom Modell, mit dem man einen Repository erstellen kann. +
+ +Erstens muss man den Besitzer vom Repository eingeben: Das kannst entweder du selbst oder jede andere Person von der Organisation sein, zu der du gehörst. Wenn du eine Organisation auswählst, wird das Modell auf der Seite der Organisation präsentiert und jedes Mitglied der Organisation wird zu diesem Repository beitragen können. + +Als nächstes gib den Namen deines Modells ein. So wird der Repository auch heißen. Zuletzt kannst du spezifizieren, ob das Modell öffentlich oder privat sein soll. Private Modelle sind von der Öffentlichkeit unsichtbar. + +Nach der Erstellung des Repositorys solltest du so eine Seite sehen können: + +
+Leeres Modell nach der Erstellung des Repositorys. +
+ +Hier wird dein Modell gehostet. Um mit dem Auffüllen zu beginnen, kannst du direkt über die Weboberfläche eine README-Datei hinzufügen. + +
+The README file showing the Markdown capabilities. +
+ +Die README-Datei ist im Markdown Format — du kannst dich damit gerne austoben! +Der dritte Teil dieses Kapitels zielt darauf hin, eine "model card" (Steckbrief) zu bauen. Steckbriefe haben eine entscheidende Relevanz, um dein Modell wertvoll zu machen, denn du kannst dort anderen erzählen, was das Modell kann. + +Wenn du dir den "Files and versions" Tab anschaust, wirst du sehen, dass noch nicht viele Dateien darauf sind – nämlich nur die von dir eben kreierte *README.md* und die *.gitattributes* (wo große Dateien geloggt werden). + + +
+The 'Files and versions' tab only shows the .gitattributes and README.md files. +
+ +Gleich werden wir sehen, wie wir neue Dateien hinzufügen können. + +## Hochladen von Modell-Dateien + +Das System zum Managen der Dateien auf Hugging Face Hub basiert auf git für normale Dateien und auf git-lfs ([Git Large File Storage](https://git-lfs.github.com/)) für größere Dateien. + +Im nächsten Teil schauen wir uns drei Möglichkeitein an, um Dateien mittels `huggingface_hub` und git-Befehle auf den Hub hochzuladen. + +### Die `upload_file` Variante + +Um `upload_file` zu verwenden, muss man nicht unbedingt git und git-lfs installiert haben. Die Funktion lädt Dateien auf den 🤗 Hub mittels HTTP POST Anfragen. Eine Einschränkunf dieser Variante ist, dass man nur mit Dateien unter 5GB groß arbeiten kann. +Wenn deine Dateien größer als 5GB sind, nutz eine von den folgenden zwei Methoden. + +Die API kann folgendermaßen benutzt werden: + +```py +from huggingface_hub import upload_file + +upload_file( + "/config.json", + path_in_repo="config.json", + repo_id="/dummy-model", +) +``` +Das wird die `config.json` Datei in `` auf das Root-Verzeichnis vom Repository als `config.json` vom `dummy-model` Repository. +Andere nützliche Argumente : + +- `token`, um den Token zu überscheiben, der in deinem Cache gespeichert ist +- `repo_type`, wenn du anstatt von einem Modell Dateien auf einen `dataset` oder `space` hochladen möchtest. Valide Werte sind `"dataset"` und `"space"`. + + +### Die `Repository` Klasse + +Die `Repository` Klasse verwaltet einen lokalen Repository so wie git. Sie abstrahiert aber die meisten schwierigen Punkte, auf die man stoßen würde, wenn man eine ähnliche Funktionalität mit git erreichen möchte. + +Diese Klasse braucht git und git-lfs im System schon installiert. Also stell sicher, dass du git-lfs installiert hast (siehe [hier](https://git-lfs.github.com/) für Installationsanweisungen) und richte alles ein, bevor du loslegst. + +Um mit dem Repository rumspielen zu starten, können wir den in einem lokalen Ordner initialisieren, in dem wir den Remote-Repository klonen: + +```py +from huggingface_hub import Repository + +repo = Repository("", clone_from="/dummy-model") +``` + +Das hat den Ordner `` in unserem Arbeitsverzeichnis erstellt. Dieser Ordner enthält bisher nur die `.gitattributes` Datel, da diese die einzige Datei ist, die wir mit `create_repo` kreiert haben. + +Ab jetzt können mehrere gängige Methoden benutzten: + +```py +repo.git_pull() +repo.git_add() +repo.git_commit() +repo.git_push() +repo.git_tag() +``` + +Und andere Optionen auch! Wir empfehlen, dass du dir die Dokumentation zu `Repository`, die dir [hier](https://github.com/huggingface/huggingface_hub/tree/main/src/huggingface_hub#advanced-programmatic-repository-management) zur Verfügung steht, anschaust, um dir eine Übersicht aller verfügbaren Methoden zu verschaffen. + +Bisher haben wir ein Modell und einen Tokenizer, die wir gerne auf den Hub pushen würden. Wir haben auch den Repository geklont, sodass wir die Dateien in dem Repository speichern können. + +Zuerst stellen wir sicher, dass unser lokaler Repository einen aktuellen Stand hat, in dem wir die letzten Änderungen pullen: + +```py +repo.git_pull() +``` + +Wenn das durch ist, speichern wir die Dateien vom Modell und Tokenizer: + +```py +model.save_pretrained("") +tokenizer.save_pretrained("") +``` + +Der Pfad `` beinhaltet jetzt alle Modell- und Tokenizerdateien. Wir folgen dem gängigen Git-Workflow, indem wir die Dateien in die "staging area" bringen, wir committen und pushen sie auf den hub: + +```py +repo.git_add() +repo.git_commit("Add model and tokenizer files") +repo.git_push() +``` + +Glückwunsch! Du hast gerade deine ersten Dateien auf den Hub hochgeladen. + +### Die git-basierte Variante + +Das ist der einfachste Weg zum Hochladen von Dateien: Wir werden es direkt mit git und git-lfs tun. Der Größtenteil der Schwierigkeit wird durch die früheren Ansätze abstrahiert, aber es gibt ein paar Vorbehalte bei der folgenden Methode, deswegen werden wir einem komplexeren Anwendungsfall folgen. + +Um diese Klasse zu benutzten, mussen wir git und git-lfs installiert haben. Also stell sicher, dass du [git-lfs](https://git-lfs.github.com/) installiert und aufgesetzt hast, bevor du beginst. + +Zuerst initialisiere git-lfs: + +```bash +git lfs install +``` + +```bash +Updated git hooks. +Git LFS initialized. +``` + +Danach musst du den Modell-Repository klonen: + +```bash +git clone https://huggingface.co// +``` + +Mein Username ist `lysandre` und ich habe den Modellnamen `dummy` benutzt. Also bei bei sieht der Befehl so aus: + +``` +git clone https://huggingface.co/lysandre/dummy +``` + +Ich habe jetzt einen Ordner namens *dummy* in meinem Arbeitsverzeichnis. Ich kann jetzt `cd` in den Ordner und mir den Inhalt anschauen: + +```bash +cd dummy && ls +``` + +```bash +README.md +``` + +Wenn du eben einen Repository mit der Hugging Face Hubs Methode `create_repo` erstellt hast, dann sollte dieser Ordner nur eine versteckte `.gitattributes` Datei enthalten. Wenn du es nach den Anweisungen in dem vorherigen Abschnitt mittels der Webinterface gemacht hast, dann sollte der Ordner eine einzige README.md Datei neben der `.gitattributes` enthalten – so wie hier angezeigt wird. + +Das Hinzufügen einer Datei mit normaler Größe, z.B. Konfiguration- oder Vokabulardatei, wird so gemach wie in einem git-basierten System. Aber größere Dateien müssen mit git-lfs registriert werden, um sie zu *huggingface.co* zu pushen. + +Lass uns kurz zurück zu Python, um ein Modell und einen Tokenizer zu generieren, die wir zu unserem dummy repository committen möchten: + +{#if fw === 'pt'} +```py +from transformers import AutoModelForMaskedLM, AutoTokenizer + +checkpoint = "camembert-base" + +model = AutoModelForMaskedLM.from_pretrained(checkpoint) +tokenizer = AutoTokenizer.from_pretrained(checkpoint) + +# Mach was du möchtest mit dem Modell, z.B. trainieren, fine-tunen. + +model.save_pretrained("") +tokenizer.save_pretrained("") +``` +{:else} +```py +from transformers import TFAutoModelForMaskedLM, AutoTokenizer + +checkpoint = "camembert-base" + +model = TFAutoModelForMaskedLM.from_pretrained(checkpoint) +tokenizer = AutoTokenizer.from_pretrained(checkpoint) + +# Mach was du möchtest mit dem Modell, z.B. trainieren, fine-tunen. + +model.save_pretrained("") +tokenizer.save_pretrained("") +``` +{/if} + +Jetzt haben wir die Modell- und Tokenizer-Artifakte gespeichert und können wir uns nochmal den *dummy* Ordner anschauen: + +```bash +ls +``` + +{#if fw === 'pt'} +```bash +config.json pytorch_model.bin README.md sentencepiece.bpe.model special_tokens_map.json tokenizer_config.json tokenizer.json +``` + +Wenn du dir die Dateigrößen anschaust (z.B. mit `ls -lh`), solltest du sehen, dass die Modell-Statedict Datei (*pytorch_model.bin*) der einzige Ausreißer ist mit über 400 MB. + +{:else} +```bash +config.json README.md sentencepiece.bpe.model special_tokens_map.json tf_model.h5 tokenizer_config.json tokenizer.json +``` + +Wenn du dir die Dateigrößen anschaust (z.B. mit `ls -lh`), solltest du sehen, dass die Modell-Statedict Datei (*t5_model.h5*) der einzige Ausreißer ist mit über 400 MB. + +{/if} + +> [!TIP] +> ✏️ Wenn ein Repository mittels der Webinterface kreiert wird, wird die *.gitattributes* Datei automatisch gesetzt, um bestimmte Dateiendungen wie *.bin* und *.h5* als große Dateien zu betrachten, sodass git-lfs sie tracken kann, ohne dass du weiteres konfigurieren musst. + +Nun können wir weitermachen und so arbeiten wie wir es mit normalen Git Repositories machen. Wir können die Dateien stagen mit dem Git-Befehl `git add`: + +```bash +git add . +``` + +Jetzt schauen wir, welche Dateien gestaged wurden: + +```bash +git status +``` + +{#if fw === 'pt'} +```bash +On branch main +Your branch is up to date with 'origin/main'. + +Changes to be committed: + (use "git restore --staged ..." to unstage) + modified: .gitattributes + new file: config.json + new file: pytorch_model.bin + new file: sentencepiece.bpe.model + new file: special_tokens_map.json + new file: tokenizer.json + new file: tokenizer_config.json +``` +{:else} +```bash +On branch main +Your branch is up to date with 'origin/main'. + +Changes to be committed: + (use "git restore --staged ..." to unstage) + modified: .gitattributes + new file: config.json + new file: sentencepiece.bpe.model + new file: special_tokens_map.json + new file: tf_model.h5 + new file: tokenizer.json + new file: tokenizer_config.json +``` +{/if} + +Ähnlicherweise können wir sicherstellen, dass git-lfs die richtigen Dateien trackt mit dem `status` Befehl: + +```bash +git lfs status +``` + +{#if fw === 'pt'} +```bash +On branch main +Objects to be pushed to origin/main: + + +Objects to be committed: + + config.json (Git: bc20ff2) + pytorch_model.bin (LFS: 35686c2) + sentencepiece.bpe.model (LFS: 988bc5a) + special_tokens_map.json (Git: cb23931) + tokenizer.json (Git: 851ff3e) + tokenizer_config.json (Git: f0f7783) + +Objects not staged for commit: + + +``` + +Da sehen wir, dass alle Dateien `Git` als Handler haben. Nur die *pytorch_model.bin* und *sentencepiece.bpe.model* Dateien haben `LFS`. Toll! + +{:else} +```bash +On branch main +Objects to be pushed to origin/main: + + +Objects to be committed: + + config.json (Git: bc20ff2) + sentencepiece.bpe.model (LFS: 988bc5a) + special_tokens_map.json (Git: cb23931) + tf_model.h5 (LFS: 86fce29) + tokenizer.json (Git: 851ff3e) + tokenizer_config.json (Git: f0f7783) + +Objects not staged for commit: + + +``` + +Da sehen wir, dass alle Dateien `Git` als Handler haben. Nur die *t5_model.h5* hat `LFS`. Sehr gut! + +{/if} + +Lass uns mit den letzten Schritten weitermachen, indem wir die Änderungen commiten und zum *huggingface.co* Remote-Repository pushen: + +```bash +git commit -m "First model version" +``` + +{#if fw === 'pt'} +```bash +[main b08aab1] First model version + 7 files changed, 29027 insertions(+) + 6 files changed, 36 insertions(+) + create mode 100644 config.json + create mode 100644 pytorch_model.bin + create mode 100644 sentencepiece.bpe.model + create mode 100644 special_tokens_map.json + create mode 100644 tokenizer.json + create mode 100644 tokenizer_config.json +``` +{:else} +```bash +[main b08aab1] First model version + 6 files changed, 36 insertions(+) + create mode 100644 config.json + create mode 100644 sentencepiece.bpe.model + create mode 100644 special_tokens_map.json + create mode 100644 tf_model.h5 + create mode 100644 tokenizer.json + create mode 100644 tokenizer_config.json +``` +{/if} + +Das Pushen kann ein bisschen dauern, je nach dem wie schnell deine Internetverbindung ist und wie groß deine Dateien sind: + +```bash +git push +``` + +```bash +Uploading LFS objects: 100% (1/1), 433 MB | 1.3 MB/s, done. +Enumerating objects: 11, done. +Counting objects: 100% (11/11), done. +Delta compression using up to 12 threads +Compressing objects: 100% (9/9), done. +Writing objects: 100% (9/9), 288.27 KiB | 6.27 MiB/s, done. +Total 9 (delta 1), reused 0 (delta 0), pack-reused 0 +To https://huggingface.co/lysandre/dummy + 891b41d..b08aab1 main -> main +``` + +{#if fw === 'pt'} +Wenn alles durch ist, können wir uns den Repository anschauen und die eben hinzugefügten Dateien finden: + +
+The 'Files and versions' tab now contains all the recently uploaded files. +
+ +Mit der UI kannst du die Modell-Dateien und die Commits explorieren, um die Differenz bei jedem Commit zu sehen: + +
+The diff introduced by the recent commit. +
+{:else} + +Wenn alles durch ist, können wir uns den Repository anschauen und die eben hinzugefügten Dateien finden: + +
+The 'Files and versions' tab now contains all the recently uploaded files. +
+ +Mit der UI kannst du die Modell-Dateien und die Commits explorieren, um die Differenz bei jedem Commit zu sehen: + +
+The diff introduced by the recent commit. +
+{/if} diff --git a/chapters/de/chapter4/4.mdx b/chapters/de/chapter4/4.mdx index 1689f5ade..8cd0a65eb 100644 --- a/chapters/de/chapter4/4.mdx +++ b/chapters/de/chapter4/4.mdx @@ -1,91 +1,91 @@ -# Erstellung einer Modellkarte ("model card") - - - -Die Modellkarte (Steckbrief) ist eine Datei, die wahrscheinlich genauso wichtig wie das Modell und der Tokenizer in dem Modell-Repository ist. -Da liegt die zentrale Definition vom Modell und sie trägt dazu bei, dass andere Menschen der Community das wiederverwenden und die Ergebnisse reproduzieren können – also das ist die Basis, auf der Andere ihre Artifakte bauen können. - -Die Dokumentation zum Modell- Training und Evaluierung hilft anderen Nutzer:innen zu verstehen, was sie vom Modell erwarten sollten. -Ausreichende Information zu der Vor- und Nachaufarbeitung der Daten dient auch dazu, dass man die Einschränkungen, Biases und den Kontext identifizieren kann, wann das Modell nützlich ist und wann nicht. - -Deswegen ist die Erstellung einer klar definierten Modellkarte ein sehr wichtiger Schritt. Hier geben wir ein Paar Hinweise, die dir dabei helfen könnten. Die Modellkarte wird durch eine *README.md* Datei (eine Markdown Datei) kreiert, die du schonmal gesehen hast. - -Das Konzept von Modellkarte ("model card") stammt aus einer Forschungsrichtung bei Google, die zuerst in dem Paper ["Model Cards for Model Reporting"](https://arxiv.org/abs/1810.03993) von Margaret Mitchell et al erschien. Vieles von dem, was hier steht, basiert auf dem Paper und wir empfehlen dir, das Paper zu lesen, um besser zu verstehen, warum Modellkarten so wichtig sind, wenn man Wert auf Reproduzierbarkeit, Wiederverwendbarkeit und Fairness legt. - -Eine Modellkarte fängt mit einer kurzen, große Übersicht davon, was das Modell kann plus einige Details in den folgenden Abschnitte: - -- Modell-Beschreibung -- Beabsichtigte Nutzung und Einschränkungen -- Modell-Bedienung -- Einschränkungen und Bias -- Trainingsdaten -- Trainingsverfahren -- Evaluierungsergebnisse - -Lass uns anschauen, was genau in jedem Abschnitt stehen sollte. - -### Modell-Beschreibung - -Die Modellbeschreibung enthält grundlegende Details zum Modell. Dazu gehören die Architektur, die Version, ob es in einem Paper vorgestellt wurde, ob eine Originalimplementierung verfügbar ist, der Autor und allgemeine Informationen über das Modell. Eventuelle Urheberrechte sind hier anzugeben. In diesem Abschnitt können auch allgemeine Informationen zu Trainingsverfahren, Parametern und wichtigen Haftungsausschlüssen erwähnt werden. - -### Verwendungszweck und Einschränkungen - -Hier beschreibst du die angedachten Anwendungsfälle fürs Modell, einschließlich der Sprachen, Felder und Domänen, in denen es angewendet werden kann. In diesem Abschnitt der Modellkarte können auch Bereiche dokumentiert werden, die bekanntermaßen außerhalb des Anwendungsbereichs des Modells liegen oder in denen die Leistung wahrscheinlich nicht optimal ist. - -### Modell-Bedienung - -Dieser Abschnitt sollte einige Beispiele für die Verwendung des Modells enthalten. Dies kann die Verwendung der Funktion `pipeline()`, die Verwendung der Modell- und Tokenizer-Klassen und jeden anderen Code zeigen, der deiner Meinung nach hilfreich sein könnte. - - -### Trainingsdaten - -In diesem Teil sollte angegeben werden, auf welchen Datensatz bzw. Datensätze das Modell trainiert wurde. Eine kurze Beschreibung des Datensatzes/der Datensätze ist ebenfalls willkommen. - -### Trainingsverfahren - -In diesem Abschnitt solltest du alle relevanten Aspekte des Modelltrainingsverfahren beschreiben, die für die Reproduzierbarkeit nützlich sind. Dazu gehören alle Vor- und Nachbearbeitungen, die an den Daten durchgeführt wurden, sowie Details wie die Anzahl der Trainingsepochene, Batch-Größe, die Lernrate usw. - -### Variablen und Metriken - -Hier solltest du die Bewertungsmetriken beschreiben und die verschiedenen Faktoren, die du dabei mit berücksichtigst. Durch die Angabe, welche Metrik(en) verwendet wurden, für welchen Datensatz und welche Datensatzaufteilung, kannst du die Leistung deines Modells leicht mit der anderer Modelle vergleichen. Diese sollten durch die vorherigen Abschnitte informiert werden, wie z. B. die beabsichtigten Benutzer und Anwendungsfälle. - -### Evaluierungsergebnisse - -Abschließend gibst du an, wie gut das Modell mit dem Bewertungsdatensatz abschneidet. Wenn das Modell einen Entscheidungsschwellenwert verwendet, gib entweder den in der Bewertung verwendeten Entscheidungsschwellenwert an oder mach Angaben zur Bewertung bei verschiedenen Schwellenwerten für die beabsichtigten Verwendungszwecke. - -## Beispiel - -Im Folgenden findest du einige Beispiele von guten Modellkarten: - -- [`bert-base-cased`](https://huggingface.co/bert-base-cased) -- [`gpt2`](https://huggingface.co/gpt2) -- [`distilbert`](https://huggingface.co/distilbert-base-uncased) - - -Mehr Beispiele von verschiedene Organisationen/Firmen sind hier verfügbar [here](https://github.com/huggingface/model_card/blob/master/examples.md). - -## Hinweis - -Modellkarten sind bei der Veröffentlichung von Modellen nicht erforderlich und du musst bei der Erstellung nicht alle oben beschriebenen Abschnitte einbeziehen. Allerdings kann eine explizite Dokumentation des Modells künftigen Nutzern nur nützen, daher empfehlen wir dir, so viele Abschnitte wie möglich nach bestem Wissen und Gewissen auszufüllen. - -## Modellkarte-Metadaten - -Wenn du den Hugging Face Hub ein wenig erkundet hast, solltest du gesehen haben, dass einige Modelle zu bestimmten Kategorien gehören: Du kannst sie nach Aufgaben, Sprachen, Bibliotheken und mehr filtern. Die Kategorien, zu denen ein Modell gehört, werden anhand der Metadaten identifiziert, die du im Kopf der Modellkarte hinzufügst. - -Zum Beispiel sieh dir dieses an [`camembert-base` model card](https://huggingface.co/camembert-base/blob/main/README.md). Du solltest folgende Zeilen auf der Modellkarte sehen: - -``` ---- -language: fr -license: mit -datasets: -- oscar ---- -``` - -Diese Metadaten werden vom Hugging Face Hub analysiert, der dieses Modell dann als französisches Modell mit einer MIT-Lizenz identifiziert, das auf dem Oscar-Datensatz trainiert wurde. - -Die vollständige [Modellkarte](https://github.com/huggingface/hub-docs/blame/main/modelcard.md) ermöglicht die Angabe von Sprachen, Lizenzen, Tags, Datensätzen, Metriken sowie den Bewertungsergebnissen, die das Modell wann erhalten hat Ausbildung. +# Erstellung einer Modellkarte ("model card") + + + +Die Modellkarte (Steckbrief) ist eine Datei, die wahrscheinlich genauso wichtig wie das Modell und der Tokenizer in dem Modell-Repository ist. +Da liegt die zentrale Definition vom Modell und sie trägt dazu bei, dass andere Menschen der Community das wiederverwenden und die Ergebnisse reproduzieren können – also das ist die Basis, auf der Andere ihre Artifakte bauen können. + +Die Dokumentation zum Modell- Training und Evaluierung hilft anderen Nutzer:innen zu verstehen, was sie vom Modell erwarten sollten. +Ausreichende Information zu der Vor- und Nachaufarbeitung der Daten dient auch dazu, dass man die Einschränkungen, Biases und den Kontext identifizieren kann, wann das Modell nützlich ist und wann nicht. + +Deswegen ist die Erstellung einer klar definierten Modellkarte ein sehr wichtiger Schritt. Hier geben wir ein Paar Hinweise, die dir dabei helfen könnten. Die Modellkarte wird durch eine *README.md* Datei (eine Markdown Datei) kreiert, die du schonmal gesehen hast. + +Das Konzept von Modellkarte ("model card") stammt aus einer Forschungsrichtung bei Google, die zuerst in dem Paper ["Model Cards for Model Reporting"](https://arxiv.org/abs/1810.03993) von Margaret Mitchell et al erschien. Vieles von dem, was hier steht, basiert auf dem Paper und wir empfehlen dir, das Paper zu lesen, um besser zu verstehen, warum Modellkarten so wichtig sind, wenn man Wert auf Reproduzierbarkeit, Wiederverwendbarkeit und Fairness legt. + +Eine Modellkarte fängt mit einer kurzen, große Übersicht davon, was das Modell kann plus einige Details in den folgenden Abschnitte: + +- Modell-Beschreibung +- Beabsichtigte Nutzung und Einschränkungen +- Modell-Bedienung +- Einschränkungen und Bias +- Trainingsdaten +- Trainingsverfahren +- Evaluierungsergebnisse + +Lass uns anschauen, was genau in jedem Abschnitt stehen sollte. + +### Modell-Beschreibung + +Die Modellbeschreibung enthält grundlegende Details zum Modell. Dazu gehören die Architektur, die Version, ob es in einem Paper vorgestellt wurde, ob eine Originalimplementierung verfügbar ist, der Autor und allgemeine Informationen über das Modell. Eventuelle Urheberrechte sind hier anzugeben. In diesem Abschnitt können auch allgemeine Informationen zu Trainingsverfahren, Parametern und wichtigen Haftungsausschlüssen erwähnt werden. + +### Verwendungszweck und Einschränkungen + +Hier beschreibst du die angedachten Anwendungsfälle fürs Modell, einschließlich der Sprachen, Felder und Domänen, in denen es angewendet werden kann. In diesem Abschnitt der Modellkarte können auch Bereiche dokumentiert werden, die bekanntermaßen außerhalb des Anwendungsbereichs des Modells liegen oder in denen die Leistung wahrscheinlich nicht optimal ist. + +### Modell-Bedienung + +Dieser Abschnitt sollte einige Beispiele für die Verwendung des Modells enthalten. Dies kann die Verwendung der Funktion `pipeline()`, die Verwendung der Modell- und Tokenizer-Klassen und jeden anderen Code zeigen, der deiner Meinung nach hilfreich sein könnte. + + +### Trainingsdaten + +In diesem Teil sollte angegeben werden, auf welchen Datensatz bzw. Datensätze das Modell trainiert wurde. Eine kurze Beschreibung des Datensatzes/der Datensätze ist ebenfalls willkommen. + +### Trainingsverfahren + +In diesem Abschnitt solltest du alle relevanten Aspekte des Modelltrainingsverfahren beschreiben, die für die Reproduzierbarkeit nützlich sind. Dazu gehören alle Vor- und Nachbearbeitungen, die an den Daten durchgeführt wurden, sowie Details wie die Anzahl der Trainingsepochene, Batch-Größe, die Lernrate usw. + +### Variablen und Metriken + +Hier solltest du die Bewertungsmetriken beschreiben und die verschiedenen Faktoren, die du dabei mit berücksichtigst. Durch die Angabe, welche Metrik(en) verwendet wurden, für welchen Datensatz und welche Datensatzaufteilung, kannst du die Leistung deines Modells leicht mit der anderer Modelle vergleichen. Diese sollten durch die vorherigen Abschnitte informiert werden, wie z. B. die beabsichtigten Benutzer und Anwendungsfälle. + +### Evaluierungsergebnisse + +Abschließend gibst du an, wie gut das Modell mit dem Bewertungsdatensatz abschneidet. Wenn das Modell einen Entscheidungsschwellenwert verwendet, gib entweder den in der Bewertung verwendeten Entscheidungsschwellenwert an oder mach Angaben zur Bewertung bei verschiedenen Schwellenwerten für die beabsichtigten Verwendungszwecke. + +## Beispiel + +Im Folgenden findest du einige Beispiele von guten Modellkarten: + +- [`bert-base-cased`](https://huggingface.co/bert-base-cased) +- [`gpt2`](https://huggingface.co/gpt2) +- [`distilbert`](https://huggingface.co/distilbert-base-uncased) + + +Mehr Beispiele von verschiedene Organisationen/Firmen sind hier verfügbar [here](https://github.com/huggingface/model_card/blob/master/examples.md). + +## Hinweis + +Modellkarten sind bei der Veröffentlichung von Modellen nicht erforderlich und du musst bei der Erstellung nicht alle oben beschriebenen Abschnitte einbeziehen. Allerdings kann eine explizite Dokumentation des Modells künftigen Nutzern nur nützen, daher empfehlen wir dir, so viele Abschnitte wie möglich nach bestem Wissen und Gewissen auszufüllen. + +## Modellkarte-Metadaten + +Wenn du den Hugging Face Hub ein wenig erkundet hast, solltest du gesehen haben, dass einige Modelle zu bestimmten Kategorien gehören: Du kannst sie nach Aufgaben, Sprachen, Bibliotheken und mehr filtern. Die Kategorien, zu denen ein Modell gehört, werden anhand der Metadaten identifiziert, die du im Kopf der Modellkarte hinzufügst. + +Zum Beispiel sieh dir dieses an [`camembert-base` model card](https://huggingface.co/camembert-base/blob/main/README.md). Du solltest folgende Zeilen auf der Modellkarte sehen: + +``` +--- +language: fr +license: mit +datasets: +- oscar +--- +``` + +Diese Metadaten werden vom Hugging Face Hub analysiert, der dieses Modell dann als französisches Modell mit einer MIT-Lizenz identifiziert, das auf dem Oscar-Datensatz trainiert wurde. + +Die vollständige [Modellkarte](https://github.com/huggingface/hub-docs/blame/main/modelcard.md) ermöglicht die Angabe von Sprachen, Lizenzen, Tags, Datensätzen, Metriken sowie den Bewertungsergebnissen, die das Modell wann erhalten hat Ausbildung. diff --git a/chapters/de/chapter4/5.mdx b/chapters/de/chapter4/5.mdx index 65eac0fa9..e1feb9b6d 100644 --- a/chapters/de/chapter4/5.mdx +++ b/chapters/de/chapter4/5.mdx @@ -1,12 +1,12 @@ -# Teil 1 abgeschlossen! - - - -Dies ist das Ende des ersten Teils des Kurses! Teil 2 wird am 15. November mit einem großen Community-Event veröffentlicht, weitere Informationen findest du [hier](https://huggingface.co/blog/course-launch-event). - -Du solltest nun in der Lage sein, ein vorab trainiertes Modell für ein Textklassifizierungsproblem (einzelne Sätze oder Satzpaare) zu optimieren und das Ergebnis in den Model Hub hochzuladen. Um sicherzustellen, dass du diesen ersten Abschnitt beherrschst, solltest du genau das an einem Problem verwenden, das dich interessiert (und nicht unbedingt auf Englisch, wenn Sie eine andere Sprache sprechen)! Hilfe findest du in den [Hugging Face-Foren](https://discuss.huggingface.co/) und du kannst dein Projekt in [diesem Thema](https://discuss.huggingface.co/t/share-your-projects) teilen /6803), sobald du damit fertig bist. - -Wir freuen uns darauf, zu sehen, was du alles damit baust! +# Teil 1 abgeschlossen! + + + +Dies ist das Ende des ersten Teils des Kurses! Teil 2 wird am 15. November mit einem großen Community-Event veröffentlicht, weitere Informationen findest du [hier](https://huggingface.co/blog/course-launch-event). + +Du solltest nun in der Lage sein, ein vorab trainiertes Modell für ein Textklassifizierungsproblem (einzelne Sätze oder Satzpaare) zu optimieren und das Ergebnis in den Model Hub hochzuladen. Um sicherzustellen, dass du diesen ersten Abschnitt beherrschst, solltest du genau das an einem Problem verwenden, das dich interessiert (und nicht unbedingt auf Englisch, wenn Sie eine andere Sprache sprechen)! Hilfe findest du in den [Hugging Face-Foren](https://discuss.huggingface.co/) und du kannst dein Projekt in [diesem Thema](https://discuss.huggingface.co/t/share-your-projects) teilen /6803), sobald du damit fertig bist. + +Wir freuen uns darauf, zu sehen, was du alles damit baust! diff --git a/chapters/de/chapter4/6.mdx b/chapters/de/chapter4/6.mdx index cc87f7cb3..4577653d9 100644 --- a/chapters/de/chapter4/6.mdx +++ b/chapters/de/chapter4/6.mdx @@ -1,231 +1,231 @@ - - - - -# Quiz am Ende des Kapitels - - - -Lass uns testen, was du im vorheringen Kapitel gelernt hast! - -### 1. Auf welche Modelle sind die Hub-Modelle beschränkt? - - - -### 2. Wie kannst du die Modelle auf dem Hub verwalten? - -git-lfs benutzen.", - correct: true - } - ]} -/> - -### 3. Was kannst du mit der Hugging Face Hub-Weboberfläche tun? - - - -### 4. Was ist eine Modellkarte? - - - -### 5. Welche dieser Objekte der 🤗 Transformers-Bibliothek können mit `push_to_hub()` direkt auf dem Hub geteilt werden? - -{#if fw === 'pt'} -push_to_hub, und wenn su sie verwendest, werden alle Tokenizer-Dateien (Vokabular, Architektur des Tokenizers usw.) in ein bestimmtes Repo verschoben. Aber das ist nicht die einzig richtige Antwort!", - correct: true - }, - { - text: "Eine Modell-Konfiguration", - explain: "Richtig! Alle Modellkonfigurationen verfügen über die Methode push_to_hub, und wenn Sie sie verwenden, werden sie an ein bestimmtes Repo gepusht. Was kannst du sonst noch teilen?", - correct: true - }, - { - text: "Ein Model", - explain: "Richtig! Alle Modelle verfügen über die Methode push_to_hub, und wenn du sie verwendest, werden sie und ihre Konfigurationsdateien in ein bestimmtes Repo gepusht. Das ist jedoch nicht alles, was du teilen kannst.", - correct: true - }, - { - text: "Ein Trainer", - explain: "Das ist richtig – der Trainer implementiert auch die Methode push_to_hub und lädt mit dieser Methode das Modell, seine Konfiguration, den Tokenizer und einen Modellkartenentwurf auf einen gegebenen Server hoch repo. Versuch es auch mit einer anderen Antwort!", - correct: true - } - ]} -/> -{:else} -push_to_hub method, and using it will push all the tokenizer files (vocabulary, architecture of the tokenizer, etc.) to a given repo. That's not the only right answer, though!", - explain: "Richtig! Alle Tokenizer verfügen über die Methode push_to_hub, und wenn du sie verwendest, werden alle Tokenizer-Dateien (Vokabular, Architektur des Tokenizers usw.) in ein bestimmtes Repo verschoben. Das ist aber nicht die einzige richtige Antwort!", - correct: true - }, - { - text: "Eine Modell-Konfiguration", - explain: "Right! All model configurations have the push_to_hub method, and using it will push them to a given repo. What else can you share?", - explain: "Richtig! Alle Modellkonfigurationen verfügen über die Methode push_to_hub, und wenn du sie verwendest, werden sie an ein bestimmtes Repo gepusht. Was kannst du sonst noch teilen?", - correct: true - }, - { - text: "Ein Modell", - explain: "Richtig! Alle Modelle verfügen über die Methode push_to_hub, und wenn du sie verwendest, werden sie und ihre Konfigurationsdateien in ein bestimmtes Repo gepusht. Das ist jedoch nicht alles, was du teilen kannst.", - correct: true - }, - { - text: "Alles oben mit einem speziellen `Callback`", - explain: "Das ist richtig – der PushToHubCallback sendet während des Trainings regelmäßig alle diese Objekte an ein Repo.", - correct: true - } - ]} -/> -{/if} - -### 6. Was ist der erste Schritt bei Verwendung der Methode `push_to_hub()` oder der CLI-Tools? - - - -### 7. Du verwendest ein Modell und einen Tokenizer – wie kannst du diese auf den Hub hochladen? - -huggingface_hub-Dienstprogramm einschließt.", - explain: "Modelle und Tokenizer profitieren bereits von den Dienstprogrammen huggingface_hub: kein zusätzlicher Wrapping erforderlich!" - }, - { - text: "Indem du sie auf der Festplatte speicherst und transformers-cli upload-model aufrufst", - explain: "Der Befehl upload-model existiert nicht." - } - ]} -/> - -### 8. Welche Git-Operationen kann man mit der Klasse „Repository“ ausführen? - -git_commit() Methode da.", - correct: true - }, - { - text: "Ein Pull", - explain: "Das ist der Zweck der git_pull() Methode.", - correct: true - }, - { - text: "Ein Push", - explain: "Die Methode git_push() macht das.", - correct: true - }, - { - text: "Ein Merge", - explain: "Nein, die Operation wird mit dieser API nie möglich sein." - } - ]} -/> + + + + +# Quiz am Ende des Kapitels + + + +Lass uns testen, was du im vorheringen Kapitel gelernt hast! + +### 1. Auf welche Modelle sind die Hub-Modelle beschränkt? + + + +### 2. Wie kannst du die Modelle auf dem Hub verwalten? + +git-lfs benutzen.", + correct: true + } + ]} +/> + +### 3. Was kannst du mit der Hugging Face Hub-Weboberfläche tun? + + + +### 4. Was ist eine Modellkarte? + + + +### 5. Welche dieser Objekte der 🤗 Transformers-Bibliothek können mit `push_to_hub()` direkt auf dem Hub geteilt werden? + +{#if fw === 'pt'} +push_to_hub, und wenn su sie verwendest, werden alle Tokenizer-Dateien (Vokabular, Architektur des Tokenizers usw.) in ein bestimmtes Repo verschoben. Aber das ist nicht die einzig richtige Antwort!", + correct: true + }, + { + text: "Eine Modell-Konfiguration", + explain: "Richtig! Alle Modellkonfigurationen verfügen über die Methode push_to_hub, und wenn Sie sie verwenden, werden sie an ein bestimmtes Repo gepusht. Was kannst du sonst noch teilen?", + correct: true + }, + { + text: "Ein Model", + explain: "Richtig! Alle Modelle verfügen über die Methode push_to_hub, und wenn du sie verwendest, werden sie und ihre Konfigurationsdateien in ein bestimmtes Repo gepusht. Das ist jedoch nicht alles, was du teilen kannst.", + correct: true + }, + { + text: "Ein Trainer", + explain: "Das ist richtig – der Trainer implementiert auch die Methode push_to_hub und lädt mit dieser Methode das Modell, seine Konfiguration, den Tokenizer und einen Modellkartenentwurf auf einen gegebenen Server hoch repo. Versuch es auch mit einer anderen Antwort!", + correct: true + } + ]} +/> +{:else} +push_to_hub method, and using it will push all the tokenizer files (vocabulary, architecture of the tokenizer, etc.) to a given repo. That's not the only right answer, though!", + explain: "Richtig! Alle Tokenizer verfügen über die Methode push_to_hub, und wenn du sie verwendest, werden alle Tokenizer-Dateien (Vokabular, Architektur des Tokenizers usw.) in ein bestimmtes Repo verschoben. Das ist aber nicht die einzige richtige Antwort!", + correct: true + }, + { + text: "Eine Modell-Konfiguration", + explain: "Right! All model configurations have the push_to_hub method, and using it will push them to a given repo. What else can you share?", + explain: "Richtig! Alle Modellkonfigurationen verfügen über die Methode push_to_hub, und wenn du sie verwendest, werden sie an ein bestimmtes Repo gepusht. Was kannst du sonst noch teilen?", + correct: true + }, + { + text: "Ein Modell", + explain: "Richtig! Alle Modelle verfügen über die Methode push_to_hub, und wenn du sie verwendest, werden sie und ihre Konfigurationsdateien in ein bestimmtes Repo gepusht. Das ist jedoch nicht alles, was du teilen kannst.", + correct: true + }, + { + text: "Alles oben mit einem speziellen `Callback`", + explain: "Das ist richtig – der PushToHubCallback sendet während des Trainings regelmäßig alle diese Objekte an ein Repo.", + correct: true + } + ]} +/> +{/if} + +### 6. Was ist der erste Schritt bei Verwendung der Methode `push_to_hub()` oder der CLI-Tools? + + + +### 7. Du verwendest ein Modell und einen Tokenizer – wie kannst du diese auf den Hub hochladen? + +huggingface_hub-Dienstprogramm einschließt.", + explain: "Modelle und Tokenizer profitieren bereits von den Dienstprogrammen huggingface_hub: kein zusätzlicher Wrapping erforderlich!" + }, + { + text: "Indem du sie auf der Festplatte speicherst und transformers-cli upload-model aufrufst", + explain: "Der Befehl upload-model existiert nicht." + } + ]} +/> + +### 8. Welche Git-Operationen kann man mit der Klasse „Repository“ ausführen? + +git_commit() Methode da.", + correct: true + }, + { + text: "Ein Pull", + explain: "Das ist der Zweck der git_pull() Methode.", + correct: true + }, + { + text: "Ein Push", + explain: "Die Methode git_push() macht das.", + correct: true + }, + { + text: "Ein Merge", + explain: "Nein, die Operation wird mit dieser API nie möglich sein." + } + ]} +/> diff --git a/chapters/de/glossary/1.mdx b/chapters/de/glossary/1.mdx index 82c7d5fbd..bd3019a41 100644 --- a/chapters/de/glossary/1.mdx +++ b/chapters/de/glossary/1.mdx @@ -1,141 +1,141 @@ -# Wörterverzeichnis - -| Original | Übersetzung | -|---------------------------------|-----------------------------------------| -| Abstraction | Abstraktion | -| Account | Account | -| Accuracy | Genauigkeit | -| Artificial General Intelligence | künstliche allgemeine Intelligenz | -| Attention | Attention | -| Attention mask (layer) | Attention-Mask (Layer) | -| Backward Pass | Rückwärtsalgorithmus berechnen | -| Batch | Batch | -| Bias | Bias (Voreingenommenheit) | -| Causal Language Modeling | kausale Sprachmodellierung | -| Chapter | Kapitel | -| Checkpoint(s) | Checkpoint(s) | -| Class | Klasse | -| Classification | Klassifizierung | -| Code | Code | -| Colab Notebook | Colab Notebook | -| Command | Befehl | -| Computer Vision | Computer Vision | -| Configuration | Konfiguration | -| Course | Kurs | -| Decoder | Decoder | -| Dependency | Abhängigkeitsbeziehung | -| Deployment | Deployment | -| Development | Entwicklung | -| Dictionary | Dictionary | -| Distribution | Verteilung | -| Download | Download | -| Encoder | Encoder | -| Extractive question answering | Extraktives Question Answering | -| F1 score | F1-Maß | -| Feature | Feature | -| Fine-tune | feintunen | -| Fine-tuning | Feintuning | -| Folder | Ordner | -| Forward Pass | Vorwärtsalgorithmus berechnen | -| Function | Funktion | -| Generative question answering | Generatives Question Answering | -| Google | Google | -| Hugging Face | Hugging Face | -| Incompatibility | Inkompatibilität | -| Inference | Inferenz | -| Input | Input | -| Input data | Input-Daten | -| Label (verb) | labeln (gelabelt), annotieren | -| Label (subj) | Label, das / Labels, die (plur.) | -| Layer | Layer (plur. Layer(n)) | -| Library | Bibliothek | -| Linux | Linux | -| Load | laden | -| Loss function | Verlustfunktion | -| Machine Learning | Maschinelles Lernen | -| macOS | macOS | -| Mask | Maskierung | -| Mask Filling | Mask Filling | -| Mask Token | Mask-Token | -| Masked Language Modeling | maskierte Sprachmodellierung | -| Model | Modell | -| Model Hub | Model Hub | -| Module | Modul | -| Named Entities | benannte Entitäten | -| Named Entity Recognition | Eigennamenerkennung | -| Natural Language Processing | Computerlinguistik | -| Output | Output | -| Package | Paket | -| Package Manager | Paketverwaltung | -| Padding | das Padding / auffüllen | -| Parameter | Parameter | -| Postprocessing | Nachverarveitung | -| Preprocessing | Vorverarbeitung | -| Pretraining | Pretraining | -| Pretrained model | vortrainiertes Modell | -| Prompt | Prompt | -| Python | Python | -| Pytorch | Pytorch | -| Question Answering | Question Answering | -| Save | speichern | -| Sample | Sample (auch Stichprobe) | -| Script | Script | -| Self-Contained | in sich abgeschlossen | -| Sentiment analysis | Sentiment-Analyse | -| Sequence-to-sequence models | Sequence-to-Sequence-Modelle | -| Setup | Installation | -| Speech Processing | Verarbeitung gesprochener Sprache | -| Speech Recognition | Spracherkennung | -| Summarization | Automatische Textzusammenfassung | -| Target | Zielvariable / vorherzusagende Variable | -| Task | Aufgabe / Aufgabenstellung | -| TensorFlow | Tensorflow | -| Terminal | Terminal | -| Text generation | Textgenerierung | -| Tokenizer | Tokenizer | -| Train | Training | -| Transfer Learning | Transfer Learning | -| Transformer | Transformer | -| Transformer models | Transformer-Modelle | -| Translation | Maschinelle Übersetzung | -| Virtual Environment | Virtuelle Umgebung | -| Weight | Gewicht | -| Weights | Gewichtung | -| Windows | Windows | -| Working Environment | Arbeitsumgebung | -| Workload | Auslastung | -| Workspace | Workspace | -| Zero-shot classification | Zero-Shot-Klassifizierung | -======= - -## Abkürzungen - -| Original | Übersetzung | -|-----------|-------------| -| NLP | CL | -| API | API | -| GPU | GPU | -| TPU | TPU | -| ML | ML | - -## Notes - -Please refer to [TRANSLATING.txt](/chapters/de/TRANSLATING.txt) for a translation guide. Here are some excerpts relevant to the glossary: - -- Refer and contribute to the glossary frequently to stay on top of the latest - choices we make. This minimizes the amount of editing that is required. - Add new terms alphabetically sorted. - -- The German language accepts English words especially in modern contexts more - than many other languages (i.e. Anglicisms). Check for the correct usage of - terms in computer science and commonly used terms in other publications. - -- Don't translate industry-accepted acronyms. e.g. TPU or GPU. - -- If translating a technical word, keep the choice of German translation consistent. - This does not apply for non-technical choices, as in those cases variety actually - helps keep the text engaging. - -- Be exact when choosing equivalents for technical words. Package is package. - Library is library. Don't mix and match. - +# Wörterverzeichnis + +| Original | Übersetzung | +|---------------------------------|-----------------------------------------| +| Abstraction | Abstraktion | +| Account | Account | +| Accuracy | Genauigkeit | +| Artificial General Intelligence | künstliche allgemeine Intelligenz | +| Attention | Attention | +| Attention mask (layer) | Attention-Mask (Layer) | +| Backward Pass | Rückwärtsalgorithmus berechnen | +| Batch | Batch | +| Bias | Bias (Voreingenommenheit) | +| Causal Language Modeling | kausale Sprachmodellierung | +| Chapter | Kapitel | +| Checkpoint(s) | Checkpoint(s) | +| Class | Klasse | +| Classification | Klassifizierung | +| Code | Code | +| Colab Notebook | Colab Notebook | +| Command | Befehl | +| Computer Vision | Computer Vision | +| Configuration | Konfiguration | +| Course | Kurs | +| Decoder | Decoder | +| Dependency | Abhängigkeitsbeziehung | +| Deployment | Deployment | +| Development | Entwicklung | +| Dictionary | Dictionary | +| Distribution | Verteilung | +| Download | Download | +| Encoder | Encoder | +| Extractive question answering | Extraktives Question Answering | +| F1 score | F1-Maß | +| Feature | Feature | +| Fine-tune | feintunen | +| Fine-tuning | Feintuning | +| Folder | Ordner | +| Forward Pass | Vorwärtsalgorithmus berechnen | +| Function | Funktion | +| Generative question answering | Generatives Question Answering | +| Google | Google | +| Hugging Face | Hugging Face | +| Incompatibility | Inkompatibilität | +| Inference | Inferenz | +| Input | Input | +| Input data | Input-Daten | +| Label (verb) | labeln (gelabelt), annotieren | +| Label (subj) | Label, das / Labels, die (plur.) | +| Layer | Layer (plur. Layer(n)) | +| Library | Bibliothek | +| Linux | Linux | +| Load | laden | +| Loss function | Verlustfunktion | +| Machine Learning | Maschinelles Lernen | +| macOS | macOS | +| Mask | Maskierung | +| Mask Filling | Mask Filling | +| Mask Token | Mask-Token | +| Masked Language Modeling | maskierte Sprachmodellierung | +| Model | Modell | +| Model Hub | Model Hub | +| Module | Modul | +| Named Entities | benannte Entitäten | +| Named Entity Recognition | Eigennamenerkennung | +| Natural Language Processing | Computerlinguistik | +| Output | Output | +| Package | Paket | +| Package Manager | Paketverwaltung | +| Padding | das Padding / auffüllen | +| Parameter | Parameter | +| Postprocessing | Nachverarveitung | +| Preprocessing | Vorverarbeitung | +| Pretraining | Pretraining | +| Pretrained model | vortrainiertes Modell | +| Prompt | Prompt | +| Python | Python | +| Pytorch | Pytorch | +| Question Answering | Question Answering | +| Save | speichern | +| Sample | Sample (auch Stichprobe) | +| Script | Script | +| Self-Contained | in sich abgeschlossen | +| Sentiment analysis | Sentiment-Analyse | +| Sequence-to-sequence models | Sequence-to-Sequence-Modelle | +| Setup | Installation | +| Speech Processing | Verarbeitung gesprochener Sprache | +| Speech Recognition | Spracherkennung | +| Summarization | Automatische Textzusammenfassung | +| Target | Zielvariable / vorherzusagende Variable | +| Task | Aufgabe / Aufgabenstellung | +| TensorFlow | Tensorflow | +| Terminal | Terminal | +| Text generation | Textgenerierung | +| Tokenizer | Tokenizer | +| Train | Training | +| Transfer Learning | Transfer Learning | +| Transformer | Transformer | +| Transformer models | Transformer-Modelle | +| Translation | Maschinelle Übersetzung | +| Virtual Environment | Virtuelle Umgebung | +| Weight | Gewicht | +| Weights | Gewichtung | +| Windows | Windows | +| Working Environment | Arbeitsumgebung | +| Workload | Auslastung | +| Workspace | Workspace | +| Zero-shot classification | Zero-Shot-Klassifizierung | +======= + +## Abkürzungen + +| Original | Übersetzung | +|-----------|-------------| +| NLP | CL | +| API | API | +| GPU | GPU | +| TPU | TPU | +| ML | ML | + +## Notes + +Please refer to [TRANSLATING.txt](/chapters/de/TRANSLATING.txt) for a translation guide. Here are some excerpts relevant to the glossary: + +- Refer and contribute to the glossary frequently to stay on top of the latest + choices we make. This minimizes the amount of editing that is required. + Add new terms alphabetically sorted. + +- The German language accepts English words especially in modern contexts more + than many other languages (i.e. Anglicisms). Check for the correct usage of + terms in computer science and commonly used terms in other publications. + +- Don't translate industry-accepted acronyms. e.g. TPU or GPU. + +- If translating a technical word, keep the choice of German translation consistent. + This does not apply for non-technical choices, as in those cases variety actually + helps keep the text engaging. + +- Be exact when choosing equivalents for technical words. Package is package. + Library is library. Don't mix and match. + diff --git a/chapters/en/_toctree.yml b/chapters/en/_toctree.yml index e7d22597b..9c05907cb 100644 --- a/chapters/en/_toctree.yml +++ b/chapters/en/_toctree.yml @@ -1,264 +1,264 @@ -- title: 0. Setup - sections: - - local: chapter0/1 - title: Introduction - -- title: 1. Transformer models - sections: - - local: chapter1/1 - title: Introduction - - local: chapter1/2 - title: Natural Language Processing and Large Language Models - - local: chapter1/3 - title: Transformers, what can they do? - - local: chapter1/4 - title: How do Transformers work? - - local: chapter1/5 - title: How 🤗 Transformers solve tasks - - local: chapter1/6 - title: Transformer Architectures - - local: chapter1/7 - title: Quick quiz - - local: chapter1/8 - title: Inference with LLMs - - local: chapter1/9 - title: Bias and limitations - - local: chapter1/10 - title: Summary - - local: chapter1/11 - title: Certification exam - quiz: 1 - -- title: 2. Using 🤗 Transformers - sections: - - local: chapter2/1 - title: Introduction - - local: chapter2/2 - title: Behind the pipeline - - local: chapter2/3 - title: Models - - local: chapter2/4 - title: Tokenizers - - local: chapter2/5 - title: Handling multiple sequences - - local: chapter2/6 - title: Putting it all together - - local: chapter2/7 - title: Basic usage completed! - - local: chapter2/8 - title: Optimized Inference Deployment - - local: chapter2/9 - title: End-of-chapter quiz - quiz: 2 - -- title: 3. Fine-tuning a pretrained model - sections: - - local: chapter3/1 - title: Introduction - - local: chapter3/2 - title: Processing the data - - local: chapter3/3 - title: Fine-tuning a model with the Trainer API - - local: chapter3/4 - title: A full training loop - - local: chapter3/5 - title: Understanding Learning Curves - - local: chapter3/6 - title: Fine-tuning, Check! - - local: chapter3/7 - title: End-of-chapter quiz - quiz: 3 - -- title: 4. Sharing models and tokenizers - sections: - - local: chapter4/1 - title: The Hugging Face Hub - - local: chapter4/2 - title: Using pretrained models - - local: chapter4/3 - title: Sharing pretrained models - - local: chapter4/4 - title: Building a model card - - local: chapter4/5 - title: Part 1 completed! - - local: chapter4/6 - title: End-of-chapter quiz - quiz: 4 - -- title: 5. The 🤗 Datasets library - sections: - - local: chapter5/1 - title: Introduction - - local: chapter5/2 - title: What if my dataset isn't on the Hub? - - local: chapter5/3 - title: Time to slice and dice - - local: chapter5/4 - title: Big data? 🤗 Datasets to the rescue! - - local: chapter5/5 - title: Creating your own dataset - - local: chapter5/6 - title: Semantic search with FAISS - - local: chapter5/7 - title: 🤗 Datasets, check! - - local: chapter5/8 - title: End-of-chapter quiz - quiz: 5 - -- title: 6. The 🤗 Tokenizers library - sections: - - local: chapter6/1 - title: Introduction - - local: chapter6/2 - title: Training a new tokenizer from an old one - - local: chapter6/3 - title: Fast tokenizers' special powers - - local: chapter6/3b - title: Fast tokenizers in the QA pipeline - - local: chapter6/4 - title: Normalization and pre-tokenization - - local: chapter6/5 - title: Byte-Pair Encoding tokenization - - local: chapter6/6 - title: WordPiece tokenization - - local: chapter6/7 - title: Unigram tokenization - - local: chapter6/8 - title: Building a tokenizer, block by block - - local: chapter6/9 - title: Tokenizers, check! - - local: chapter6/10 - title: End-of-chapter quiz - quiz: 6 - -- title: 7. Classical NLP tasks - sections: - - local: chapter7/1 - title: Introduction - - local: chapter7/2 - title: Token classification - - local: chapter7/3 - title: Fine-tuning a masked language model - - local: chapter7/4 - title: Translation - - local: chapter7/5 - title: Summarization - - local: chapter7/6 - title: Training a causal language model from scratch - - local: chapter7/7 - title: Question answering - - local: chapter7/8 - title: Mastering LLMs - - local: chapter7/9 - title: End-of-chapter quiz - quiz: 7 - -- title: 8. How to ask for help - sections: - - local: chapter8/1 - title: Introduction - - local: chapter8/2 - title: What to do when you get an error - - local: chapter8/3 - title: Asking for help on the forums - - local: chapter8/4 - title: Debugging the training pipeline - local_fw: { pt: chapter8/4, tf: chapter8/4_tf } - - local: chapter8/5 - title: How to write a good issue - - local: chapter8/6 - title: Part 2 completed! - - local: chapter8/7 - title: End-of-chapter quiz - quiz: 8 - -- title: 9. Building and sharing demos - subtitle: I trained a model, but how can I show it off? - sections: - - local: chapter9/1 - title: Introduction to Gradio - - local: chapter9/2 - title: Building your first demo - - local: chapter9/3 - title: Understanding the Interface class - - local: chapter9/4 - title: Sharing demos with others - - local: chapter9/5 - title: Integrations with the Hugging Face Hub - - local: chapter9/6 - title: Advanced Interface features - - local: chapter9/7 - title: Introduction to Blocks - - local: chapter9/8 - title: Gradio, check! - - local: chapter9/9 - title: End-of-chapter quiz - quiz: 9 - -- title: 10. Curate high-quality datasets - subtitle: How to use Argilla to create amazing datasets - sections: - - local: chapter10/1 - title: Introduction to Argilla - - local: chapter10/2 - title: Set up your Argilla instance - - local: chapter10/3 - title: Load your dataset to Argilla - - local: chapter10/4 - title: Annotate your dataset - - local: chapter10/5 - title: Use your annotated dataset - - local: chapter10/6 - title: Argilla, check! - - local: chapter10/7 - title: End-of-chapter quiz - quiz: 10 - -- title: 11. Fine-tune Large Language Models - subtitle: Use Supervised Fine-tuning and Low-Rank Adaptation to fine-tune a large language model - sections: - - local: chapter11/1 - title: Introduction - - local: chapter11/2 - title: Chat Templates - - local: chapter11/3 - title: Fine-Tuning with SFTTrainer - - local: chapter11/4 - title: LoRA (Low-Rank Adaptation) - - local: chapter11/5 - title: Evaluation - - local: chapter11/6 - title: Conclusion - - local: chapter11/7 - title: Exam Time! - quiz: 11 - -- title: 12. Build Reasoning Models - subtitle: Learn how to build reasoning models like DeepSeek R1 - new: true - sections: - - local: chapter12/1 - title: Introduction - - local: chapter12/2 - title: Reinforcement Learning on LLMs - - local: chapter12/3 - title: The Aha Moment in the DeepSeek R1 Paper - - local: chapter12/3b - title: Advanced Understanding of GRPO in DeepSeekMath - - local: chapter12/4 - title: Implementing GRPO in TRL - - local: chapter12/5 - title: Practical Exercise to Fine-tune a model with GRPO - - local: chapter12/6 - title: Practical Exercise with Unsloth - - local: chapter12/7 - title: Coming soon... - -- title: Course Events - sections: - - local: events/1 - title: Live sessions and workshops - - local: events/2 - title: Part 2 release event - - local: events/3 - title: Gradio Blocks party +- title: 0. Setup + sections: + - local: chapter0/1 + title: Introduction + +- title: 1. Transformer models + sections: + - local: chapter1/1 + title: Introduction + - local: chapter1/2 + title: Natural Language Processing and Large Language Models + - local: chapter1/3 + title: Transformers, what can they do? + - local: chapter1/4 + title: How do Transformers work? + - local: chapter1/5 + title: How 🤗 Transformers solve tasks + - local: chapter1/6 + title: Transformer Architectures + - local: chapter1/7 + title: Quick quiz + - local: chapter1/8 + title: Inference with LLMs + - local: chapter1/9 + title: Bias and limitations + - local: chapter1/10 + title: Summary + - local: chapter1/11 + title: Certification exam + quiz: 1 + +- title: 2. Using 🤗 Transformers + sections: + - local: chapter2/1 + title: Introduction + - local: chapter2/2 + title: Behind the pipeline + - local: chapter2/3 + title: Models + - local: chapter2/4 + title: Tokenizers + - local: chapter2/5 + title: Handling multiple sequences + - local: chapter2/6 + title: Putting it all together + - local: chapter2/7 + title: Basic usage completed! + - local: chapter2/8 + title: Optimized Inference Deployment + - local: chapter2/9 + title: End-of-chapter quiz + quiz: 2 + +- title: 3. Fine-tuning a pretrained model + sections: + - local: chapter3/1 + title: Introduction + - local: chapter3/2 + title: Processing the data + - local: chapter3/3 + title: Fine-tuning a model with the Trainer API + - local: chapter3/4 + title: A full training loop + - local: chapter3/5 + title: Understanding Learning Curves + - local: chapter3/6 + title: Fine-tuning, Check! + - local: chapter3/7 + title: End-of-chapter quiz + quiz: 3 + +- title: 4. Sharing models and tokenizers + sections: + - local: chapter4/1 + title: The Hugging Face Hub + - local: chapter4/2 + title: Using pretrained models + - local: chapter4/3 + title: Sharing pretrained models + - local: chapter4/4 + title: Building a model card + - local: chapter4/5 + title: Part 1 completed! + - local: chapter4/6 + title: End-of-chapter quiz + quiz: 4 + +- title: 5. The 🤗 Datasets library + sections: + - local: chapter5/1 + title: Introduction + - local: chapter5/2 + title: What if my dataset isn't on the Hub? + - local: chapter5/3 + title: Time to slice and dice + - local: chapter5/4 + title: Big data? 🤗 Datasets to the rescue! + - local: chapter5/5 + title: Creating your own dataset + - local: chapter5/6 + title: Semantic search with FAISS + - local: chapter5/7 + title: 🤗 Datasets, check! + - local: chapter5/8 + title: End-of-chapter quiz + quiz: 5 + +- title: 6. The 🤗 Tokenizers library + sections: + - local: chapter6/1 + title: Introduction + - local: chapter6/2 + title: Training a new tokenizer from an old one + - local: chapter6/3 + title: Fast tokenizers' special powers + - local: chapter6/3b + title: Fast tokenizers in the QA pipeline + - local: chapter6/4 + title: Normalization and pre-tokenization + - local: chapter6/5 + title: Byte-Pair Encoding tokenization + - local: chapter6/6 + title: WordPiece tokenization + - local: chapter6/7 + title: Unigram tokenization + - local: chapter6/8 + title: Building a tokenizer, block by block + - local: chapter6/9 + title: Tokenizers, check! + - local: chapter6/10 + title: End-of-chapter quiz + quiz: 6 + +- title: 7. Classical NLP tasks + sections: + - local: chapter7/1 + title: Introduction + - local: chapter7/2 + title: Token classification + - local: chapter7/3 + title: Fine-tuning a masked language model + - local: chapter7/4 + title: Translation + - local: chapter7/5 + title: Summarization + - local: chapter7/6 + title: Training a causal language model from scratch + - local: chapter7/7 + title: Question answering + - local: chapter7/8 + title: Mastering LLMs + - local: chapter7/9 + title: End-of-chapter quiz + quiz: 7 + +- title: 8. How to ask for help + sections: + - local: chapter8/1 + title: Introduction + - local: chapter8/2 + title: What to do when you get an error + - local: chapter8/3 + title: Asking for help on the forums + - local: chapter8/4 + title: Debugging the training pipeline + local_fw: { pt: chapter8/4, tf: chapter8/4_tf } + - local: chapter8/5 + title: How to write a good issue + - local: chapter8/6 + title: Part 2 completed! + - local: chapter8/7 + title: End-of-chapter quiz + quiz: 8 + +- title: 9. Building and sharing demos + subtitle: I trained a model, but how can I show it off? + sections: + - local: chapter9/1 + title: Introduction to Gradio + - local: chapter9/2 + title: Building your first demo + - local: chapter9/3 + title: Understanding the Interface class + - local: chapter9/4 + title: Sharing demos with others + - local: chapter9/5 + title: Integrations with the Hugging Face Hub + - local: chapter9/6 + title: Advanced Interface features + - local: chapter9/7 + title: Introduction to Blocks + - local: chapter9/8 + title: Gradio, check! + - local: chapter9/9 + title: End-of-chapter quiz + quiz: 9 + +- title: 10. Curate high-quality datasets + subtitle: How to use Argilla to create amazing datasets + sections: + - local: chapter10/1 + title: Introduction to Argilla + - local: chapter10/2 + title: Set up your Argilla instance + - local: chapter10/3 + title: Load your dataset to Argilla + - local: chapter10/4 + title: Annotate your dataset + - local: chapter10/5 + title: Use your annotated dataset + - local: chapter10/6 + title: Argilla, check! + - local: chapter10/7 + title: End-of-chapter quiz + quiz: 10 + +- title: 11. Fine-tune Large Language Models + subtitle: Use Supervised Fine-tuning and Low-Rank Adaptation to fine-tune a large language model + sections: + - local: chapter11/1 + title: Introduction + - local: chapter11/2 + title: Chat Templates + - local: chapter11/3 + title: Fine-Tuning with SFTTrainer + - local: chapter11/4 + title: LoRA (Low-Rank Adaptation) + - local: chapter11/5 + title: Evaluation + - local: chapter11/6 + title: Conclusion + - local: chapter11/7 + title: Exam Time! + quiz: 11 + +- title: 12. Build Reasoning Models + subtitle: Learn how to build reasoning models like DeepSeek R1 + new: true + sections: + - local: chapter12/1 + title: Introduction + - local: chapter12/2 + title: Reinforcement Learning on LLMs + - local: chapter12/3 + title: The Aha Moment in the DeepSeek R1 Paper + - local: chapter12/3b + title: Advanced Understanding of GRPO in DeepSeekMath + - local: chapter12/4 + title: Implementing GRPO in TRL + - local: chapter12/5 + title: Practical Exercise to Fine-tune a model with GRPO + - local: chapter12/6 + title: Practical Exercise with Unsloth + - local: chapter12/7 + title: Coming soon... + +- title: Course Events + sections: + - local: events/1 + title: Live sessions and workshops + - local: events/2 + title: Part 2 release event + - local: events/3 + title: Gradio Blocks party diff --git a/chapters/en/chapter0/1.mdx b/chapters/en/chapter0/1.mdx index 40e21bf91..726b0ece8 100644 --- a/chapters/en/chapter0/1.mdx +++ b/chapters/en/chapter0/1.mdx @@ -1,110 +1,110 @@ -# Introduction[[introduction]] - -Welcome to the Hugging Face course! This introduction will guide you through setting up a working environment. If you're just starting the course, we recommend you first take a look at [Chapter 1](/course/chapter1), then come back and set up your environment so you can try the code yourself. - -All the libraries that we'll be using in this course are available as Python packages, so here we'll show you how to set up a Python environment and install the specific libraries you'll need. - -We'll cover two ways of setting up your working environment, using a Colab notebook or a Python virtual environment. Feel free to choose the one that resonates with you the most. For beginners, we strongly recommend that you get started by using a Colab notebook. - -Note that we will not be covering the Windows system. If you're running on Windows, we recommend following along using a Colab notebook. If you're using a Linux distribution or macOS, you can use either approach described here. - -Most of the course relies on you having a Hugging Face account. We recommend creating one now: [create an account](https://huggingface.co/join). - -## Using a Google Colab notebook[[using-a-google-colab-notebook]] - -Using a Colab notebook is the simplest possible setup; boot up a notebook in your browser and get straight to coding! - -If you're not familiar with Colab, we recommend you start by following the [introduction](https://colab.research.google.com/notebooks/intro.ipynb). Colab allows you to use some accelerating hardware, like GPUs or TPUs, and it is free for smaller workloads. - -Once you're comfortable moving around in Colab, create a new notebook and get started with the setup: - -
-An empty colab notebook -
- -The next step is to install the libraries that we'll be using in this course. We'll use `pip` for the installation, which is the package manager for Python. In notebooks, you can run system commands by preceding them with the `!` character, so you can install the 🤗 Transformers library as follows: - -``` -!pip install transformers -``` - -You can make sure the package was correctly installed by importing it within your Python runtime: - -``` -import transformers -``` - -
-A gif showing the result of the two commands above: installation and import -
- -This installs a very light version of 🤗 Transformers. In particular, no specific machine learning frameworks (like PyTorch or TensorFlow) are installed. Since we'll be using a lot of different features of the library, we recommend installing the development version, which comes with all the required dependencies for pretty much any imaginable use case: - -``` -!pip install transformers[sentencepiece] -``` - -This will take a bit of time, but then you'll be ready to go for the rest of the course! - -## Using a Python virtual environment[[using-a-python-virtual-environment]] - -If you prefer to use a Python virtual environment, the first step is to install Python on your system. We recommend following [this guide](https://realpython.com/installing-python/) to get started. - -Once you have Python installed, you should be able to run Python commands in your terminal. You can start by running the following command to ensure that it is correctly installed before proceeding to the next steps: `python --version`. This should print out the Python version now available on your system. - -When running a Python command in your terminal, such as `python --version`, you should think of the program running your command as the "main" Python on your system. We recommend keeping this main installation free of any packages, and using it to create separate environments for each application you work on — this way, each application can have its own dependencies and packages, and you won't need to worry about potential compatibility issues with other applications. - -In Python this is done with [*virtual environments*](https://docs.python.org/3/tutorial/venv.html), which are self-contained directory trees that each contain a Python installation with a particular Python version alongside all the packages the application needs. Creating such a virtual environment can be done with a number of different tools, but we'll use the official Python package for that purpose, which is called [`venv`](https://docs.python.org/3/library/venv.html#module-venv). - -First, create the directory you'd like your application to live in — for example, you might want to make a new directory called *transformers-course* at the root of your home directory: - -``` -mkdir ~/transformers-course -cd ~/transformers-course -``` - -From inside this directory, create a virtual environment using the Python `venv` module: - -``` -python -m venv .env -``` - -You should now have a directory called *.env* in your otherwise empty folder: - -``` -ls -a -``` - -```out -. .. .env -``` - -You can jump in and out of your virtual environment with the `activate` and `deactivate` scripts: - -``` -# Activate the virtual environment -source .env/bin/activate - -# Deactivate the virtual environment -deactivate -``` - -You can make sure that the environment is activated by running the `which python` command: if it points to the virtual environment, then you have successfully activated it! - -``` -which python -``` - -```out -/home//transformers-course/.env/bin/python -``` - -### Installing dependencies[[installing-dependencies]] - -As in the previous section on using Google Colab instances, you'll now need to install the packages required to continue. Again, you can install the development version of 🤗 Transformers using the `pip` package manager: - -``` -pip install "transformers[sentencepiece]" -``` - -You're now all set up and ready to go! +# Introduction[[introduction]] + +Welcome to the Hugging Face course! This introduction will guide you through setting up a working environment. If you're just starting the course, we recommend you first take a look at [Chapter 1](/course/chapter1), then come back and set up your environment so you can try the code yourself. + +All the libraries that we'll be using in this course are available as Python packages, so here we'll show you how to set up a Python environment and install the specific libraries you'll need. + +We'll cover two ways of setting up your working environment, using a Colab notebook or a Python virtual environment. Feel free to choose the one that resonates with you the most. For beginners, we strongly recommend that you get started by using a Colab notebook. + +Note that we will not be covering the Windows system. If you're running on Windows, we recommend following along using a Colab notebook. If you're using a Linux distribution or macOS, you can use either approach described here. + +Most of the course relies on you having a Hugging Face account. We recommend creating one now: [create an account](https://huggingface.co/join). + +## Using a Google Colab notebook[[using-a-google-colab-notebook]] + +Using a Colab notebook is the simplest possible setup; boot up a notebook in your browser and get straight to coding! + +If you're not familiar with Colab, we recommend you start by following the [introduction](https://colab.research.google.com/notebooks/intro.ipynb). Colab allows you to use some accelerating hardware, like GPUs or TPUs, and it is free for smaller workloads. + +Once you're comfortable moving around in Colab, create a new notebook and get started with the setup: + +
+An empty colab notebook +
+ +The next step is to install the libraries that we'll be using in this course. We'll use `pip` for the installation, which is the package manager for Python. In notebooks, you can run system commands by preceding them with the `!` character, so you can install the 🤗 Transformers library as follows: + +``` +!pip install transformers +``` + +You can make sure the package was correctly installed by importing it within your Python runtime: + +``` +import transformers +``` + +
+A gif showing the result of the two commands above: installation and import +
+ +This installs a very light version of 🤗 Transformers. In particular, no specific machine learning frameworks (like PyTorch or TensorFlow) are installed. Since we'll be using a lot of different features of the library, we recommend installing the development version, which comes with all the required dependencies for pretty much any imaginable use case: + +``` +!pip install transformers[sentencepiece] +``` + +This will take a bit of time, but then you'll be ready to go for the rest of the course! + +## Using a Python virtual environment[[using-a-python-virtual-environment]] + +If you prefer to use a Python virtual environment, the first step is to install Python on your system. We recommend following [this guide](https://realpython.com/installing-python/) to get started. + +Once you have Python installed, you should be able to run Python commands in your terminal. You can start by running the following command to ensure that it is correctly installed before proceeding to the next steps: `python --version`. This should print out the Python version now available on your system. + +When running a Python command in your terminal, such as `python --version`, you should think of the program running your command as the "main" Python on your system. We recommend keeping this main installation free of any packages, and using it to create separate environments for each application you work on — this way, each application can have its own dependencies and packages, and you won't need to worry about potential compatibility issues with other applications. + +In Python this is done with [*virtual environments*](https://docs.python.org/3/tutorial/venv.html), which are self-contained directory trees that each contain a Python installation with a particular Python version alongside all the packages the application needs. Creating such a virtual environment can be done with a number of different tools, but we'll use the official Python package for that purpose, which is called [`venv`](https://docs.python.org/3/library/venv.html#module-venv). + +First, create the directory you'd like your application to live in — for example, you might want to make a new directory called *transformers-course* at the root of your home directory: + +``` +mkdir ~/transformers-course +cd ~/transformers-course +``` + +From inside this directory, create a virtual environment using the Python `venv` module: + +``` +python -m venv .env +``` + +You should now have a directory called *.env* in your otherwise empty folder: + +``` +ls -a +``` + +```out +. .. .env +``` + +You can jump in and out of your virtual environment with the `activate` and `deactivate` scripts: + +``` +# Activate the virtual environment +source .env/bin/activate + +# Deactivate the virtual environment +deactivate +``` + +You can make sure that the environment is activated by running the `which python` command: if it points to the virtual environment, then you have successfully activated it! + +``` +which python +``` + +```out +/home//transformers-course/.env/bin/python +``` + +### Installing dependencies[[installing-dependencies]] + +As in the previous section on using Google Colab instances, you'll now need to install the packages required to continue. Again, you can install the development version of 🤗 Transformers using the `pip` package manager: + +``` +pip install "transformers[sentencepiece]" +``` + +You're now all set up and ready to go! diff --git a/chapters/en/chapter1/1.mdx b/chapters/en/chapter1/1.mdx index 9294f9af1..107bd03f8 100644 --- a/chapters/en/chapter1/1.mdx +++ b/chapters/en/chapter1/1.mdx @@ -1,159 +1,159 @@ -# Introduction[[introduction]] - - - -## Welcome to the 🤗 Course![[welcome-to-the-course]] - - - -This course will teach you about large language models (LLMs) and natural language processing (NLP) using libraries from the [Hugging Face](https://huggingface.co/) ecosystem — [🤗 Transformers](https://github.com/huggingface/transformers), [🤗 Datasets](https://github.com/huggingface/datasets), [🤗 Tokenizers](https://github.com/huggingface/tokenizers), and [🤗 Accelerate](https://github.com/huggingface/accelerate) — as well as the [Hugging Face Hub](https://huggingface.co/models). - -We'll also cover libraries outside the Hugging Face ecosystem. These are amazing contributions to the AI community and incredibly useful tools. - -It's completely free and without ads. - -## Understanding NLP and LLMs[[understanding-nlp-and-llms]] - -While this course was originally focused on NLP (Natural Language Processing), it has evolved to emphasize Large Language Models (LLMs), which represent the latest advancement in the field. - -**What's the difference?** -- **NLP (Natural Language Processing)** is the broader field focused on enabling computers to understand, interpret, and generate human language. NLP encompasses many techniques and tasks such as sentiment analysis, named entity recognition, and machine translation. -- **LLMs (Large Language Models)** are a powerful subset of NLP models characterized by their massive size, extensive training data, and ability to perform a wide range of language tasks with minimal task-specific training. Models like the Llama, GPT, or Claude series are examples of LLMs that have revolutionized what's possible in NLP. - -Throughout this course, you'll learn about both traditional NLP concepts and cutting-edge LLM techniques, as understanding the foundations of NLP is crucial for working effectively with LLMs. - -## What to expect?[[what-to-expect]] - -Here is a brief overview of the course: - -
-Brief overview of the chapters of the course. - -
- -- Chapters 1 to 4 provide an introduction to the main concepts of the 🤗 Transformers library. By the end of this part of the course, you will be familiar with how Transformer models work and will know how to use a model from the [Hugging Face Hub](https://huggingface.co/models), fine-tune it on a dataset, and share your results on the Hub! -- Chapters 5 to 8 teach the basics of 🤗 Datasets and 🤗 Tokenizers before diving into classic NLP tasks and LLM techniques. By the end of this part, you will be able to tackle the most common language processing challenges by yourself. -- Chapter 9 goes beyond NLP to cover how to build and share demos of your models on the 🤗 Hub. By the end of this part, you will be ready to showcase your 🤗 Transformers application to the world! -- Chapters 10 to 12 dive into advanced LLM topics like fine-tuning, curating high-quality datasets, and building reasoning models. - -This course: - -* Requires a good knowledge of Python -* Is better taken after an introductory deep learning course, such as [fast.ai's](https://www.fast.ai/) [Practical Deep Learning for Coders](https://course.fast.ai/) or one of the programs developed by [DeepLearning.AI](https://www.deeplearning.ai/) -* Does not expect prior [PyTorch](https://pytorch.org/) or [TensorFlow](https://www.tensorflow.org/) knowledge, though some familiarity with either of those will help - -After you've completed this course, we recommend checking out DeepLearning.AI's [Natural Language Processing Specialization](https://www.coursera.org/specializations/natural-language-processing?utm_source=deeplearning-ai&utm_medium=institutions&utm_campaign=20211011-nlp-2-hugging_face-page-nlp-refresh), which covers a wide range of traditional NLP models like naive Bayes and LSTMs that are well worth knowing about! - -## Who are we?[[who-are-we]] - -About the authors: - -[**Abubakar Abid**](https://huggingface.co/abidlabs) completed his PhD at Stanford in applied machine learning. During his PhD, he founded [Gradio](https://github.com/gradio-app/gradio), an open-source Python library that has been used to build over 600,000 machine learning demos. Gradio was acquired by Hugging Face, which is where Abubakar now serves as a machine learning team lead. - -[**Ben Burtenshaw**](https://huggingface.co/burtenshaw) is a Machine Learning Engineer at Hugging Face. He completed his PhD in Natural Language Processing at the University of Antwerp, where he applied Transformer models to generate children stories for the purpose of improving literacy skills. Since then, he has focused on educational materials and tools for the wider community. - -[**Matthew Carrigan**](https://huggingface.co/Rocketknight1) is a Machine Learning Engineer at Hugging Face. He lives in Dublin, Ireland and previously worked as an ML engineer at Parse.ly and before that as a post-doctoral researcher at Trinity College Dublin. He does not believe we're going to get to AGI by scaling existing architectures, but has high hopes for robot immortality regardless. - -[**Lysandre Debut**](https://huggingface.co/lysandre) is a Machine Learning Engineer at Hugging Face and has been working on the 🤗 Transformers library since the very early development stages. His aim is to make NLP accessible for everyone by developing tools with a very simple API. - -[**Sylvain Gugger**](https://huggingface.co/sgugger) is a Research Engineer at Hugging Face and one of the core maintainers of the 🤗 Transformers library. Previously he was a Research Scientist at fast.ai, and he co-wrote _[Deep Learning for Coders with fastai and PyTorch](https://learning.oreilly.com/library/view/deep-learning-for/9781492045519/)_ with Jeremy Howard. The main focus of his research is on making deep learning more accessible, by designing and improving techniques that allow models to train fast on limited resources. - -[**Dawood Khan**](https://huggingface.co/dawoodkhan82) is a Machine Learning Engineer at Hugging Face. He's from NYC and graduated from New York University studying Computer Science. After working as an iOS Engineer for a few years, Dawood quit to start Gradio with his fellow co-founders. Gradio was eventually acquired by Hugging Face. - -[**Merve Noyan**](https://huggingface.co/merve) is a developer advocate at Hugging Face, working on developing tools and building content around them to democratize machine learning for everyone. - -[**Lucile Saulnier**](https://huggingface.co/SaulLu) is a machine learning engineer at Hugging Face, developing and supporting the use of open source tools. She is also actively involved in many research projects in the field of Natural Language Processing such as collaborative training and BigScience. - -[**Lewis Tunstall**](https://huggingface.co/lewtun) is a machine learning engineer at Hugging Face, focused on developing open-source tools and making them accessible to the wider community. He is also a co-author of the O'Reilly book [Natural Language Processing with Transformers](https://www.oreilly.com/library/view/natural-language-processing/9781098136789/). - -[**Leandro von Werra**](https://huggingface.co/lvwerra) is a machine learning engineer in the open-source team at Hugging Face and also a co-author of the O'Reilly book [Natural Language Processing with Transformers](https://www.oreilly.com/library/view/natural-language-processing/9781098136789/). He has several years of industry experience bringing NLP projects to production by working across the whole machine learning stack.. - -## FAQ[[faq]] - -Here are some answers to frequently asked questions: - -- **Does taking this course lead to a certification?** -Currently we do not have any certification for this course. However, we are working on a certification program for the Hugging Face ecosystem -- stay tuned! - -- **How much time should I spend on this course?** -Each chapter in this course is designed to be completed in 1 week, with approximately 6-8 hours of work per week. However, you can take as much time as you need to complete the course. - -- **Where can I ask a question if I have one?** -If you have a question about any section of the course, just click on the "*Ask a question*" banner at the top of the page to be automatically redirected to the right section of the [Hugging Face forums](https://discuss.huggingface.co/): - -Link to the Hugging Face forums - -Note that a list of [project ideas](https://discuss.huggingface.co/c/course/course-event/25) is also available on the forums if you wish to practice more once you have completed the course. - -- **Where can I get the code for the course?** -For each section, click on the banner at the top of the page to run the code in either Google Colab or Amazon SageMaker Studio Lab: - -Link to the Hugging Face course notebooks - -The Jupyter notebooks containing all the code from the course are hosted on the [`huggingface/notebooks`](https://github.com/huggingface/notebooks) repo. If you wish to generate them locally, check out the instructions in the [`course`](https://github.com/huggingface/course#-jupyter-notebooks) repo on GitHub. - - -- **How can I contribute to the course?** -There are many ways to contribute to the course! If you find a typo or a bug, please open an issue on the [`course`](https://github.com/huggingface/course) repo. If you would like to help translate the course into your native language, check out the instructions [here](https://github.com/huggingface/course#translating-the-course-into-your-language). - -- ** What were the choices made for each translation?** -Each translation has a glossary and `TRANSLATING.txt` file that details the choices that were made for machine learning jargon etc. You can find an example for German [here](https://github.com/huggingface/course/blob/main/chapters/de/TRANSLATING.txt). - - -- **Can I reuse this course?** -Of course! The course is released under the permissive [Apache 2 license](https://www.apache.org/licenses/LICENSE-2.0.html). This means that you must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use. If you would like to cite the course, please use the following BibTeX: - -``` -@misc{huggingfacecourse, - author = {Hugging Face}, - title = {The Hugging Face Course, 2022}, - howpublished = "\url{https://huggingface.co/course}", - year = {2022}, - note = "[Online; accessed ]" -} -``` - -## Languages and translations[[languages-and-translations]] - -Thanks to our wonderful community, the course is available in many languages beyond English 🔥! Check out the table below to see which languages are available and who contributed to the translations: - -| Language | Authors | -|:------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| [French](https://huggingface.co/course/fr/chapter1/1) | [@lbourdois](https://github.com/lbourdois), [@ChainYo](https://github.com/ChainYo), [@melaniedrevet](https://github.com/melaniedrevet), [@abdouaziz](https://github.com/abdouaziz) | -| [Vietnamese](https://huggingface.co/course/vi/chapter1/1) | [@honghanhh](https://github.com/honghanhh) | -| [Chinese (simplified)](https://huggingface.co/course/zh-CN/chapter1/1) | [@zhlhyx](https://github.com/zhlhyx), [petrichor1122](https://github.com/petrichor1122), [@yaoqih](https://github.com/yaoqih) | -| [Bengali](https://huggingface.co/course/bn/chapter1/1) (WIP) | [@avishek-018](https://github.com/avishek-018), [@eNipu](https://github.com/eNipu) | -| [German](https://huggingface.co/course/de/chapter1/1) (WIP) | [@JesperDramsch](https://github.com/JesperDramsch), [@MarcusFra](https://github.com/MarcusFra), [@fabridamicelli](https://github.com/fabridamicelli) | -| [Spanish](https://huggingface.co/course/es/chapter1/1) (WIP) | [@camartinezbu](https://github.com/camartinezbu), [@munozariasjm](https://github.com/munozariasjm), [@fordaz](https://github.com/fordaz) | -| [Persian](https://huggingface.co/course/fa/chapter1/1) (WIP) | [@jowharshamshiri](https://github.com/jowharshamshiri), [@schoobani](https://github.com/schoobani) | -| [Gujarati](https://huggingface.co/course/gu/chapter1/1) (WIP) | [@pandyaved98](https://github.com/pandyaved98) | -| [Hebrew](https://huggingface.co/course/he/chapter1/1) (WIP) | [@omer-dor](https://github.com/omer-dor) | -| [Hindi](https://huggingface.co/course/hi/chapter1/1) (WIP) | [@pandyaved98](https://github.com/pandyaved98) | -| [Bahasa Indonesia](https://huggingface.co/course/id/chapter1/1) (WIP) | [@gstdl](https://github.com/gstdl) | -| [Italian](https://huggingface.co/course/it/chapter1/1) (WIP) | [@CaterinaBi](https://github.com/CaterinaBi), [@ClonedOne](https://github.com/ClonedOne), [@Nolanogenn](https://github.com/Nolanogenn), [@EdAbati](https://github.com/EdAbati), [@gdacciaro](https://github.com/gdacciaro) | -| [Japanese](https://huggingface.co/course/ja/chapter1/1) (WIP) | [@hiromu166](https://github.com/@hiromu166), [@younesbelkada](https://github.com/@younesbelkada), [@HiromuHota](https://github.com/@HiromuHota) | -| [Korean](https://huggingface.co/course/ko/chapter1/1) (WIP) | [@Doohae](https://github.com/Doohae), [@wonhyeongseo](https://github.com/wonhyeongseo), [@dlfrnaos19](https://github.com/dlfrnaos19) | -| [Portuguese](https://huggingface.co/course/pt/chapter1/1) (WIP) | [@johnnv1](https://github.com/johnnv1), [@victorescosta](https://github.com/victorescosta), [@LincolnVS](https://github.com/LincolnVS) | -| [Russian](https://huggingface.co/course/ru/chapter1/1) (WIP) | [@pdumin](https://github.com/pdumin), [@svv73](https://github.com/svv73) | -| [Thai](https://huggingface.co/course/th/chapter1/1) (WIP) | [@peeraponw](https://github.com/peeraponw), [@a-krirk](https://github.com/a-krirk), [@jomariya23156](https://github.com/jomariya23156), [@ckingkan](https://github.com/ckingkan) | -| [Turkish](https://huggingface.co/course/tr/chapter1/1) (WIP) | [@tanersekmen](https://github.com/tanersekmen), [@mertbozkir](https://github.com/mertbozkir), [@ftarlaci](https://github.com/ftarlaci), [@akkasayaz](https://github.com/akkasayaz) | -| [Chinese (traditional)](https://huggingface.co/course/zh-TW/chapter1/1) (WIP) | [@davidpeng86](https://github.com/davidpeng86) | - -For some languages, the [course YouTube videos](https://youtube.com/playlist?list=PLo2EIpI_JMQvWfQndUesu0nPBAtZ9gP1o) have subtitles in the language. You can enable them by first clicking the _CC_ button in the bottom right corner of the video. Then, under the settings icon ⚙️, you can select the language you want by selecting the _Subtitles/CC_ option. - -Activating subtitles for the Hugging Face course YouTube videos - -> [!TIP] -> Don't see your language in the above table or you'd like to contribute to an existing translation? You can help us translate the course by following the instructions here. - -## Let's go 🚀 - -Are you ready to roll? In this chapter, you will learn: - -* How to use the `pipeline()` function to solve NLP tasks such as text generation and classification -* About the Transformer architecture -* How to distinguish between encoder, decoder, and encoder-decoder architectures and use cases - +# Introduction[[introduction]] + + + +## Welcome to the 🤗 Course![[welcome-to-the-course]] + + + +This course will teach you about large language models (LLMs) and natural language processing (NLP) using libraries from the [Hugging Face](https://huggingface.co/) ecosystem — [🤗 Transformers](https://github.com/huggingface/transformers), [🤗 Datasets](https://github.com/huggingface/datasets), [🤗 Tokenizers](https://github.com/huggingface/tokenizers), and [🤗 Accelerate](https://github.com/huggingface/accelerate) — as well as the [Hugging Face Hub](https://huggingface.co/models). + +We'll also cover libraries outside the Hugging Face ecosystem. These are amazing contributions to the AI community and incredibly useful tools. + +It's completely free and without ads. + +## Understanding NLP and LLMs[[understanding-nlp-and-llms]] + +While this course was originally focused on NLP (Natural Language Processing), it has evolved to emphasize Large Language Models (LLMs), which represent the latest advancement in the field. + +**What's the difference?** +- **NLP (Natural Language Processing)** is the broader field focused on enabling computers to understand, interpret, and generate human language. NLP encompasses many techniques and tasks such as sentiment analysis, named entity recognition, and machine translation. +- **LLMs (Large Language Models)** are a powerful subset of NLP models characterized by their massive size, extensive training data, and ability to perform a wide range of language tasks with minimal task-specific training. Models like the Llama, GPT, or Claude series are examples of LLMs that have revolutionized what's possible in NLP. + +Throughout this course, you'll learn about both traditional NLP concepts and cutting-edge LLM techniques, as understanding the foundations of NLP is crucial for working effectively with LLMs. + +## What to expect?[[what-to-expect]] + +Here is a brief overview of the course: + +
+Brief overview of the chapters of the course. + +
+ +- Chapters 1 to 4 provide an introduction to the main concepts of the 🤗 Transformers library. By the end of this part of the course, you will be familiar with how Transformer models work and will know how to use a model from the [Hugging Face Hub](https://huggingface.co/models), fine-tune it on a dataset, and share your results on the Hub! +- Chapters 5 to 8 teach the basics of 🤗 Datasets and 🤗 Tokenizers before diving into classic NLP tasks and LLM techniques. By the end of this part, you will be able to tackle the most common language processing challenges by yourself. +- Chapter 9 goes beyond NLP to cover how to build and share demos of your models on the 🤗 Hub. By the end of this part, you will be ready to showcase your 🤗 Transformers application to the world! +- Chapters 10 to 12 dive into advanced LLM topics like fine-tuning, curating high-quality datasets, and building reasoning models. + +This course: + +* Requires a good knowledge of Python +* Is better taken after an introductory deep learning course, such as [fast.ai's](https://www.fast.ai/) [Practical Deep Learning for Coders](https://course.fast.ai/) or one of the programs developed by [DeepLearning.AI](https://www.deeplearning.ai/) +* Does not expect prior [PyTorch](https://pytorch.org/) or [TensorFlow](https://www.tensorflow.org/) knowledge, though some familiarity with either of those will help + +After you've completed this course, we recommend checking out DeepLearning.AI's [Natural Language Processing Specialization](https://www.coursera.org/specializations/natural-language-processing?utm_source=deeplearning-ai&utm_medium=institutions&utm_campaign=20211011-nlp-2-hugging_face-page-nlp-refresh), which covers a wide range of traditional NLP models like naive Bayes and LSTMs that are well worth knowing about! + +## Who are we?[[who-are-we]] + +About the authors: + +[**Abubakar Abid**](https://huggingface.co/abidlabs) completed his PhD at Stanford in applied machine learning. During his PhD, he founded [Gradio](https://github.com/gradio-app/gradio), an open-source Python library that has been used to build over 600,000 machine learning demos. Gradio was acquired by Hugging Face, which is where Abubakar now serves as a machine learning team lead. + +[**Ben Burtenshaw**](https://huggingface.co/burtenshaw) is a Machine Learning Engineer at Hugging Face. He completed his PhD in Natural Language Processing at the University of Antwerp, where he applied Transformer models to generate children stories for the purpose of improving literacy skills. Since then, he has focused on educational materials and tools for the wider community. + +[**Matthew Carrigan**](https://huggingface.co/Rocketknight1) is a Machine Learning Engineer at Hugging Face. He lives in Dublin, Ireland and previously worked as an ML engineer at Parse.ly and before that as a post-doctoral researcher at Trinity College Dublin. He does not believe we're going to get to AGI by scaling existing architectures, but has high hopes for robot immortality regardless. + +[**Lysandre Debut**](https://huggingface.co/lysandre) is a Machine Learning Engineer at Hugging Face and has been working on the 🤗 Transformers library since the very early development stages. His aim is to make NLP accessible for everyone by developing tools with a very simple API. + +[**Sylvain Gugger**](https://huggingface.co/sgugger) is a Research Engineer at Hugging Face and one of the core maintainers of the 🤗 Transformers library. Previously he was a Research Scientist at fast.ai, and he co-wrote _[Deep Learning for Coders with fastai and PyTorch](https://learning.oreilly.com/library/view/deep-learning-for/9781492045519/)_ with Jeremy Howard. The main focus of his research is on making deep learning more accessible, by designing and improving techniques that allow models to train fast on limited resources. + +[**Dawood Khan**](https://huggingface.co/dawoodkhan82) is a Machine Learning Engineer at Hugging Face. He's from NYC and graduated from New York University studying Computer Science. After working as an iOS Engineer for a few years, Dawood quit to start Gradio with his fellow co-founders. Gradio was eventually acquired by Hugging Face. + +[**Merve Noyan**](https://huggingface.co/merve) is a developer advocate at Hugging Face, working on developing tools and building content around them to democratize machine learning for everyone. + +[**Lucile Saulnier**](https://huggingface.co/SaulLu) is a machine learning engineer at Hugging Face, developing and supporting the use of open source tools. She is also actively involved in many research projects in the field of Natural Language Processing such as collaborative training and BigScience. + +[**Lewis Tunstall**](https://huggingface.co/lewtun) is a machine learning engineer at Hugging Face, focused on developing open-source tools and making them accessible to the wider community. He is also a co-author of the O'Reilly book [Natural Language Processing with Transformers](https://www.oreilly.com/library/view/natural-language-processing/9781098136789/). + +[**Leandro von Werra**](https://huggingface.co/lvwerra) is a machine learning engineer in the open-source team at Hugging Face and also a co-author of the O'Reilly book [Natural Language Processing with Transformers](https://www.oreilly.com/library/view/natural-language-processing/9781098136789/). He has several years of industry experience bringing NLP projects to production by working across the whole machine learning stack.. + +## FAQ[[faq]] + +Here are some answers to frequently asked questions: + +- **Does taking this course lead to a certification?** +Currently we do not have any certification for this course. However, we are working on a certification program for the Hugging Face ecosystem -- stay tuned! + +- **How much time should I spend on this course?** +Each chapter in this course is designed to be completed in 1 week, with approximately 6-8 hours of work per week. However, you can take as much time as you need to complete the course. + +- **Where can I ask a question if I have one?** +If you have a question about any section of the course, just click on the "*Ask a question*" banner at the top of the page to be automatically redirected to the right section of the [Hugging Face forums](https://discuss.huggingface.co/): + +Link to the Hugging Face forums + +Note that a list of [project ideas](https://discuss.huggingface.co/c/course/course-event/25) is also available on the forums if you wish to practice more once you have completed the course. + +- **Where can I get the code for the course?** +For each section, click on the banner at the top of the page to run the code in either Google Colab or Amazon SageMaker Studio Lab: + +Link to the Hugging Face course notebooks + +The Jupyter notebooks containing all the code from the course are hosted on the [`huggingface/notebooks`](https://github.com/huggingface/notebooks) repo. If you wish to generate them locally, check out the instructions in the [`course`](https://github.com/huggingface/course#-jupyter-notebooks) repo on GitHub. + + +- **How can I contribute to the course?** +There are many ways to contribute to the course! If you find a typo or a bug, please open an issue on the [`course`](https://github.com/huggingface/course) repo. If you would like to help translate the course into your native language, check out the instructions [here](https://github.com/huggingface/course#translating-the-course-into-your-language). + +- ** What were the choices made for each translation?** +Each translation has a glossary and `TRANSLATING.txt` file that details the choices that were made for machine learning jargon etc. You can find an example for German [here](https://github.com/huggingface/course/blob/main/chapters/de/TRANSLATING.txt). + + +- **Can I reuse this course?** +Of course! The course is released under the permissive [Apache 2 license](https://www.apache.org/licenses/LICENSE-2.0.html). This means that you must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use. If you would like to cite the course, please use the following BibTeX: + +``` +@misc{huggingfacecourse, + author = {Hugging Face}, + title = {The Hugging Face Course, 2022}, + howpublished = "\url{https://huggingface.co/course}", + year = {2022}, + note = "[Online; accessed ]" +} +``` + +## Languages and translations[[languages-and-translations]] + +Thanks to our wonderful community, the course is available in many languages beyond English 🔥! Check out the table below to see which languages are available and who contributed to the translations: + +| Language | Authors | +|:------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [French](https://huggingface.co/course/fr/chapter1/1) | [@lbourdois](https://github.com/lbourdois), [@ChainYo](https://github.com/ChainYo), [@melaniedrevet](https://github.com/melaniedrevet), [@abdouaziz](https://github.com/abdouaziz) | +| [Vietnamese](https://huggingface.co/course/vi/chapter1/1) | [@honghanhh](https://github.com/honghanhh) | +| [Chinese (simplified)](https://huggingface.co/course/zh-CN/chapter1/1) | [@zhlhyx](https://github.com/zhlhyx), [petrichor1122](https://github.com/petrichor1122), [@yaoqih](https://github.com/yaoqih) | +| [Bengali](https://huggingface.co/course/bn/chapter1/1) (WIP) | [@avishek-018](https://github.com/avishek-018), [@eNipu](https://github.com/eNipu) | +| [German](https://huggingface.co/course/de/chapter1/1) (WIP) | [@JesperDramsch](https://github.com/JesperDramsch), [@MarcusFra](https://github.com/MarcusFra), [@fabridamicelli](https://github.com/fabridamicelli) | +| [Spanish](https://huggingface.co/course/es/chapter1/1) (WIP) | [@camartinezbu](https://github.com/camartinezbu), [@munozariasjm](https://github.com/munozariasjm), [@fordaz](https://github.com/fordaz) | +| [Persian](https://huggingface.co/course/fa/chapter1/1) (WIP) | [@jowharshamshiri](https://github.com/jowharshamshiri), [@schoobani](https://github.com/schoobani) | +| [Gujarati](https://huggingface.co/course/gu/chapter1/1) (WIP) | [@pandyaved98](https://github.com/pandyaved98) | +| [Hebrew](https://huggingface.co/course/he/chapter1/1) (WIP) | [@omer-dor](https://github.com/omer-dor) | +| [Hindi](https://huggingface.co/course/hi/chapter1/1) (WIP) | [@pandyaved98](https://github.com/pandyaved98) | +| [Bahasa Indonesia](https://huggingface.co/course/id/chapter1/1) (WIP) | [@gstdl](https://github.com/gstdl) | +| [Italian](https://huggingface.co/course/it/chapter1/1) (WIP) | [@CaterinaBi](https://github.com/CaterinaBi), [@ClonedOne](https://github.com/ClonedOne), [@Nolanogenn](https://github.com/Nolanogenn), [@EdAbati](https://github.com/EdAbati), [@gdacciaro](https://github.com/gdacciaro) | +| [Japanese](https://huggingface.co/course/ja/chapter1/1) (WIP) | [@hiromu166](https://github.com/@hiromu166), [@younesbelkada](https://github.com/@younesbelkada), [@HiromuHota](https://github.com/@HiromuHota) | +| [Korean](https://huggingface.co/course/ko/chapter1/1) (WIP) | [@Doohae](https://github.com/Doohae), [@wonhyeongseo](https://github.com/wonhyeongseo), [@dlfrnaos19](https://github.com/dlfrnaos19) | +| [Portuguese](https://huggingface.co/course/pt/chapter1/1) (WIP) | [@johnnv1](https://github.com/johnnv1), [@victorescosta](https://github.com/victorescosta), [@LincolnVS](https://github.com/LincolnVS) | +| [Russian](https://huggingface.co/course/ru/chapter1/1) (WIP) | [@pdumin](https://github.com/pdumin), [@svv73](https://github.com/svv73) | +| [Thai](https://huggingface.co/course/th/chapter1/1) (WIP) | [@peeraponw](https://github.com/peeraponw), [@a-krirk](https://github.com/a-krirk), [@jomariya23156](https://github.com/jomariya23156), [@ckingkan](https://github.com/ckingkan) | +| [Turkish](https://huggingface.co/course/tr/chapter1/1) (WIP) | [@tanersekmen](https://github.com/tanersekmen), [@mertbozkir](https://github.com/mertbozkir), [@ftarlaci](https://github.com/ftarlaci), [@akkasayaz](https://github.com/akkasayaz) | +| [Chinese (traditional)](https://huggingface.co/course/zh-TW/chapter1/1) (WIP) | [@davidpeng86](https://github.com/davidpeng86) | + +For some languages, the [course YouTube videos](https://youtube.com/playlist?list=PLo2EIpI_JMQvWfQndUesu0nPBAtZ9gP1o) have subtitles in the language. You can enable them by first clicking the _CC_ button in the bottom right corner of the video. Then, under the settings icon ⚙️, you can select the language you want by selecting the _Subtitles/CC_ option. + +Activating subtitles for the Hugging Face course YouTube videos + +> [!TIP] +> Don't see your language in the above table or you'd like to contribute to an existing translation? You can help us translate the course by following the instructions here. + +## Let's go 🚀 + +Are you ready to roll? In this chapter, you will learn: + +* How to use the `pipeline()` function to solve NLP tasks such as text generation and classification +* About the Transformer architecture +* How to distinguish between encoder, decoder, and encoder-decoder architectures and use cases + diff --git a/chapters/en/chapter1/10.mdx b/chapters/en/chapter1/10.mdx index b5d646a3c..15d6d4550 100644 --- a/chapters/en/chapter1/10.mdx +++ b/chapters/en/chapter1/10.mdx @@ -1,66 +1,66 @@ -# Summary[[summary]] - - - -In this chapter, you've been introduced to the fundamentals of Transformer models, Large Language Models (LLMs), and how they're revolutionizing AI and beyond. - -## Key concepts covered - -### Natural Language Processing and LLMs - -We explored what NLP is and how Large Language Models have transformed the field. You learned that: -- NLP encompasses a wide range of tasks from classification to generation -- LLMs are powerful models trained on massive amounts of text data -- These models can perform multiple tasks within a single architecture -- Despite their capabilities, LLMs have limitations including hallucinations and bias - -### Transformer capabilities - -You saw how the `pipeline()` function from 🤗 Transformers makes it easy to use pre-trained models for various tasks: -- Text classification, token classification, and question answering -- Text generation and summarization -- Translation and other sequence-to-sequence tasks -- Speech recognition and image classification - -### Transformer architecture - -We discussed how Transformer models work at a high level, including: -- The importance of the attention mechanism -- How transfer learning enables models to adapt to specific tasks -- The three main architectural variants: encoder-only, decoder-only, and encoder-decoder - -### Model architectures and their applications -A key aspect of this chapter was understanding which architecture to use for different tasks: - -| Model | Examples | Tasks | -|-----------------|--------------------------------------------|----------------------------------------------------------------------------------| -| Encoder-only | BERT, DistilBERT, ModernBERT | Sentence classification, named entity recognition, extractive question answering | -| Decoder-only | GPT, LLaMA, Gemma, SmolLM | Text generation, conversational AI, creative writing | -| Encoder-decoder | BART, T5, Marian, mBART | Summarization, translation, generative question answering | - -### Modern LLM developments -You also learned about recent developments in the field: -- How LLMs have grown in size and capability over time -- The concept of scaling laws and how they guide model development -- Specialized attention mechanisms that help models process longer sequences -- The two-phase training approach of pretraining and instruction tuning - -### Practical applications -Throughout the chapter, you've seen how these models can be applied to real-world problems: -- Using the Hugging Face Hub to find and use pre-trained models -- Leveraging the Inference API to test models directly in your browser -- Understanding which models are best suited for specific tasks - -## Looking ahead - -Now that you have a solid understanding of what Transformer models are and how they work at a high level, you're ready to dive deeper into how to use them effectively. In the next chapters, you'll learn how to: - -- Use the Transformers library to load and fine-tune models -- Process different types of data for model input -- Adapt pre-trained models to your specific tasks -- Deploy models for practical applications - -The foundation you've built in this chapter will serve you well as you explore more advanced topics and techniques in the coming sections. +# Summary[[summary]] + + + +In this chapter, you've been introduced to the fundamentals of Transformer models, Large Language Models (LLMs), and how they're revolutionizing AI and beyond. + +## Key concepts covered + +### Natural Language Processing and LLMs + +We explored what NLP is and how Large Language Models have transformed the field. You learned that: +- NLP encompasses a wide range of tasks from classification to generation +- LLMs are powerful models trained on massive amounts of text data +- These models can perform multiple tasks within a single architecture +- Despite their capabilities, LLMs have limitations including hallucinations and bias + +### Transformer capabilities + +You saw how the `pipeline()` function from 🤗 Transformers makes it easy to use pre-trained models for various tasks: +- Text classification, token classification, and question answering +- Text generation and summarization +- Translation and other sequence-to-sequence tasks +- Speech recognition and image classification + +### Transformer architecture + +We discussed how Transformer models work at a high level, including: +- The importance of the attention mechanism +- How transfer learning enables models to adapt to specific tasks +- The three main architectural variants: encoder-only, decoder-only, and encoder-decoder + +### Model architectures and their applications +A key aspect of this chapter was understanding which architecture to use for different tasks: + +| Model | Examples | Tasks | +|-----------------|--------------------------------------------|----------------------------------------------------------------------------------| +| Encoder-only | BERT, DistilBERT, ModernBERT | Sentence classification, named entity recognition, extractive question answering | +| Decoder-only | GPT, LLaMA, Gemma, SmolLM | Text generation, conversational AI, creative writing | +| Encoder-decoder | BART, T5, Marian, mBART | Summarization, translation, generative question answering | + +### Modern LLM developments +You also learned about recent developments in the field: +- How LLMs have grown in size and capability over time +- The concept of scaling laws and how they guide model development +- Specialized attention mechanisms that help models process longer sequences +- The two-phase training approach of pretraining and instruction tuning + +### Practical applications +Throughout the chapter, you've seen how these models can be applied to real-world problems: +- Using the Hugging Face Hub to find and use pre-trained models +- Leveraging the Inference API to test models directly in your browser +- Understanding which models are best suited for specific tasks + +## Looking ahead + +Now that you have a solid understanding of what Transformer models are and how they work at a high level, you're ready to dive deeper into how to use them effectively. In the next chapters, you'll learn how to: + +- Use the Transformers library to load and fine-tune models +- Process different types of data for model input +- Adapt pre-trained models to your specific tasks +- Deploy models for practical applications + +The foundation you've built in this chapter will serve you well as you explore more advanced topics and techniques in the coming sections. diff --git a/chapters/en/chapter1/11.mdx b/chapters/en/chapter1/11.mdx index dddddf271..1c2b7bc9c 100644 --- a/chapters/en/chapter1/11.mdx +++ b/chapters/en/chapter1/11.mdx @@ -1,21 +1,21 @@ -# Exam Time! - -It's time to put your knowledge to the test! We've prepared a short quiz for you to test your understanding of the concepts covered in this chapter. - -To take the quiz, you will need to follow these steps: - -1. Sign in to your Hugging Face account. -2. Answer the questions in the quiz. -3. Submit your answers. - - -## Multiple Choice Quiz - -In this quiz, you will be asked to select the correct answer from a list of options. We'll test you on the fundamentals of supervised finetuning. - - +# Exam Time! + +It's time to put your knowledge to the test! We've prepared a short quiz for you to test your understanding of the concepts covered in this chapter. + +To take the quiz, you will need to follow these steps: + +1. Sign in to your Hugging Face account. +2. Answer the questions in the quiz. +3. Submit your answers. + + +## Multiple Choice Quiz + +In this quiz, you will be asked to select the correct answer from a list of options. We'll test you on the fundamentals of supervised finetuning. + + diff --git a/chapters/en/chapter1/2.mdx b/chapters/en/chapter1/2.mdx index ebfb179a4..decda3f96 100644 --- a/chapters/en/chapter1/2.mdx +++ b/chapters/en/chapter1/2.mdx @@ -1,52 +1,52 @@ -# Natural Language Processing and Large Language Models[[natural-language-processing-and-large-language-models]] - - - -Before jumping into Transformer models, let's do a quick overview of what natural language processing is, how large language models have transformed the field, and why we care about it. - -## What is NLP?[[what-is-nlp]] - - - -NLP is a field of linguistics and machine learning focused on understanding everything related to human language. The aim of NLP tasks is not only to understand single words individually, but to be able to understand the context of those words. - -The following is a list of common NLP tasks, with some examples of each: - -- **Classifying whole sentences**: Getting the sentiment of a review, detecting if an email is spam, determining if a sentence is grammatically correct or whether two sentences are logically related or not -- **Classifying each word in a sentence**: Identifying the grammatical components of a sentence (noun, verb, adjective), or the named entities (person, location, organization) -- **Generating text content**: Completing a prompt with auto-generated text, filling in the blanks in a text with masked words -- **Extracting an answer from a text**: Given a question and a context, extracting the answer to the question based on the information provided in the context -- **Generating a new sentence from an input text**: Translating a text into another language, summarizing a text - -NLP isn't limited to written text though. It also tackles complex challenges in speech recognition and computer vision, such as generating a transcript of an audio sample or a description of an image. - -## The Rise of Large Language Models (LLMs)[[rise-of-llms]] - -In recent years, the field of NLP has been revolutionized by Large Language Models (LLMs). These models, which include architectures like GPT (Generative Pre-trained Transformer) and [Llama](https://huggingface.co/meta-llama), have transformed what's possible in language processing. - -> [!TIP] -> A large language model (LLM) is an AI model trained on massive amounts of text data that can understand and generate human-like text, recognize patterns in language, and perform a wide variety of language tasks without task-specific training. They represent a significant advancement in the field of natural language processing (NLP). - -LLMs are characterized by: -- **Scale**: They contain millions, billions, or even hundreds of billions of parameters -- **General capabilities**: They can perform multiple tasks without task-specific training -- **In-context learning**: They can learn from examples provided in the prompt -- **Emergent abilities**: As these models grow in size, they demonstrate capabilities that weren't explicitly programmed or anticipated - -The advent of LLMs has shifted the paradigm from building specialized models for specific NLP tasks to using a single, large model that can be prompted or fine-tuned to address a wide range of language tasks. This has made sophisticated language processing more accessible while also introducing new challenges in areas like efficiency, ethics, and deployment. - -However, LLMs also have important limitations: -- **Hallucinations**: They can generate incorrect information confidently -- **Lack of true understanding**: They lack true understanding of the world and operate purely on statistical patterns -- **Bias**: They may reproduce biases present in their training data or inputs. -- **Context windows**: They have limited context windows (though this is improving) -- **Computational resources**: They require significant computational resources - -## Why is language processing challenging?[[why-is-it-challenging]] - -Computers don't process information in the same way as humans. For example, when we read the sentence "I am hungry," we can easily understand its meaning. Similarly, given two sentences such as "I am hungry" and "I am sad," we're able to easily determine how similar they are. For machine learning (ML) models, such tasks are more difficult. The text needs to be processed in a way that enables the model to learn from it. And because language is complex, we need to think carefully about how this processing must be done. There has been a lot of research done on how to represent text, and we will look at some methods in the next chapter. - -Even with the advances in LLMs, many fundamental challenges remain. These include understanding ambiguity, cultural context, sarcasm, and humor. LLMs address these challenges through massive training on diverse datasets, but still often fall short of human-level understanding in many complex scenarios. +# Natural Language Processing and Large Language Models[[natural-language-processing-and-large-language-models]] + + + +Before jumping into Transformer models, let's do a quick overview of what natural language processing is, how large language models have transformed the field, and why we care about it. + +## What is NLP?[[what-is-nlp]] + + + +NLP is a field of linguistics and machine learning focused on understanding everything related to human language. The aim of NLP tasks is not only to understand single words individually, but to be able to understand the context of those words. + +The following is a list of common NLP tasks, with some examples of each: + +- **Classifying whole sentences**: Getting the sentiment of a review, detecting if an email is spam, determining if a sentence is grammatically correct or whether two sentences are logically related or not +- **Classifying each word in a sentence**: Identifying the grammatical components of a sentence (noun, verb, adjective), or the named entities (person, location, organization) +- **Generating text content**: Completing a prompt with auto-generated text, filling in the blanks in a text with masked words +- **Extracting an answer from a text**: Given a question and a context, extracting the answer to the question based on the information provided in the context +- **Generating a new sentence from an input text**: Translating a text into another language, summarizing a text + +NLP isn't limited to written text though. It also tackles complex challenges in speech recognition and computer vision, such as generating a transcript of an audio sample or a description of an image. + +## The Rise of Large Language Models (LLMs)[[rise-of-llms]] + +In recent years, the field of NLP has been revolutionized by Large Language Models (LLMs). These models, which include architectures like GPT (Generative Pre-trained Transformer) and [Llama](https://huggingface.co/meta-llama), have transformed what's possible in language processing. + +> [!TIP] +> A large language model (LLM) is an AI model trained on massive amounts of text data that can understand and generate human-like text, recognize patterns in language, and perform a wide variety of language tasks without task-specific training. They represent a significant advancement in the field of natural language processing (NLP). + +LLMs are characterized by: +- **Scale**: They contain millions, billions, or even hundreds of billions of parameters +- **General capabilities**: They can perform multiple tasks without task-specific training +- **In-context learning**: They can learn from examples provided in the prompt +- **Emergent abilities**: As these models grow in size, they demonstrate capabilities that weren't explicitly programmed or anticipated + +The advent of LLMs has shifted the paradigm from building specialized models for specific NLP tasks to using a single, large model that can be prompted or fine-tuned to address a wide range of language tasks. This has made sophisticated language processing more accessible while also introducing new challenges in areas like efficiency, ethics, and deployment. + +However, LLMs also have important limitations: +- **Hallucinations**: They can generate incorrect information confidently +- **Lack of true understanding**: They lack true understanding of the world and operate purely on statistical patterns +- **Bias**: They may reproduce biases present in their training data or inputs. +- **Context windows**: They have limited context windows (though this is improving) +- **Computational resources**: They require significant computational resources + +## Why is language processing challenging?[[why-is-it-challenging]] + +Computers don't process information in the same way as humans. For example, when we read the sentence "I am hungry," we can easily understand its meaning. Similarly, given two sentences such as "I am hungry" and "I am sad," we're able to easily determine how similar they are. For machine learning (ML) models, such tasks are more difficult. The text needs to be processed in a way that enables the model to learn from it. And because language is complex, we need to think carefully about how this processing must be done. There has been a lot of research done on how to represent text, and we will look at some methods in the next chapter. + +Even with the advances in LLMs, many fundamental challenges remain. These include understanding ambiguity, cultural context, sarcasm, and humor. LLMs address these challenges through massive training on diverse datasets, but still often fall short of human-level understanding in many complex scenarios. diff --git a/chapters/en/chapter1/3.mdx b/chapters/en/chapter1/3.mdx index 7efc4ef8e..3f3762356 100644 --- a/chapters/en/chapter1/3.mdx +++ b/chapters/en/chapter1/3.mdx @@ -269,8 +269,7 @@ Summarization is the task of reducing a text into a shorter text while keeping a from transformers import pipeline summarizer = pipeline("summarization") -summarizer( - """ +summarizer(""" America has changed dramatically during recent years. Not only has the number of graduates in traditional engineering disciplines such as mechanical, civil, electrical, chemical, and aeronautical engineering declined, but in most of @@ -289,8 +288,7 @@ summarizer( Other industrial countries at minimum maintain their output, while America suffers an increasingly serious decline in the number of engineering graduates and a lack of well-educated engineers. -""" -) +""") ``` ```python out diff --git a/chapters/en/chapter1/4.mdx b/chapters/en/chapter1/4.mdx index 7500f6376..c9ec1d2d3 100644 --- a/chapters/en/chapter1/4.mdx +++ b/chapters/en/chapter1/4.mdx @@ -1,189 +1,189 @@ -# How do Transformers work?[[how-do-transformers-work]] - - - -In this section, we will take a look at the architecture of Transformer models and dive deeper into the concepts of attention, encoder-decoder architecture, and more. - -> [!WARNING] -> 🚀 We're taking things up a notch here. This section is detailed and technical, so don't worry if you don't understand everything right away. We'll come back to these concepts later in the course. - -## A bit of Transformer history[[a-bit-of-transformer-history]] - -Here are some reference points in the (short) history of Transformer models: - -
-A brief chronology of Transformers models. - -
- -The [Transformer architecture](https://arxiv.org/abs/1706.03762) was introduced in June 2017. The focus of the original research was on translation tasks. This was followed by the introduction of several influential models, including: - -- **June 2018**: [GPT](https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf), the first pretrained Transformer model, used for fine-tuning on various NLP tasks and obtained state-of-the-art results - -- **October 2018**: [BERT](https://arxiv.org/abs/1810.04805), another large pretrained model, this one designed to produce better summaries of sentences (more on this in the next chapter!) - -- **February 2019**: [GPT-2](https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf), an improved (and bigger) version of GPT that was not immediately publicly released due to ethical concerns - -- **October 2019**: [T5](https://huggingface.co/papers/1910.10683), A multi-task focused implementation of the sequence-to-sequence Transformer architecture. - -- **May 2020**, [GPT-3](https://huggingface.co/papers/2005.14165), an even bigger version of GPT-2 that is able to perform well on a variety of tasks without the need for fine-tuning (called _zero-shot learning_) - -- **January 2022**: [InstructGPT](https://huggingface.co/papers/2203.02155), a version of GPT-3 that was trained to follow instructions better. - -- **January 2023**: [Llama](https://huggingface.co/papers/2302.13971), a large language model that is able to generate text in a variety of languages. - -- **March 2023**: [Mistral](https://huggingface.co/papers/2310.06825), a 7-billion-parameter language model that outperforms Llama 2 13B across all evaluated benchmarks, leveraging grouped-query attention for faster inference and sliding window attention to handle sequences of arbitrary length. - -- **May 2024**: [Gemma 2](https://huggingface.co/papers/2408.00118), a family of lightweight, state-of-the-art open models ranging from 2B to 27B parameters that incorporate interleaved local-global attentions and group-query attention, with smaller models trained using knowledge distillation to deliver performance competitive with models 2-3 times larger. - -- **November 2024**: [SmolLM2](https://huggingface.co/papers/2502.02737), a state-of-the-art small language model (135 million to 1.7 billion parameters) that achieves impressive performance despite its compact size, and unlocking new possibilities for mobile and edge devices. - -This list is far from comprehensive, and is just meant to highlight a few of the different kinds of Transformer models. Broadly, they can be grouped into three categories: - -- GPT-like (also called _auto-regressive_ Transformer models) -- BERT-like (also called _auto-encoding_ Transformer models) -- T5-like (also called _sequence-to-sequence_ Transformer models) - -We will dive into these families in more depth later on. - -## Transformers are language models[[transformers-are-language-models]] - -All the Transformer models mentioned above (GPT, BERT, T5, etc.) have been trained as *language models*. This means they have been trained on large amounts of raw text in a self-supervised fashion. - -Self-supervised learning is a type of training in which the objective is automatically computed from the inputs of the model. That means that humans are not needed to label the data! - -This type of model develops a statistical understanding of the language it has been trained on, but it's less useful for specific practical tasks. Because of this, the general pretrained model then goes through a process called *transfer learning* or *fine-tuning*. During this process, the model is fine-tuned in a supervised way -- that is, using human-annotated labels -- on a given task. - -An example of a task is predicting the next word in a sentence having read the *n* previous words. This is called *causal language modeling* because the output depends on the past and present inputs, but not the future ones. - -
-Example of causal language modeling in which the next word from a sentence is predicted. - -
- -Another example is *masked language modeling*, in which the model predicts a masked word in the sentence. - -
-Example of masked language modeling in which a masked word from a sentence is predicted. - -
- -## Transformers are big models[[transformers-are-big-models]] - -Apart from a few outliers (like DistilBERT), the general strategy to achieve better performance is by increasing the models' sizes as well as the amount of data they are pretrained on. - -
-Number of parameters of recent Transformers models -
- -Unfortunately, training a model, especially a large one, requires a large amount of data. This becomes very costly in terms of time and compute resources. It even translates to environmental impact, as can be seen in the following graph. - -
-The carbon footprint of a large language model. - -
- - - -And this is showing a project for a (very big) model led by a team consciously trying to reduce the environmental impact of pretraining. The footprint of running lots of trials to get the best hyperparameters would be even higher. - -Imagine if each time a research team, a student organization, or a company wanted to train a model, it did so from scratch. This would lead to huge, unnecessary global costs! - -This is why sharing language models is paramount: sharing the trained weights and building on top of already trained weights reduces the overall compute cost and carbon footprint of the community. - -By the way, you can evaluate the carbon footprint of your models' training through several tools. For example [ML CO2 Impact](https://mlco2.github.io/impact/) or [Code Carbon]( https://codecarbon.io/) which is integrated in 🤗 Transformers. To learn more about this, you can read this [blog post](https://huggingface.co/blog/carbon-emissions-on-the-hub) which will show you how to generate an `emissions.csv` file with an estimate of the footprint of your training, as well as the [documentation](https://huggingface.co/docs/hub/model-cards-co2) of 🤗 Transformers addressing this topic. - - -## Transfer Learning[[transfer-learning]] - - - -*Pretraining* is the act of training a model from scratch: the weights are randomly initialized, and the training starts without any prior knowledge. - -
-The pretraining of a language model is costly in both time and money. - -
- -This pretraining is usually done on very large amounts of data. Therefore, it requires a very large corpus of data, and training can take up to several weeks. - -*Fine-tuning*, on the other hand, is the training done **after** a model has been pretrained. To perform fine-tuning, you first acquire a pretrained language model, then perform additional training with a dataset specific to your task. Wait -- why not simply train the model for your final use case from the start (**scratch**)? There are a couple of reasons: - -* The pretrained model was already trained on a dataset that has some similarities with the fine-tuning dataset. The fine-tuning process is thus able to take advantage of knowledge acquired by the initial model during pretraining (for instance, with NLP problems, the pretrained model will have some kind of statistical understanding of the language you are using for your task). -* Since the pretrained model was already trained on lots of data, the fine-tuning requires way less data to get decent results. -* For the same reason, the amount of time and resources needed to get good results are much lower. - -For example, one could leverage a pretrained model trained on the English language and then fine-tune it on an arXiv corpus, resulting in a science/research-based model. The fine-tuning will only require a limited amount of data: the knowledge the pretrained model has acquired is "transferred," hence the term *transfer learning*. - -
-The fine-tuning of a language model is cheaper than pretraining in both time and money. - -
- -Fine-tuning a model therefore has lower time, data, financial, and environmental costs. It is also quicker and easier to iterate over different fine-tuning schemes, as the training is less constraining than a full pretraining. - -This process will also achieve better results than training from scratch (unless you have lots of data), which is why you should always try to leverage a pretrained model -- one as close as possible to the task you have at hand -- and fine-tune it. - -## General Transformer architecture[[general-transformer-architecture]] - -In this section, we'll go over the general architecture of the Transformer model. Don't worry if you don't understand some of the concepts; there are detailed sections later covering each of the components. - - - -The model is primarily composed of two blocks: - -* **Encoder (left)**: The encoder receives an input and builds a representation of it (its features). This means that the model is optimized to acquire understanding from the input. -* **Decoder (right)**: The decoder uses the encoder's representation (features) along with other inputs to generate a target sequence. This means that the model is optimized for generating outputs. - -
-Architecture of a Transformers models - -
- -Each of these parts can be used independently, depending on the task: - -* **Encoder-only models**: Good for tasks that require understanding of the input, such as sentence classification and named entity recognition. -* **Decoder-only models**: Good for generative tasks such as text generation. -* **Encoder-decoder models** or **sequence-to-sequence models**: Good for generative tasks that require an input, such as translation or summarization. - -We will dive into those architectures independently in later sections. - -## Attention layers[[attention-layers]] - -A key feature of Transformer models is that they are built with special layers called *attention layers*. In fact, the title of the paper introducing the Transformer architecture was ["Attention Is All You Need"](https://arxiv.org/abs/1706.03762)! We will explore the details of attention layers later in the course; for now, all you need to know is that this layer will tell the model to pay specific attention to certain words in the sentence you passed it (and more or less ignore the others) when dealing with the representation of each word. - -To put this into context, consider the task of translating text from English to French. Given the input "You like this course", a translation model will need to also attend to the adjacent word "You" to get the proper translation for the word "like", because in French the verb "like" is conjugated differently depending on the subject. The rest of the sentence, however, is not useful for the translation of that word. In the same vein, when translating "this" the model will also need to pay attention to the word "course", because "this" translates differently depending on whether the associated noun is masculine or feminine. Again, the other words in the sentence will not matter for the translation of "course". With more complex sentences (and more complex grammar rules), the model would need to pay special attention to words that might appear farther away in the sentence to properly translate each word. - -The same concept applies to any task associated with natural language: a word by itself has a meaning, but that meaning is deeply affected by the context, which can be any other word (or words) before or after the word being studied. - -Now that you have an idea of what attention layers are all about, let's take a closer look at the Transformer architecture. - -## The original architecture[[the-original-architecture]] - -The Transformer architecture was originally designed for translation. During training, the encoder receives inputs (sentences) in a certain language, while the decoder receives the same sentences in the desired target language. In the encoder, the attention layers can use all the words in a sentence (since, as we just saw, the translation of a given word can be dependent on what is after as well as before it in the sentence). The decoder, however, works sequentially and can only pay attention to the words in the sentence that it has already translated (so, only the words before the word currently being generated). For example, when we have predicted the first three words of the translated target, we give them to the decoder which then uses all the inputs of the encoder to try to predict the fourth word. - -To speed things up during training (when the model has access to target sentences), the decoder is fed the whole target, but it is not allowed to use future words (if it had access to the word at position 2 when trying to predict the word at position 2, the problem would not be very hard!). For instance, when trying to predict the fourth word, the attention layer will only have access to the words in positions 1 to 3. - -The original Transformer architecture looked like this, with the encoder on the left and the decoder on the right: - -
-Architecture of a Transformers models - -
- -Note that the first attention layer in a decoder block pays attention to all (past) inputs to the decoder, but the second attention layer uses the output of the encoder. It can thus access the whole input sentence to best predict the current word. This is very useful as different languages can have grammatical rules that put the words in different orders, or some context provided later in the sentence may be helpful to determine the best translation of a given word. - -The *attention mask* can also be used in the encoder/decoder to prevent the model from paying attention to some special words -- for instance, the special padding word used to make all the inputs the same length when batching together sentences. - -## Architectures vs. checkpoints[[architecture-vs-checkpoints]] - -As we dive into Transformer models in this course, you'll see mentions of *architectures* and *checkpoints* as well as *models*. These terms all have slightly different meanings: - -* **Architecture**: This is the skeleton of the model -- the definition of each layer and each operation that happens within the model. -* **Checkpoints**: These are the weights that will be loaded in a given architecture. -* **Model**: This is an umbrella term that isn't as precise as "architecture" or "checkpoint": it can mean both. This course will specify *architecture* or *checkpoint* when it matters to reduce ambiguity. - -For example, BERT is an architecture while `bert-base-cased`, a set of weights trained by the Google team for the first release of BERT, is a checkpoint. However, one can say "the BERT model" and "the `bert-base-cased` model." +# How do Transformers work?[[how-do-transformers-work]] + + + +In this section, we will take a look at the architecture of Transformer models and dive deeper into the concepts of attention, encoder-decoder architecture, and more. + +> [!WARNING] +> 🚀 We're taking things up a notch here. This section is detailed and technical, so don't worry if you don't understand everything right away. We'll come back to these concepts later in the course. + +## A bit of Transformer history[[a-bit-of-transformer-history]] + +Here are some reference points in the (short) history of Transformer models: + +
+A brief chronology of Transformers models. + +
+ +The [Transformer architecture](https://arxiv.org/abs/1706.03762) was introduced in June 2017. The focus of the original research was on translation tasks. This was followed by the introduction of several influential models, including: + +- **June 2018**: [GPT](https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf), the first pretrained Transformer model, used for fine-tuning on various NLP tasks and obtained state-of-the-art results + +- **October 2018**: [BERT](https://arxiv.org/abs/1810.04805), another large pretrained model, this one designed to produce better summaries of sentences (more on this in the next chapter!) + +- **February 2019**: [GPT-2](https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf), an improved (and bigger) version of GPT that was not immediately publicly released due to ethical concerns + +- **October 2019**: [T5](https://huggingface.co/papers/1910.10683), A multi-task focused implementation of the sequence-to-sequence Transformer architecture. + +- **May 2020**, [GPT-3](https://huggingface.co/papers/2005.14165), an even bigger version of GPT-2 that is able to perform well on a variety of tasks without the need for fine-tuning (called _zero-shot learning_) + +- **January 2022**: [InstructGPT](https://huggingface.co/papers/2203.02155), a version of GPT-3 that was trained to follow instructions better. + +- **January 2023**: [Llama](https://huggingface.co/papers/2302.13971), a large language model that is able to generate text in a variety of languages. + +- **March 2023**: [Mistral](https://huggingface.co/papers/2310.06825), a 7-billion-parameter language model that outperforms Llama 2 13B across all evaluated benchmarks, leveraging grouped-query attention for faster inference and sliding window attention to handle sequences of arbitrary length. + +- **May 2024**: [Gemma 2](https://huggingface.co/papers/2408.00118), a family of lightweight, state-of-the-art open models ranging from 2B to 27B parameters that incorporate interleaved local-global attentions and group-query attention, with smaller models trained using knowledge distillation to deliver performance competitive with models 2-3 times larger. + +- **November 2024**: [SmolLM2](https://huggingface.co/papers/2502.02737), a state-of-the-art small language model (135 million to 1.7 billion parameters) that achieves impressive performance despite its compact size, and unlocking new possibilities for mobile and edge devices. + +This list is far from comprehensive, and is just meant to highlight a few of the different kinds of Transformer models. Broadly, they can be grouped into three categories: + +- GPT-like (also called _auto-regressive_ Transformer models) +- BERT-like (also called _auto-encoding_ Transformer models) +- T5-like (also called _sequence-to-sequence_ Transformer models) + +We will dive into these families in more depth later on. + +## Transformers are language models[[transformers-are-language-models]] + +All the Transformer models mentioned above (GPT, BERT, T5, etc.) have been trained as *language models*. This means they have been trained on large amounts of raw text in a self-supervised fashion. + +Self-supervised learning is a type of training in which the objective is automatically computed from the inputs of the model. That means that humans are not needed to label the data! + +This type of model develops a statistical understanding of the language it has been trained on, but it's less useful for specific practical tasks. Because of this, the general pretrained model then goes through a process called *transfer learning* or *fine-tuning*. During this process, the model is fine-tuned in a supervised way -- that is, using human-annotated labels -- on a given task. + +An example of a task is predicting the next word in a sentence having read the *n* previous words. This is called *causal language modeling* because the output depends on the past and present inputs, but not the future ones. + +
+Example of causal language modeling in which the next word from a sentence is predicted. + +
+ +Another example is *masked language modeling*, in which the model predicts a masked word in the sentence. + +
+Example of masked language modeling in which a masked word from a sentence is predicted. + +
+ +## Transformers are big models[[transformers-are-big-models]] + +Apart from a few outliers (like DistilBERT), the general strategy to achieve better performance is by increasing the models' sizes as well as the amount of data they are pretrained on. + +
+Number of parameters of recent Transformers models +
+ +Unfortunately, training a model, especially a large one, requires a large amount of data. This becomes very costly in terms of time and compute resources. It even translates to environmental impact, as can be seen in the following graph. + +
+The carbon footprint of a large language model. + +
+ + + +And this is showing a project for a (very big) model led by a team consciously trying to reduce the environmental impact of pretraining. The footprint of running lots of trials to get the best hyperparameters would be even higher. + +Imagine if each time a research team, a student organization, or a company wanted to train a model, it did so from scratch. This would lead to huge, unnecessary global costs! + +This is why sharing language models is paramount: sharing the trained weights and building on top of already trained weights reduces the overall compute cost and carbon footprint of the community. + +By the way, you can evaluate the carbon footprint of your models' training through several tools. For example [ML CO2 Impact](https://mlco2.github.io/impact/) or [Code Carbon]( https://codecarbon.io/) which is integrated in 🤗 Transformers. To learn more about this, you can read this [blog post](https://huggingface.co/blog/carbon-emissions-on-the-hub) which will show you how to generate an `emissions.csv` file with an estimate of the footprint of your training, as well as the [documentation](https://huggingface.co/docs/hub/model-cards-co2) of 🤗 Transformers addressing this topic. + + +## Transfer Learning[[transfer-learning]] + + + +*Pretraining* is the act of training a model from scratch: the weights are randomly initialized, and the training starts without any prior knowledge. + +
+The pretraining of a language model is costly in both time and money. + +
+ +This pretraining is usually done on very large amounts of data. Therefore, it requires a very large corpus of data, and training can take up to several weeks. + +*Fine-tuning*, on the other hand, is the training done **after** a model has been pretrained. To perform fine-tuning, you first acquire a pretrained language model, then perform additional training with a dataset specific to your task. Wait -- why not simply train the model for your final use case from the start (**scratch**)? There are a couple of reasons: + +* The pretrained model was already trained on a dataset that has some similarities with the fine-tuning dataset. The fine-tuning process is thus able to take advantage of knowledge acquired by the initial model during pretraining (for instance, with NLP problems, the pretrained model will have some kind of statistical understanding of the language you are using for your task). +* Since the pretrained model was already trained on lots of data, the fine-tuning requires way less data to get decent results. +* For the same reason, the amount of time and resources needed to get good results are much lower. + +For example, one could leverage a pretrained model trained on the English language and then fine-tune it on an arXiv corpus, resulting in a science/research-based model. The fine-tuning will only require a limited amount of data: the knowledge the pretrained model has acquired is "transferred," hence the term *transfer learning*. + +
+The fine-tuning of a language model is cheaper than pretraining in both time and money. + +
+ +Fine-tuning a model therefore has lower time, data, financial, and environmental costs. It is also quicker and easier to iterate over different fine-tuning schemes, as the training is less constraining than a full pretraining. + +This process will also achieve better results than training from scratch (unless you have lots of data), which is why you should always try to leverage a pretrained model -- one as close as possible to the task you have at hand -- and fine-tune it. + +## General Transformer architecture[[general-transformer-architecture]] + +In this section, we'll go over the general architecture of the Transformer model. Don't worry if you don't understand some of the concepts; there are detailed sections later covering each of the components. + + + +The model is primarily composed of two blocks: + +* **Encoder (left)**: The encoder receives an input and builds a representation of it (its features). This means that the model is optimized to acquire understanding from the input. +* **Decoder (right)**: The decoder uses the encoder's representation (features) along with other inputs to generate a target sequence. This means that the model is optimized for generating outputs. + +
+Architecture of a Transformers models + +
+ +Each of these parts can be used independently, depending on the task: + +* **Encoder-only models**: Good for tasks that require understanding of the input, such as sentence classification and named entity recognition. +* **Decoder-only models**: Good for generative tasks such as text generation. +* **Encoder-decoder models** or **sequence-to-sequence models**: Good for generative tasks that require an input, such as translation or summarization. + +We will dive into those architectures independently in later sections. + +## Attention layers[[attention-layers]] + +A key feature of Transformer models is that they are built with special layers called *attention layers*. In fact, the title of the paper introducing the Transformer architecture was ["Attention Is All You Need"](https://arxiv.org/abs/1706.03762)! We will explore the details of attention layers later in the course; for now, all you need to know is that this layer will tell the model to pay specific attention to certain words in the sentence you passed it (and more or less ignore the others) when dealing with the representation of each word. + +To put this into context, consider the task of translating text from English to French. Given the input "You like this course", a translation model will need to also attend to the adjacent word "You" to get the proper translation for the word "like", because in French the verb "like" is conjugated differently depending on the subject. The rest of the sentence, however, is not useful for the translation of that word. In the same vein, when translating "this" the model will also need to pay attention to the word "course", because "this" translates differently depending on whether the associated noun is masculine or feminine. Again, the other words in the sentence will not matter for the translation of "course". With more complex sentences (and more complex grammar rules), the model would need to pay special attention to words that might appear farther away in the sentence to properly translate each word. + +The same concept applies to any task associated with natural language: a word by itself has a meaning, but that meaning is deeply affected by the context, which can be any other word (or words) before or after the word being studied. + +Now that you have an idea of what attention layers are all about, let's take a closer look at the Transformer architecture. + +## The original architecture[[the-original-architecture]] + +The Transformer architecture was originally designed for translation. During training, the encoder receives inputs (sentences) in a certain language, while the decoder receives the same sentences in the desired target language. In the encoder, the attention layers can use all the words in a sentence (since, as we just saw, the translation of a given word can be dependent on what is after as well as before it in the sentence). The decoder, however, works sequentially and can only pay attention to the words in the sentence that it has already translated (so, only the words before the word currently being generated). For example, when we have predicted the first three words of the translated target, we give them to the decoder which then uses all the inputs of the encoder to try to predict the fourth word. + +To speed things up during training (when the model has access to target sentences), the decoder is fed the whole target, but it is not allowed to use future words (if it had access to the word at position 2 when trying to predict the word at position 2, the problem would not be very hard!). For instance, when trying to predict the fourth word, the attention layer will only have access to the words in positions 1 to 3. + +The original Transformer architecture looked like this, with the encoder on the left and the decoder on the right: + +
+Architecture of a Transformers models + +
+ +Note that the first attention layer in a decoder block pays attention to all (past) inputs to the decoder, but the second attention layer uses the output of the encoder. It can thus access the whole input sentence to best predict the current word. This is very useful as different languages can have grammatical rules that put the words in different orders, or some context provided later in the sentence may be helpful to determine the best translation of a given word. + +The *attention mask* can also be used in the encoder/decoder to prevent the model from paying attention to some special words -- for instance, the special padding word used to make all the inputs the same length when batching together sentences. + +## Architectures vs. checkpoints[[architecture-vs-checkpoints]] + +As we dive into Transformer models in this course, you'll see mentions of *architectures* and *checkpoints* as well as *models*. These terms all have slightly different meanings: + +* **Architecture**: This is the skeleton of the model -- the definition of each layer and each operation that happens within the model. +* **Checkpoints**: These are the weights that will be loaded in a given architecture. +* **Model**: This is an umbrella term that isn't as precise as "architecture" or "checkpoint": it can mean both. This course will specify *architecture* or *checkpoint* when it matters to reduce ambiguity. + +For example, BERT is an architecture while `bert-base-cased`, a set of weights trained by the Google team for the first release of BERT, is a checkpoint. However, one can say "the BERT model" and "the `bert-base-cased` model." diff --git a/chapters/en/chapter1/5.mdx b/chapters/en/chapter1/5.mdx index f00f6643b..d305202c6 100644 --- a/chapters/en/chapter1/5.mdx +++ b/chapters/en/chapter1/5.mdx @@ -1,235 +1,235 @@ -# How 🤗 Transformers solve tasks - - - -In [Transformers, what can they do?](/course/chapter1/3), you learned about natural language processing (NLP), speech and audio, computer vision tasks, and some important applications of them. This page will look closely at how models solve these tasks and explain what's happening under the hood. There are many ways to solve a given task, some models may implement certain techniques or even approach the task from a new angle, but for Transformer models, the general idea is the same. Owing to its flexible architecture, most models are a variant of an encoder, a decoder, or an encoder-decoder structure. - -> [!TIP] -> Before diving into specific architectural variants, it's helpful to understand that most tasks follow a similar pattern: input data is processed through a model, and the output is interpreted for a specific task. The differences lie in how the data is prepared, what model architecture variant is used, and how the output is processed. - -To explain how tasks are solved, we'll walk through what goes on inside the model to output useful predictions. We'll cover the following models and their corresponding tasks: - -- [Wav2Vec2](https://huggingface.co/docs/transformers/model_doc/wav2vec2) for audio classification and automatic speech recognition (ASR) -- [Vision Transformer (ViT)](https://huggingface.co/docs/transformers/model_doc/vit) and [ConvNeXT](https://huggingface.co/docs/transformers/model_doc/convnext) for image classification -- [DETR](https://huggingface.co/docs/transformers/model_doc/detr) for object detection -- [Mask2Former](https://huggingface.co/docs/transformers/model_doc/mask2former) for image segmentation -- [GLPN](https://huggingface.co/docs/transformers/model_doc/glpn) for depth estimation -- [BERT](https://huggingface.co/docs/transformers/model_doc/bert) for NLP tasks like text classification, token classification and question answering that use an encoder -- [GPT2](https://huggingface.co/docs/transformers/model_doc/gpt2) for NLP tasks like text generation that use a decoder -- [BART](https://huggingface.co/docs/transformers/model_doc/bart) for NLP tasks like summarization and translation that use an encoder-decoder - -> [!TIP] -> Before you go further, it is good to have some basic knowledge of the original Transformer architecture. Knowing how encoders, decoders, and attention work will aid you in understanding how different Transformer models work. Be sure to check out our [the previous section](https://huggingface.co/course/chapter1/4?fw=pt) for more information! - -## Transformer models for language - -Language models are at the heart of modern NLP. They're designed to understand and generate human language by learning the statistical patterns and relationships between words or tokens in text. - -The Transformer was initially designed for machine translation, and since then, it has become the default architecture for solving all AI tasks. Some tasks lend themselves to the Transformer's encoder structure, while others are better suited for the decoder. Still, other tasks make use of both the Transformer's encoder-decoder structure. - -### How language models work - -Language models work by being trained to predict the probability of a word given the context of surrounding words. This gives them a foundational understanding of language that can generalize to other tasks. - -There are two main approaches for training a transformer model: - -1. **Masked language modeling (MLM)**: Used by encoder models like BERT, this approach randomly masks some tokens in the input and trains the model to predict the original tokens based on the surrounding context. This allows the model to learn bidirectional context (looking at words both before and after the masked word). - -2. **Causal language modeling (CLM)**: Used by decoder models like GPT, this approach predicts the next token based on all previous tokens in the sequence. The model can only use context from the left (previous tokens) to predict the next token. - -### Types of language models - -In the Transformers library, language models generally fall into three architectural categories: - -1. **Encoder-only models** (like BERT): These models use a bidirectional approach to understand context from both directions. They're best suited for tasks that require deep understanding of text, such as classification, named entity recognition, and question answering. - -2. **Decoder-only models** (like GPT, Llama): These models process text from left to right and are particularly good at text generation tasks. They can complete sentences, write essays, or even generate code based on a prompt. - -3. **Encoder-decoder models** (like T5, BART): These models combine both approaches, using an encoder to understand the input and a decoder to generate output. They excel at sequence-to-sequence tasks like translation, summarization, and question answering. - -![transformer-models-for-language](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter1/transformers_architecture.png) - -As we covered in the previous section, language models are typically pretrained on large amounts of text data in a self-supervised manner (without human annotations), then fine-tuned on specific tasks. This approach, known as transfer learning, allows these models to adapt to many different NLP tasks with relatively small amounts of task-specific data. - -In the following sections, we'll explore specific model architectures and how they're applied to various tasks across speech, vision, and text domains. - -> [!TIP] -> Understanding which part of the Transformer architecture (encoder, decoder, or both) is best suited for a particular NLP task is key to choosing the right model. Generally, tasks requiring bidirectional context use encoders, tasks generating text use decoders, and tasks converting one sequence to another use encoder-decoders. - -### Text generation - -Text generation involves creating coherent and contextually relevant text based on a prompt or input. - -[GPT-2](https://huggingface.co/docs/transformers/model_doc/gpt2) is a decoder-only model pretrained on a large amount of text. It can generate convincing (though not always true!) text given a prompt and complete other NLP tasks like question answering despite not being explicitly trained to. - -
- -
- -1. GPT-2 uses [byte pair encoding (BPE)](https://huggingface.co/docs/transformers/tokenizer_summary#bytepair-encoding-bpe) to tokenize words and generate a token embedding. Positional encodings are added to the token embeddings to indicate the position of each token in the sequence. The input embeddings are passed through multiple decoder blocks to output some final hidden state. Within each decoder block, GPT-2 uses a *masked self-attention* layer which means GPT-2 can't attend to future tokens. It is only allowed to attend to tokens on the left. This is different from BERT's [`mask`] token because, in masked self-attention, an attention mask is used to set the score to `0` for future tokens. - -2. The output from the decoder is passed to a language modeling head, which performs a linear transformation to convert the hidden states into logits. The label is the next token in the sequence, which are created by shifting the logits to the right by one. The cross-entropy loss is calculated between the shifted logits and the labels to output the next most likely token. - -GPT-2's pretraining objective is based entirely on [causal language modeling](https://huggingface.co/docs/transformers/glossary#causal-language-modeling), predicting the next word in a sequence. This makes GPT-2 especially good at tasks that involve generating text. - -Ready to try your hand at text generation? Check out our complete [causal language modeling guide](https://huggingface.co/docs/transformers/tasks/language_modeling#causal-language-modeling) to learn how to finetune DistilGPT-2 and use it for inference! - -> [!TIP] -> For more information about text generation, check out the [text generation strategies](https://huggingface.co/docs/transformers/generation_strategies#generation-strategies) guide! - -### Text classification - -Text classification involves assigning predefined categories to text documents, such as sentiment analysis, topic classification, or spam detection. - -[BERT](https://huggingface.co/docs/transformers/model_doc/bert) is an encoder-only model and is the first model to effectively implement deep bidirectionality to learn richer representations of the text by attending to words on both sides. - -1. BERT uses [WordPiece](https://huggingface.co/docs/transformers/tokenizer_summary#wordpiece) tokenization to generate a token embedding of the text. To tell the difference between a single sentence and a pair of sentences, a special `[SEP]` token is added to differentiate them. A special `[CLS]` token is added to the beginning of every sequence of text. The final output with the `[CLS]` token is used as the input to the classification head for classification tasks. BERT also adds a segment embedding to denote whether a token belongs to the first or second sentence in a pair of sentences. - -2. BERT is pretrained with two objectives: masked language modeling and next-sentence prediction. In masked language modeling, some percentage of the input tokens are randomly masked, and the model needs to predict these. This solves the issue of bidirectionality, where the model could cheat and see all the words and "predict" the next word. The final hidden states of the predicted mask tokens are passed to a feedforward network with a softmax over the vocabulary to predict the masked word. - - The second pretraining object is next-sentence prediction. The model must predict whether sentence B follows sentence A. Half of the time sentence B is the next sentence, and the other half of the time, sentence B is a random sentence. The prediction, whether it is the next sentence or not, is passed to a feedforward network with a softmax over the two classes (`IsNext` and `NotNext`). - -3. The input embeddings are passed through multiple encoder layers to output some final hidden states. - -To use the pretrained model for text classification, add a sequence classification head on top of the base BERT model. The sequence classification head is a linear layer that accepts the final hidden states and performs a linear transformation to convert them into logits. The cross-entropy loss is calculated between the logits and target to find the most likely label. - -Ready to try your hand at text classification? Check out our complete [text classification guide](https://huggingface.co/docs/transformers/tasks/sequence_classification) to learn how to finetune DistilBERT and use it for inference! - -### Token classification - -Token classification involves assigning a label to each token in a sequence, such as in named entity recognition or part-of-speech tagging. - -To use BERT for token classification tasks like named entity recognition (NER), add a token classification head on top of the base BERT model. The token classification head is a linear layer that accepts the final hidden states and performs a linear transformation to convert them into logits. The cross-entropy loss is calculated between the logits and each token to find the most likely label. - -Ready to try your hand at token classification? Check out our complete [token classification guide](https://huggingface.co/docs/transformers/tasks/token_classification) to learn how to finetune DistilBERT and use it for inference! - -### Question answering - -Question answering involves finding the answer to a question within a given context or passage. - -To use BERT for question answering, add a span classification head on top of the base BERT model. This linear layer accepts the final hidden states and performs a linear transformation to compute the `span` start and end logits corresponding to the answer. The cross-entropy loss is calculated between the logits and the label position to find the most likely span of text corresponding to the answer. - -Ready to try your hand at question answering? Check out our complete [question answering guide](https://huggingface.co/docs/transformers/tasks/question_answering) to learn how to finetune DistilBERT and use it for inference! - -> [!TIP] -> 💡 Notice how easy it is to use BERT for different tasks once it's been pretrained. You only need to add a specific head to the pretrained model to manipulate the hidden states into your desired output! - -### Summarization - -Summarization involves condensing a longer text into a shorter version while preserving its key information and meaning. - -Encoder-decoder models like [BART](https://huggingface.co/docs/transformers/model_doc/bart) and [T5](model_doc/t5) are designed for the sequence-to-sequence pattern of a summarization task. We'll explain how BART works in this section, and then you can try finetuning T5 at the end. - -
- -
- -1. BART's encoder architecture is very similar to BERT and accepts a token and positional embedding of the text. BART is pretrained by corrupting the input and then reconstructing it with the decoder. Unlike other encoders with specific corruption strategies, BART can apply any type of corruption. The *text infilling* corruption strategy works the best though. In text infilling, a number of text spans are replaced with a **single** [`mask`] token. This is important because the model has to predict the masked tokens, and it teaches the model to predict the number of missing tokens. The input embeddings and masked spans are passed through the encoder to output some final hidden states, but unlike BERT, BART doesn't add a final feedforward network at the end to predict a word. - -2. The encoder's output is passed to the decoder, which must predict the masked tokens and any uncorrupted tokens from the encoder's output. This gives additional context to help the decoder restore the original text. The output from the decoder is passed to a language modeling head, which performs a linear transformation to convert the hidden states into logits. The cross-entropy loss is calculated between the logits and the label, which is just the token shifted to the right. - -Ready to try your hand at summarization? Check out our complete [summarization guide](https://huggingface.co/docs/transformers/tasks/summarization) to learn how to finetune T5 and use it for inference! - -> [!TIP] -> For more information about text generation, check out the [text generation strategies](https://huggingface.co/docs/transformers/generation_strategies) guide! - -### Translation - -Translation involves converting text from one language to another while preserving its meaning. Translation is another example of a sequence-to-sequence task, which means you can use an encoder-decoder model like [BART](https://huggingface.co/docs/transformers/model_doc/bart) or [T5](model_doc/t5) to do it. We'll explain how BART works in this section, and then you can try finetuning T5 at the end. - -BART adapts to translation by adding a separate randomly initialized encoder to map a source language to an input that can be decoded into the target language. This new encoder's embeddings are passed to the pretrained encoder instead of the original word embeddings. The source encoder is trained by updating the source encoder, positional embeddings, and input embeddings with the cross-entropy loss from the model output. The model parameters are frozen in this first step, and all the model parameters are trained together in the second step. -BART has since been followed up by a multilingual version, mBART, intended for translation and pretrained on many different languages. - -Ready to try your hand at translation? Check out our complete [translation guide](https://huggingface.co/docs/transformers/tasks/translation) to learn how to finetune T5 and use it for inference! - -> [!TIP] -> As you've seen throughout this guide, many models follow similar patterns despite addressing different tasks. Understanding these common patterns can help you quickly grasp how new models work and how to adapt existing models to your specific needs. - -## Modalities beyond text - -Transformers are not limited to text. They can also be applied to other modalities like speech and audio, images, and video. Of course, on this course we will focus on text, but we can briefly introduce the other modalities. - -### Speech and audio - -Let's start by exploring how Transformer models handle speech and audio data, which presents unique challenges compared to text or images. - -[Whisper](https://huggingface.co/docs/transformers/main/en/model_doc/whisper) is a encoder-decoder (sequence-to-sequence) transformer pretrained on 680,000 hours of labeled audio data. This amount of pretraining data enables zero-shot performance on audio tasks in English and many other languages. The decoder allows Whisper to map the encoders learned speech representations to useful outputs, such as text, without additional fine-tuning. Whisper just works out of the box. - -
- -
- -Diagram is from [Whisper paper](https://huggingface.co/papers/2212.04356). - -This model has two main components: - -1. An **encoder** processes the input audio. The raw audio is first converted into a log-Mel spectrogram. This spectrogram is then passed through a Transformer encoder network. - -2. A **decoder** takes the encoded audio representation and autoregressively predicts the corresponding text tokens. It's a standard Transformer decoder trained to predict the next text token given the previous tokens and the encoder output. Special tokens are used at the beginning of the decoder input to steer the model towards specific tasks like transcription, translation, or language identification. - -Whisper was pretrained on a massive and diverse dataset of 680,000 hours of labeled audio data collected from the web. This large-scale, weakly supervised pretraining is the key to its strong zero-shot performance across many languages and tasks. - -Now that Whisper is pretrained, you can use it directly for zero-shot inference or finetune it on your data for improved performance on specific tasks like automatic speech recognition or speech translation! - -> [!TIP] -> The key innovation in Whisper is its training on an unprecedented scale of diverse, weakly supervised audio data from the internet. This allows it to generalize remarkably well to different languages, accents, and tasks without task-specific finetuning. - -### Automatic speech recognition - -To use the pretrained model for automatic speech recognition, you leverage its full encoder-decoder structure. The encoder processes the audio input, and the decoder autoregressively generates the transcript token by token. When fine-tuning, the model is typically trained using a standard sequence-to-sequence loss (like cross-entropy) to predict the correct text tokens based on the audio input. - -The easiest way to use a fine-tuned model for inference is within a `pipeline`. - -```python -from transformers import pipeline - -transcriber = pipeline( - task="automatic-speech-recognition", model="openai/whisper-base.en" -) -transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac") -# Output: {'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'} -``` - -Ready to try your hand at automatic speech recognition? Check out our complete [automatic speech recognition guide](https://huggingface.co/docs/transformers/tasks/asr) to learn how to finetune Whisper and use it for inference! - -### Computer vision - -Now let's move on to computer vision tasks, which deal with understanding and interpreting visual information from images or videos. - -There are two ways to approach computer vision tasks: - -1. Split an image into a sequence of patches and process them in parallel with a Transformer. -2. Use a modern CNN, like [ConvNeXT](https://huggingface.co/docs/transformers/model_doc/convnext), which relies on convolutional layers but adopts modern network designs. - -> [!TIP] -> A third approach mixes Transformers with convolutions (for example, [Convolutional Vision Transformer](https://huggingface.co/docs/transformers/model_doc/cvt) or [LeViT](https://huggingface.co/docs/transformers/model_doc/levit)). We won't discuss those because they just combine the two approaches we examine here. - -ViT and ConvNeXT are commonly used for image classification, but for other vision tasks like object detection, segmentation, and depth estimation, we'll look at DETR, Mask2Former and GLPN, respectively; these models are better suited for those tasks. - -### Image classification - -Image classification is one of the fundamental computer vision tasks. Let's see how different model architectures approach this problem. - -ViT and ConvNeXT can both be used for image classification; the main difference is that ViT uses an attention mechanism while ConvNeXT uses convolutions. - -[ViT](https://huggingface.co/docs/transformers/model_doc/vit) replaces convolutions entirely with a pure Transformer architecture. If you're familiar with the original Transformer, then you're already most of the way toward understanding ViT. - -
- -
- -The main change ViT introduced was in how images are fed to a Transformer: - -1. An image is split into square non-overlapping patches, each of which gets turned into a vector or *patch embedding*. The patch embeddings are generated from a convolutional 2D layer which creates the proper input dimensions (which for a base Transformer is 768 values for each patch embedding). If you had a 224x224 pixel image, you could split it into 196 16x16 image patches. Just like how text is tokenized into words, an image is "tokenized" into a sequence of patches. - -2. A *learnable embedding* - a special `[CLS]` token - is added to the beginning of the patch embeddings just like BERT. The final hidden state of the `[CLS]` token is used as the input to the attached classification head; other outputs are ignored. This token helps the model learn how to encode a representation of the image. - -3. The last thing to add to the patch and learnable embeddings are the *position embeddings* because the model doesn't know how the image patches are ordered. The position embeddings are also learnable and have the same size as the patch embeddings. Finally, all of the embeddings are passed to the Transformer encoder. - -4. The output, specifically only the output with the `[CLS]` token, is passed to a multilayer perceptron head (MLP). ViT's pretraining objective is simply classification. Like other classification heads, the MLP head converts the output into logits over the class labels and calculates the cross-entropy loss to find the most likely class. - -Ready to try your hand at image classification? Check out our complete [image classification guide](https://huggingface.co/docs/transformers/tasks/image_classification) to learn how to fine-tune ViT and use it for inference! - - -> [!TIP] -> Notice the parallel between ViT and BERT: both use a special token ([CLS]) to capture the overall representation, both add position information to their embeddings, and both use a Transformer encoder to process the sequence of tokens/patches. +# How 🤗 Transformers solve tasks + + + +In [Transformers, what can they do?](/course/chapter1/3), you learned about natural language processing (NLP), speech and audio, computer vision tasks, and some important applications of them. This page will look closely at how models solve these tasks and explain what's happening under the hood. There are many ways to solve a given task, some models may implement certain techniques or even approach the task from a new angle, but for Transformer models, the general idea is the same. Owing to its flexible architecture, most models are a variant of an encoder, a decoder, or an encoder-decoder structure. + +> [!TIP] +> Before diving into specific architectural variants, it's helpful to understand that most tasks follow a similar pattern: input data is processed through a model, and the output is interpreted for a specific task. The differences lie in how the data is prepared, what model architecture variant is used, and how the output is processed. + +To explain how tasks are solved, we'll walk through what goes on inside the model to output useful predictions. We'll cover the following models and their corresponding tasks: + +- [Wav2Vec2](https://huggingface.co/docs/transformers/model_doc/wav2vec2) for audio classification and automatic speech recognition (ASR) +- [Vision Transformer (ViT)](https://huggingface.co/docs/transformers/model_doc/vit) and [ConvNeXT](https://huggingface.co/docs/transformers/model_doc/convnext) for image classification +- [DETR](https://huggingface.co/docs/transformers/model_doc/detr) for object detection +- [Mask2Former](https://huggingface.co/docs/transformers/model_doc/mask2former) for image segmentation +- [GLPN](https://huggingface.co/docs/transformers/model_doc/glpn) for depth estimation +- [BERT](https://huggingface.co/docs/transformers/model_doc/bert) for NLP tasks like text classification, token classification and question answering that use an encoder +- [GPT2](https://huggingface.co/docs/transformers/model_doc/gpt2) for NLP tasks like text generation that use a decoder +- [BART](https://huggingface.co/docs/transformers/model_doc/bart) for NLP tasks like summarization and translation that use an encoder-decoder + +> [!TIP] +> Before you go further, it is good to have some basic knowledge of the original Transformer architecture. Knowing how encoders, decoders, and attention work will aid you in understanding how different Transformer models work. Be sure to check out our [the previous section](https://huggingface.co/course/chapter1/4?fw=pt) for more information! + +## Transformer models for language + +Language models are at the heart of modern NLP. They're designed to understand and generate human language by learning the statistical patterns and relationships between words or tokens in text. + +The Transformer was initially designed for machine translation, and since then, it has become the default architecture for solving all AI tasks. Some tasks lend themselves to the Transformer's encoder structure, while others are better suited for the decoder. Still, other tasks make use of both the Transformer's encoder-decoder structure. + +### How language models work + +Language models work by being trained to predict the probability of a word given the context of surrounding words. This gives them a foundational understanding of language that can generalize to other tasks. + +There are two main approaches for training a transformer model: + +1. **Masked language modeling (MLM)**: Used by encoder models like BERT, this approach randomly masks some tokens in the input and trains the model to predict the original tokens based on the surrounding context. This allows the model to learn bidirectional context (looking at words both before and after the masked word). + +2. **Causal language modeling (CLM)**: Used by decoder models like GPT, this approach predicts the next token based on all previous tokens in the sequence. The model can only use context from the left (previous tokens) to predict the next token. + +### Types of language models + +In the Transformers library, language models generally fall into three architectural categories: + +1. **Encoder-only models** (like BERT): These models use a bidirectional approach to understand context from both directions. They're best suited for tasks that require deep understanding of text, such as classification, named entity recognition, and question answering. + +2. **Decoder-only models** (like GPT, Llama): These models process text from left to right and are particularly good at text generation tasks. They can complete sentences, write essays, or even generate code based on a prompt. + +3. **Encoder-decoder models** (like T5, BART): These models combine both approaches, using an encoder to understand the input and a decoder to generate output. They excel at sequence-to-sequence tasks like translation, summarization, and question answering. + +![transformer-models-for-language](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter1/transformers_architecture.png) + +As we covered in the previous section, language models are typically pretrained on large amounts of text data in a self-supervised manner (without human annotations), then fine-tuned on specific tasks. This approach, known as transfer learning, allows these models to adapt to many different NLP tasks with relatively small amounts of task-specific data. + +In the following sections, we'll explore specific model architectures and how they're applied to various tasks across speech, vision, and text domains. + +> [!TIP] +> Understanding which part of the Transformer architecture (encoder, decoder, or both) is best suited for a particular NLP task is key to choosing the right model. Generally, tasks requiring bidirectional context use encoders, tasks generating text use decoders, and tasks converting one sequence to another use encoder-decoders. + +### Text generation + +Text generation involves creating coherent and contextually relevant text based on a prompt or input. + +[GPT-2](https://huggingface.co/docs/transformers/model_doc/gpt2) is a decoder-only model pretrained on a large amount of text. It can generate convincing (though not always true!) text given a prompt and complete other NLP tasks like question answering despite not being explicitly trained to. + +
+ +
+ +1. GPT-2 uses [byte pair encoding (BPE)](https://huggingface.co/docs/transformers/tokenizer_summary#bytepair-encoding-bpe) to tokenize words and generate a token embedding. Positional encodings are added to the token embeddings to indicate the position of each token in the sequence. The input embeddings are passed through multiple decoder blocks to output some final hidden state. Within each decoder block, GPT-2 uses a *masked self-attention* layer which means GPT-2 can't attend to future tokens. It is only allowed to attend to tokens on the left. This is different from BERT's [`mask`] token because, in masked self-attention, an attention mask is used to set the score to `0` for future tokens. + +2. The output from the decoder is passed to a language modeling head, which performs a linear transformation to convert the hidden states into logits. The label is the next token in the sequence, which are created by shifting the logits to the right by one. The cross-entropy loss is calculated between the shifted logits and the labels to output the next most likely token. + +GPT-2's pretraining objective is based entirely on [causal language modeling](https://huggingface.co/docs/transformers/glossary#causal-language-modeling), predicting the next word in a sequence. This makes GPT-2 especially good at tasks that involve generating text. + +Ready to try your hand at text generation? Check out our complete [causal language modeling guide](https://huggingface.co/docs/transformers/tasks/language_modeling#causal-language-modeling) to learn how to finetune DistilGPT-2 and use it for inference! + +> [!TIP] +> For more information about text generation, check out the [text generation strategies](https://huggingface.co/docs/transformers/generation_strategies#generation-strategies) guide! + +### Text classification + +Text classification involves assigning predefined categories to text documents, such as sentiment analysis, topic classification, or spam detection. + +[BERT](https://huggingface.co/docs/transformers/model_doc/bert) is an encoder-only model and is the first model to effectively implement deep bidirectionality to learn richer representations of the text by attending to words on both sides. + +1. BERT uses [WordPiece](https://huggingface.co/docs/transformers/tokenizer_summary#wordpiece) tokenization to generate a token embedding of the text. To tell the difference between a single sentence and a pair of sentences, a special `[SEP]` token is added to differentiate them. A special `[CLS]` token is added to the beginning of every sequence of text. The final output with the `[CLS]` token is used as the input to the classification head for classification tasks. BERT also adds a segment embedding to denote whether a token belongs to the first or second sentence in a pair of sentences. + +2. BERT is pretrained with two objectives: masked language modeling and next-sentence prediction. In masked language modeling, some percentage of the input tokens are randomly masked, and the model needs to predict these. This solves the issue of bidirectionality, where the model could cheat and see all the words and "predict" the next word. The final hidden states of the predicted mask tokens are passed to a feedforward network with a softmax over the vocabulary to predict the masked word. + + The second pretraining object is next-sentence prediction. The model must predict whether sentence B follows sentence A. Half of the time sentence B is the next sentence, and the other half of the time, sentence B is a random sentence. The prediction, whether it is the next sentence or not, is passed to a feedforward network with a softmax over the two classes (`IsNext` and `NotNext`). + +3. The input embeddings are passed through multiple encoder layers to output some final hidden states. + +To use the pretrained model for text classification, add a sequence classification head on top of the base BERT model. The sequence classification head is a linear layer that accepts the final hidden states and performs a linear transformation to convert them into logits. The cross-entropy loss is calculated between the logits and target to find the most likely label. + +Ready to try your hand at text classification? Check out our complete [text classification guide](https://huggingface.co/docs/transformers/tasks/sequence_classification) to learn how to finetune DistilBERT and use it for inference! + +### Token classification + +Token classification involves assigning a label to each token in a sequence, such as in named entity recognition or part-of-speech tagging. + +To use BERT for token classification tasks like named entity recognition (NER), add a token classification head on top of the base BERT model. The token classification head is a linear layer that accepts the final hidden states and performs a linear transformation to convert them into logits. The cross-entropy loss is calculated between the logits and each token to find the most likely label. + +Ready to try your hand at token classification? Check out our complete [token classification guide](https://huggingface.co/docs/transformers/tasks/token_classification) to learn how to finetune DistilBERT and use it for inference! + +### Question answering + +Question answering involves finding the answer to a question within a given context or passage. + +To use BERT for question answering, add a span classification head on top of the base BERT model. This linear layer accepts the final hidden states and performs a linear transformation to compute the `span` start and end logits corresponding to the answer. The cross-entropy loss is calculated between the logits and the label position to find the most likely span of text corresponding to the answer. + +Ready to try your hand at question answering? Check out our complete [question answering guide](https://huggingface.co/docs/transformers/tasks/question_answering) to learn how to finetune DistilBERT and use it for inference! + +> [!TIP] +> 💡 Notice how easy it is to use BERT for different tasks once it's been pretrained. You only need to add a specific head to the pretrained model to manipulate the hidden states into your desired output! + +### Summarization + +Summarization involves condensing a longer text into a shorter version while preserving its key information and meaning. + +Encoder-decoder models like [BART](https://huggingface.co/docs/transformers/model_doc/bart) and [T5](model_doc/t5) are designed for the sequence-to-sequence pattern of a summarization task. We'll explain how BART works in this section, and then you can try finetuning T5 at the end. + +
+ +
+ +1. BART's encoder architecture is very similar to BERT and accepts a token and positional embedding of the text. BART is pretrained by corrupting the input and then reconstructing it with the decoder. Unlike other encoders with specific corruption strategies, BART can apply any type of corruption. The *text infilling* corruption strategy works the best though. In text infilling, a number of text spans are replaced with a **single** [`mask`] token. This is important because the model has to predict the masked tokens, and it teaches the model to predict the number of missing tokens. The input embeddings and masked spans are passed through the encoder to output some final hidden states, but unlike BERT, BART doesn't add a final feedforward network at the end to predict a word. + +2. The encoder's output is passed to the decoder, which must predict the masked tokens and any uncorrupted tokens from the encoder's output. This gives additional context to help the decoder restore the original text. The output from the decoder is passed to a language modeling head, which performs a linear transformation to convert the hidden states into logits. The cross-entropy loss is calculated between the logits and the label, which is just the token shifted to the right. + +Ready to try your hand at summarization? Check out our complete [summarization guide](https://huggingface.co/docs/transformers/tasks/summarization) to learn how to finetune T5 and use it for inference! + +> [!TIP] +> For more information about text generation, check out the [text generation strategies](https://huggingface.co/docs/transformers/generation_strategies) guide! + +### Translation + +Translation involves converting text from one language to another while preserving its meaning. Translation is another example of a sequence-to-sequence task, which means you can use an encoder-decoder model like [BART](https://huggingface.co/docs/transformers/model_doc/bart) or [T5](model_doc/t5) to do it. We'll explain how BART works in this section, and then you can try finetuning T5 at the end. + +BART adapts to translation by adding a separate randomly initialized encoder to map a source language to an input that can be decoded into the target language. This new encoder's embeddings are passed to the pretrained encoder instead of the original word embeddings. The source encoder is trained by updating the source encoder, positional embeddings, and input embeddings with the cross-entropy loss from the model output. The model parameters are frozen in this first step, and all the model parameters are trained together in the second step. +BART has since been followed up by a multilingual version, mBART, intended for translation and pretrained on many different languages. + +Ready to try your hand at translation? Check out our complete [translation guide](https://huggingface.co/docs/transformers/tasks/translation) to learn how to finetune T5 and use it for inference! + +> [!TIP] +> As you've seen throughout this guide, many models follow similar patterns despite addressing different tasks. Understanding these common patterns can help you quickly grasp how new models work and how to adapt existing models to your specific needs. + +## Modalities beyond text + +Transformers are not limited to text. They can also be applied to other modalities like speech and audio, images, and video. Of course, on this course we will focus on text, but we can briefly introduce the other modalities. + +### Speech and audio + +Let's start by exploring how Transformer models handle speech and audio data, which presents unique challenges compared to text or images. + +[Whisper](https://huggingface.co/docs/transformers/main/en/model_doc/whisper) is a encoder-decoder (sequence-to-sequence) transformer pretrained on 680,000 hours of labeled audio data. This amount of pretraining data enables zero-shot performance on audio tasks in English and many other languages. The decoder allows Whisper to map the encoders learned speech representations to useful outputs, such as text, without additional fine-tuning. Whisper just works out of the box. + +
+ +
+ +Diagram is from [Whisper paper](https://huggingface.co/papers/2212.04356). + +This model has two main components: + +1. An **encoder** processes the input audio. The raw audio is first converted into a log-Mel spectrogram. This spectrogram is then passed through a Transformer encoder network. + +2. A **decoder** takes the encoded audio representation and autoregressively predicts the corresponding text tokens. It's a standard Transformer decoder trained to predict the next text token given the previous tokens and the encoder output. Special tokens are used at the beginning of the decoder input to steer the model towards specific tasks like transcription, translation, or language identification. + +Whisper was pretrained on a massive and diverse dataset of 680,000 hours of labeled audio data collected from the web. This large-scale, weakly supervised pretraining is the key to its strong zero-shot performance across many languages and tasks. + +Now that Whisper is pretrained, you can use it directly for zero-shot inference or finetune it on your data for improved performance on specific tasks like automatic speech recognition or speech translation! + +> [!TIP] +> The key innovation in Whisper is its training on an unprecedented scale of diverse, weakly supervised audio data from the internet. This allows it to generalize remarkably well to different languages, accents, and tasks without task-specific finetuning. + +### Automatic speech recognition + +To use the pretrained model for automatic speech recognition, you leverage its full encoder-decoder structure. The encoder processes the audio input, and the decoder autoregressively generates the transcript token by token. When fine-tuning, the model is typically trained using a standard sequence-to-sequence loss (like cross-entropy) to predict the correct text tokens based on the audio input. + +The easiest way to use a fine-tuned model for inference is within a `pipeline`. + +```python +from transformers import pipeline + +transcriber = pipeline( + task="automatic-speech-recognition", model="openai/whisper-base.en" +) +transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac") +# Output: {'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'} +``` + +Ready to try your hand at automatic speech recognition? Check out our complete [automatic speech recognition guide](https://huggingface.co/docs/transformers/tasks/asr) to learn how to finetune Whisper and use it for inference! + +### Computer vision + +Now let's move on to computer vision tasks, which deal with understanding and interpreting visual information from images or videos. + +There are two ways to approach computer vision tasks: + +1. Split an image into a sequence of patches and process them in parallel with a Transformer. +2. Use a modern CNN, like [ConvNeXT](https://huggingface.co/docs/transformers/model_doc/convnext), which relies on convolutional layers but adopts modern network designs. + +> [!TIP] +> A third approach mixes Transformers with convolutions (for example, [Convolutional Vision Transformer](https://huggingface.co/docs/transformers/model_doc/cvt) or [LeViT](https://huggingface.co/docs/transformers/model_doc/levit)). We won't discuss those because they just combine the two approaches we examine here. + +ViT and ConvNeXT are commonly used for image classification, but for other vision tasks like object detection, segmentation, and depth estimation, we'll look at DETR, Mask2Former and GLPN, respectively; these models are better suited for those tasks. + +### Image classification + +Image classification is one of the fundamental computer vision tasks. Let's see how different model architectures approach this problem. + +ViT and ConvNeXT can both be used for image classification; the main difference is that ViT uses an attention mechanism while ConvNeXT uses convolutions. + +[ViT](https://huggingface.co/docs/transformers/model_doc/vit) replaces convolutions entirely with a pure Transformer architecture. If you're familiar with the original Transformer, then you're already most of the way toward understanding ViT. + +
+ +
+ +The main change ViT introduced was in how images are fed to a Transformer: + +1. An image is split into square non-overlapping patches, each of which gets turned into a vector or *patch embedding*. The patch embeddings are generated from a convolutional 2D layer which creates the proper input dimensions (which for a base Transformer is 768 values for each patch embedding). If you had a 224x224 pixel image, you could split it into 196 16x16 image patches. Just like how text is tokenized into words, an image is "tokenized" into a sequence of patches. + +2. A *learnable embedding* - a special `[CLS]` token - is added to the beginning of the patch embeddings just like BERT. The final hidden state of the `[CLS]` token is used as the input to the attached classification head; other outputs are ignored. This token helps the model learn how to encode a representation of the image. + +3. The last thing to add to the patch and learnable embeddings are the *position embeddings* because the model doesn't know how the image patches are ordered. The position embeddings are also learnable and have the same size as the patch embeddings. Finally, all of the embeddings are passed to the Transformer encoder. + +4. The output, specifically only the output with the `[CLS]` token, is passed to a multilayer perceptron head (MLP). ViT's pretraining objective is simply classification. Like other classification heads, the MLP head converts the output into logits over the class labels and calculates the cross-entropy loss to find the most likely class. + +Ready to try your hand at image classification? Check out our complete [image classification guide](https://huggingface.co/docs/transformers/tasks/image_classification) to learn how to fine-tune ViT and use it for inference! + + +> [!TIP] +> Notice the parallel between ViT and BERT: both use a special token ([CLS]) to capture the overall representation, both add position information to their embeddings, and both use a Transformer encoder to process the sequence of tokens/patches. diff --git a/chapters/en/chapter1/6.mdx b/chapters/en/chapter1/6.mdx index 08e306e43..7b5e2dc5b 100644 --- a/chapters/en/chapter1/6.mdx +++ b/chapters/en/chapter1/6.mdx @@ -1,204 +1,204 @@ - - -# Transformer Architectures[[transformer-architectures]] - -In the previous sections, we introduced the general Transformer architecture and explored how these models can solve various tasks. Now, let's take a closer look at the three main architectural variants of Transformer models and understand when to use each one. Then, we look at how those architectures are applied to different language tasks. - -In this section, we're going to dive deeper into the three main architectural variants of Transformer models and understand when to use each one. - - -> [!TIP] -> Remember that most Transformer models use one of three architectures: encoder-only, decoder-only, or encoder-decoder (sequence-to-sequence). Understanding these differences will help you choose the right model for your specific task. - -## Encoder models[[encoder-models]] - - - -Encoder models use only the encoder of a Transformer model. At each stage, the attention layers can access all the words in the initial sentence. These models are often characterized as having "bi-directional" attention, and are often called *auto-encoding models*. - -The pretraining of these models usually revolves around somehow corrupting a given sentence (for instance, by masking random words in it) and tasking the model with finding or reconstructing the initial sentence. - -Encoder models are best suited for tasks requiring an understanding of the full sentence, such as sentence classification, named entity recognition (and more generally word classification), and extractive question answering. - -> [!TIP] -> As we saw in [How 🤗 Transformers solve tasks](https://huggingface.co/learn/llm-course/chapter1/5), encoder models like BERT excel at understanding text because they can look at the entire context in both directions. This makes them perfect for tasks where comprehension of the whole input is important. - -Representatives of this family of models include: - -- [BERT](https://huggingface.co/docs/transformers/model_doc/bert) -- [DistilBERT](https://huggingface.co/docs/transformers/model_doc/distilbert) -- [ModernBERT](https://huggingface.co/docs/transformers/en/model_doc/modernbert) - -## Decoder models[[decoder-models]] - - - -Decoder models use only the decoder of a Transformer model. At each stage, for a given word the attention layers can only access the words positioned before it in the sentence. These models are often called *auto-regressive models*. - -The pretraining of decoder models usually revolves around predicting the next word in the sentence. - -These models are best suited for tasks involving text generation. - -> [!TIP] -> Decoder models like GPT are designed to generate text by predicting one token at a time. As we explored in [How 🤗 Transformers solve tasks](https://huggingface.co/learn/llm-course/chapter1/5), they can only see previous tokens, which makes them excellent for creative text generation but less ideal for tasks requiring bidirectional understanding. - -Representatives of this family of models include: - -- [Hugging Face SmolLM Series](https://huggingface.co/HuggingFaceTB/SmolLM2-1.7B-Instruct) -- [Meta's Llama Series](https://huggingface.co/docs/transformers/en/model_doc/llama4) -- [Google's Gemma Series](https://huggingface.co/docs/transformers/main/en/model_doc/gemma3) -- [DeepSeek's V3](https://huggingface.co/deepseek-ai/DeepSeek-V3) - -### Modern Large Language Models (LLMs) - -Most modern Large Language Models (LLMs) use the decoder-only architecture. These models have grown dramatically in size and capabilities over the past few years, with some of the largest models containing hundreds of billions of parameters. - -Modern LLMs are typically trained in two phases: -1. **Pretraining**: The model learns to predict the next token on vast amounts of text data -2. **Instruction tuning**: The model is fine-tuned to follow instructions and generate helpful responses - -This approach has led to models that can understand and generate human-like text across a wide range of topics and tasks. - -#### Key capabilities of modern LLMs - -Modern decoder-based LLMs have demonstrated impressive capabilities: - -| Capability | Description | Example | -|------------|-------------|---------| -| Text generation | Creating coherent and contextually relevant text | Writing essays, stories, or emails | -| Summarization | Condensing long documents into shorter versions | Creating executive summaries of reports | -| Translation | Converting text between languages | Translating English to Spanish | -| Question answering | Providing answers to factual questions | "What is the capital of France?" | -| Code generation | Writing or completing code snippets | Creating a function based on a description | -| Reasoning | Working through problems step by step | Solving math problems or logical puzzles | -| Few-shot learning | Learning from a few examples in the prompt | Classifying text after seeing just 2-3 examples | - -You can experiment with decoder-based LLMs directly in your browser via model repo pages on the Hub. Here's an example with the classic [GPT-2](https://huggingface.co/openai-community/gpt2) (OpenAI's finest open source model!): - - - View GPT-2 model on Hugging Face - - -## Sequence-to-sequence models[[sequence-to-sequence-models]] - - - -Encoder-decoder models (also called *sequence-to-sequence models*) use both parts of the Transformer architecture. At each stage, the attention layers of the encoder can access all the words in the initial sentence, whereas the attention layers of the decoder can only access the words positioned before a given word in the input. - -The pretraining of these models can take different forms, but it often involves reconstructing a sentence for which the input has been somehow corrupted (for instance by masking random words). The pretraining of the T5 model consists of replacing random spans of text (that can contain several words) with a single mask special token, and the task is then to predict the text that this mask token replaces. - -Sequence-to-sequence models are best suited for tasks revolving around generating new sentences depending on a given input, such as summarization, translation, or generative question answering. - -> [!TIP] -> As we saw in [How 🤗 Transformers solve tasks](https://huggingface.co/learn/llm-course/chapter1/5), encoder-decoder models like BART and T5 combine the strengths of both architectures. The encoder provides deep bidirectional understanding of the input, while the decoder generates appropriate output text. This makes them perfect for tasks that transform one sequence into another, like translation or summarization. - -### Practical applications - -Sequence-to-sequence models excel at tasks that require transforming one form of text into another while preserving meaning. Some practical applications include: - -| Application | Description | Example Model | -|-------------|-------------|---------------| -| Machine translation | Converting text between languages | Marian, T5 | -| Text summarization | Creating concise summaries of longer texts | BART, T5 | -| Data-to-text generation | Converting structured data into natural language | T5 | -| Grammar correction | Fixing grammatical errors in text | T5 | -| Question answering | Generating answers based on context | BART, T5 | - -Here's an interactive demo of a sequence-to-sequence model for translation: - - - -Representatives of this family of models include: - -- [BART](https://huggingface.co/docs/transformers/model_doc/bart) -- [mBART](https://huggingface.co/docs/transformers/model_doc/mbart) -- [Marian](https://huggingface.co/docs/transformers/model_doc/marian) -- [T5](https://huggingface.co/docs/transformers/model_doc/t5) - -## Choosing the right architecture[[choosing-the-right-architecture]] - -When working on a specific NLP task, how do you decide which architecture to use? Here's a quick guide: - -| Task | Suggested Architecture | Examples | -|------|------------------------|----------| -| Text classification (sentiment, topic) | Encoder | BERT, RoBERTa | -| Text generation (creative writing) | Decoder | GPT, LLaMA | -| Translation | Encoder-Decoder | T5, BART | -| Summarization | Encoder-Decoder | BART, T5 | -| Named entity recognition | Encoder | BERT, RoBERTa | -| Question answering (extractive) | Encoder | BERT, RoBERTa | -| Question answering (generative) | Encoder-Decoder or Decoder | T5, GPT | -| Conversational AI | Decoder | GPT, LLaMA | - -> [!TIP] -> When in doubt about which model to use, consider: -> -> 1. What kind of understanding does your task need? (Bidirectional or unidirectional) -> 2. Are you generating new text or analyzing existing text? -> 3. Do you need to transform one sequence into another? -> -> The answers to these questions will guide you toward the right architecture. - -## The evolution of LLMs - -Large Language Models have evolved rapidly in recent years, with each generation bringing significant improvements in capabilities. - -## Attention mechanisms[[attention-mechanisms]] - -Most transformer models use full attention in the sense that the attention matrix is square. It can be a big -computational bottleneck when you have long texts. Longformer and reformer are models that try to be more efficient and -use a sparse version of the attention matrix to speed up training. - -> [!TIP] -> Standard attention mechanisms have a computational complexity of O(n²), where n is the sequence length. This becomes problematic for very long sequences. The specialized attention mechanisms below help address this limitation. - -### LSH attention - -[Reformer](https://huggingface.co/docs/transformers/model_doc/reformer) uses LSH attention. In the softmax(QK^t), only the biggest elements (in the softmax dimension) of the matrix QK^t are going to give useful contributions. So for each query q in Q, we can consider only -the keys k in K that are close to q. A hash function is used to determine if q and k are close. The attention mask is -modified to mask the current token (except at the first position), because it will give a query and a key equal (so -very similar to each other). Since the hash can be a bit random, several hash functions are used in practice -(determined by a n_rounds parameter) and then are averaged together. - -### Local attention - -[Longformer](https://huggingface.co/docs/transformers/model_doc/longformer) uses local attention: often, the local context (e.g., what are the two tokens to the left and right?) is enough to take action for a given token. Also, by stacking attention layers that have a small -window, the last layer will have a receptive field of more than just the tokens in the window, allowing them to build a -representation of the whole sentence. - -Some preselected input tokens are also given global attention: for those few tokens, the attention matrix can access -all tokens and this process is symmetric: all other tokens have access to those specific tokens (on top of the ones in -their local window). This is shown in Figure 2d of the paper, see below for a sample attention mask: - -
- -
- -Using those attention matrices with less parameters then allows the model to have inputs having a bigger sequence -length. - -### Axial positional encodings - -[Reformer](https://huggingface.co/docs/transformers/model_doc/reformer) uses axial positional encodings: in traditional transformer models, the positional encoding -E is a matrix of size \\(l\\) by \\(d\\), \\(l\\) being the sequence length and \\(d\\) the dimension of the -hidden state. If you have very long texts, this matrix can be huge and take way too much space on the GPU. To alleviate -that, axial positional encodings consist of factorizing that big matrix E in two smaller matrices E1 and E2, with -dimensions \\(l_{1} \times d_{1}\\) and \\(l_{2} \times d_{2}\\), such that \\(l_{1} \times l_{2} = l\\) and -\\(d_{1} + d_{2} = d\\) (with the product for the lengths, this ends up being way smaller). The embedding for time -step \\(j\\) in E is obtained by concatenating the embeddings for timestep \\(j \% l1\\) in E1 and \\(j // l1\\) -in E2. - -## Conclusion[[conclusion]] - -In this section, we've explored the three main Transformer architectures and some specialized attention mechanisms. Understanding these architectural differences is crucial for selecting the right model for your specific NLP task. - -As we move forward in the course, you'll get hands-on experience with these different architectures and learn how to fine-tune them for your specific needs. In the next section, we'll look at some of the limitations and biases present in these models that you should be aware of when deploying them. + + +# Transformer Architectures[[transformer-architectures]] + +In the previous sections, we introduced the general Transformer architecture and explored how these models can solve various tasks. Now, let's take a closer look at the three main architectural variants of Transformer models and understand when to use each one. Then, we look at how those architectures are applied to different language tasks. + +In this section, we're going to dive deeper into the three main architectural variants of Transformer models and understand when to use each one. + + +> [!TIP] +> Remember that most Transformer models use one of three architectures: encoder-only, decoder-only, or encoder-decoder (sequence-to-sequence). Understanding these differences will help you choose the right model for your specific task. + +## Encoder models[[encoder-models]] + + + +Encoder models use only the encoder of a Transformer model. At each stage, the attention layers can access all the words in the initial sentence. These models are often characterized as having "bi-directional" attention, and are often called *auto-encoding models*. + +The pretraining of these models usually revolves around somehow corrupting a given sentence (for instance, by masking random words in it) and tasking the model with finding or reconstructing the initial sentence. + +Encoder models are best suited for tasks requiring an understanding of the full sentence, such as sentence classification, named entity recognition (and more generally word classification), and extractive question answering. + +> [!TIP] +> As we saw in [How 🤗 Transformers solve tasks](https://huggingface.co/learn/llm-course/chapter1/5), encoder models like BERT excel at understanding text because they can look at the entire context in both directions. This makes them perfect for tasks where comprehension of the whole input is important. + +Representatives of this family of models include: + +- [BERT](https://huggingface.co/docs/transformers/model_doc/bert) +- [DistilBERT](https://huggingface.co/docs/transformers/model_doc/distilbert) +- [ModernBERT](https://huggingface.co/docs/transformers/en/model_doc/modernbert) + +## Decoder models[[decoder-models]] + + + +Decoder models use only the decoder of a Transformer model. At each stage, for a given word the attention layers can only access the words positioned before it in the sentence. These models are often called *auto-regressive models*. + +The pretraining of decoder models usually revolves around predicting the next word in the sentence. + +These models are best suited for tasks involving text generation. + +> [!TIP] +> Decoder models like GPT are designed to generate text by predicting one token at a time. As we explored in [How 🤗 Transformers solve tasks](https://huggingface.co/learn/llm-course/chapter1/5), they can only see previous tokens, which makes them excellent for creative text generation but less ideal for tasks requiring bidirectional understanding. + +Representatives of this family of models include: + +- [Hugging Face SmolLM Series](https://huggingface.co/HuggingFaceTB/SmolLM2-1.7B-Instruct) +- [Meta's Llama Series](https://huggingface.co/docs/transformers/en/model_doc/llama4) +- [Google's Gemma Series](https://huggingface.co/docs/transformers/main/en/model_doc/gemma3) +- [DeepSeek's V3](https://huggingface.co/deepseek-ai/DeepSeek-V3) + +### Modern Large Language Models (LLMs) + +Most modern Large Language Models (LLMs) use the decoder-only architecture. These models have grown dramatically in size and capabilities over the past few years, with some of the largest models containing hundreds of billions of parameters. + +Modern LLMs are typically trained in two phases: +1. **Pretraining**: The model learns to predict the next token on vast amounts of text data +2. **Instruction tuning**: The model is fine-tuned to follow instructions and generate helpful responses + +This approach has led to models that can understand and generate human-like text across a wide range of topics and tasks. + +#### Key capabilities of modern LLMs + +Modern decoder-based LLMs have demonstrated impressive capabilities: + +| Capability | Description | Example | +|------------|-------------|---------| +| Text generation | Creating coherent and contextually relevant text | Writing essays, stories, or emails | +| Summarization | Condensing long documents into shorter versions | Creating executive summaries of reports | +| Translation | Converting text between languages | Translating English to Spanish | +| Question answering | Providing answers to factual questions | "What is the capital of France?" | +| Code generation | Writing or completing code snippets | Creating a function based on a description | +| Reasoning | Working through problems step by step | Solving math problems or logical puzzles | +| Few-shot learning | Learning from a few examples in the prompt | Classifying text after seeing just 2-3 examples | + +You can experiment with decoder-based LLMs directly in your browser via model repo pages on the Hub. Here's an example with the classic [GPT-2](https://huggingface.co/openai-community/gpt2) (OpenAI's finest open source model!): + + + View GPT-2 model on Hugging Face + + +## Sequence-to-sequence models[[sequence-to-sequence-models]] + + + +Encoder-decoder models (also called *sequence-to-sequence models*) use both parts of the Transformer architecture. At each stage, the attention layers of the encoder can access all the words in the initial sentence, whereas the attention layers of the decoder can only access the words positioned before a given word in the input. + +The pretraining of these models can take different forms, but it often involves reconstructing a sentence for which the input has been somehow corrupted (for instance by masking random words). The pretraining of the T5 model consists of replacing random spans of text (that can contain several words) with a single mask special token, and the task is then to predict the text that this mask token replaces. + +Sequence-to-sequence models are best suited for tasks revolving around generating new sentences depending on a given input, such as summarization, translation, or generative question answering. + +> [!TIP] +> As we saw in [How 🤗 Transformers solve tasks](https://huggingface.co/learn/llm-course/chapter1/5), encoder-decoder models like BART and T5 combine the strengths of both architectures. The encoder provides deep bidirectional understanding of the input, while the decoder generates appropriate output text. This makes them perfect for tasks that transform one sequence into another, like translation or summarization. + +### Practical applications + +Sequence-to-sequence models excel at tasks that require transforming one form of text into another while preserving meaning. Some practical applications include: + +| Application | Description | Example Model | +|-------------|-------------|---------------| +| Machine translation | Converting text between languages | Marian, T5 | +| Text summarization | Creating concise summaries of longer texts | BART, T5 | +| Data-to-text generation | Converting structured data into natural language | T5 | +| Grammar correction | Fixing grammatical errors in text | T5 | +| Question answering | Generating answers based on context | BART, T5 | + +Here's an interactive demo of a sequence-to-sequence model for translation: + + + +Representatives of this family of models include: + +- [BART](https://huggingface.co/docs/transformers/model_doc/bart) +- [mBART](https://huggingface.co/docs/transformers/model_doc/mbart) +- [Marian](https://huggingface.co/docs/transformers/model_doc/marian) +- [T5](https://huggingface.co/docs/transformers/model_doc/t5) + +## Choosing the right architecture[[choosing-the-right-architecture]] + +When working on a specific NLP task, how do you decide which architecture to use? Here's a quick guide: + +| Task | Suggested Architecture | Examples | +|------|------------------------|----------| +| Text classification (sentiment, topic) | Encoder | BERT, RoBERTa | +| Text generation (creative writing) | Decoder | GPT, LLaMA | +| Translation | Encoder-Decoder | T5, BART | +| Summarization | Encoder-Decoder | BART, T5 | +| Named entity recognition | Encoder | BERT, RoBERTa | +| Question answering (extractive) | Encoder | BERT, RoBERTa | +| Question answering (generative) | Encoder-Decoder or Decoder | T5, GPT | +| Conversational AI | Decoder | GPT, LLaMA | + +> [!TIP] +> When in doubt about which model to use, consider: +> +> 1. What kind of understanding does your task need? (Bidirectional or unidirectional) +> 2. Are you generating new text or analyzing existing text? +> 3. Do you need to transform one sequence into another? +> +> The answers to these questions will guide you toward the right architecture. + +## The evolution of LLMs + +Large Language Models have evolved rapidly in recent years, with each generation bringing significant improvements in capabilities. + +## Attention mechanisms[[attention-mechanisms]] + +Most transformer models use full attention in the sense that the attention matrix is square. It can be a big +computational bottleneck when you have long texts. Longformer and reformer are models that try to be more efficient and +use a sparse version of the attention matrix to speed up training. + +> [!TIP] +> Standard attention mechanisms have a computational complexity of O(n²), where n is the sequence length. This becomes problematic for very long sequences. The specialized attention mechanisms below help address this limitation. + +### LSH attention + +[Reformer](https://huggingface.co/docs/transformers/model_doc/reformer) uses LSH attention. In the softmax(QK^t), only the biggest elements (in the softmax dimension) of the matrix QK^t are going to give useful contributions. So for each query q in Q, we can consider only +the keys k in K that are close to q. A hash function is used to determine if q and k are close. The attention mask is +modified to mask the current token (except at the first position), because it will give a query and a key equal (so +very similar to each other). Since the hash can be a bit random, several hash functions are used in practice +(determined by a n_rounds parameter) and then are averaged together. + +### Local attention + +[Longformer](https://huggingface.co/docs/transformers/model_doc/longformer) uses local attention: often, the local context (e.g., what are the two tokens to the left and right?) is enough to take action for a given token. Also, by stacking attention layers that have a small +window, the last layer will have a receptive field of more than just the tokens in the window, allowing them to build a +representation of the whole sentence. + +Some preselected input tokens are also given global attention: for those few tokens, the attention matrix can access +all tokens and this process is symmetric: all other tokens have access to those specific tokens (on top of the ones in +their local window). This is shown in Figure 2d of the paper, see below for a sample attention mask: + +
+ +
+ +Using those attention matrices with less parameters then allows the model to have inputs having a bigger sequence +length. + +### Axial positional encodings + +[Reformer](https://huggingface.co/docs/transformers/model_doc/reformer) uses axial positional encodings: in traditional transformer models, the positional encoding +E is a matrix of size \\(l\\) by \\(d\\), \\(l\\) being the sequence length and \\(d\\) the dimension of the +hidden state. If you have very long texts, this matrix can be huge and take way too much space on the GPU. To alleviate +that, axial positional encodings consist of factorizing that big matrix E in two smaller matrices E1 and E2, with +dimensions \\(l_{1} \times d_{1}\\) and \\(l_{2} \times d_{2}\\), such that \\(l_{1} \times l_{2} = l\\) and +\\(d_{1} + d_{2} = d\\) (with the product for the lengths, this ends up being way smaller). The embedding for time +step \\(j\\) in E is obtained by concatenating the embeddings for timestep \\(j \% l1\\) in E1 and \\(j // l1\\) +in E2. + +## Conclusion[[conclusion]] + +In this section, we've explored the three main Transformer architectures and some specialized attention mechanisms. Understanding these architectural differences is crucial for selecting the right model for your specific NLP task. + +As we move forward in the course, you'll get hands-on experience with these different architectures and learn how to fine-tune them for your specific needs. In the next section, we'll look at some of the limitations and biases present in these models that you should be aware of when deploying them. diff --git a/chapters/en/chapter1/7.mdx b/chapters/en/chapter1/7.mdx index ae770eaca..475e54412 100644 --- a/chapters/en/chapter1/7.mdx +++ b/chapters/en/chapter1/7.mdx @@ -1,257 +1,257 @@ - - -# Ungraded quiz[[ungraded-quiz]] - - - -So far, this chapter has covered a lot of ground! Don't worry if you didn't grasp all the details, but it's to reflect on what you've learned so far with a quiz. - -This quiz is ungraded, so you can try it as many times as you want. If you struggle with some questions, follow the tips and revisit the material. You'll be quizzed on this material again in the certification exam. - -### 1. Explore the Hub and look for the `roberta-large-mnli` checkpoint. What task does it perform? - - -roberta-large-mnli page." - }, - { - text: "Text classification", - explain: "More precisely, it classifies if two sentences are logically linked across three labels (contradiction, neutral, entailment) — a task also called natural language inference.", - correct: true - }, - { - text: "Text generation", - explain: "Look again on the roberta-large-mnli page." - } - ]} -/> - -### 2. What will the following code return? - -```py -from transformers import pipeline - -ner = pipeline("ner", aggregation_strategy="simple") -ner("My name is Sylvain and I work at Hugging Face in Brooklyn.") -``` - -sentiment-analysis pipeline." - }, - { - text: "It will return a generated text completing this sentence.", - explain: "This is incorrect — it would be a text-generation pipeline.", - }, - { - text: "It will return the words representing persons, organizations or locations.", - explain: "Furthermore, with aggregation_strategy="simple", it will group together the words belonging to the same entity, like \"Hugging Face\".", - correct: true - } - ]} -/> - -### 3. What should replace ... in this code sample? - -```py -from transformers import pipeline - -filler = pipeline("fill-mask", model="bert-base-cased") -result = filler("...") -``` - - has been waiting for you.", - explain: "This is incorrect. Check out the bert-base-cased model card and try to spot your mistake." - }, - { - text: "This [MASK] has been waiting for you.", - explain: "This model's mask token is [MASK].", - correct: true - }, - { - text: "This man has been waiting for you.", - explain: "This is incorrect. This pipeline fills in masked words, so it needs a mask token somewhere." - } - ]} -/> - -### 4. Why will this code fail? - -```py -from transformers import pipeline - -classifier = pipeline("zero-shot-classification") -result = classifier("This is a course about the Transformers library") -``` - -candidate_labels=[...].", - correct: true - }, - { - text: "This pipeline requires several sentences, not just one.", - explain: "This is incorrect, though when properly used, this pipeline can take a list of sentences to process (like all other pipelines)." - }, - { - text: "The 🤗 Transformers library is broken, as usual.", - explain: "We won't dignify this answer with a comment!" - }, - { - text: "This pipeline requires longer inputs; this one is too short.", - explain: "This is incorrect. Note that a very long text will be truncated when processed by this pipeline." - } - ]} -/> - -### 5. What does "transfer learning" mean? - - - -### 6. True or false? A language model usually does not need labels for its pretraining. - -self-supervised, which means the labels are created automatically from the inputs (like predicting the next word or filling in some masked words).", - correct: true - }, - { - text: "False", - explain: "This is not the correct answer." - } - ]} -/> - -### 7. Select the sentence that best describes the terms "model", "architecture", and "weights". - - - - -### 8. Which of these types of models would you use for completing prompts with generated text? - - - -### 9. Which of those types of models would you use for summarizing texts? - - - -### 10. Which of these types of models would you use for classifying text inputs according to certain labels? - - - -### 11. What possible source can the bias observed in a model have? - - + + +# Ungraded quiz[[ungraded-quiz]] + + + +So far, this chapter has covered a lot of ground! Don't worry if you didn't grasp all the details, but it's to reflect on what you've learned so far with a quiz. + +This quiz is ungraded, so you can try it as many times as you want. If you struggle with some questions, follow the tips and revisit the material. You'll be quizzed on this material again in the certification exam. + +### 1. Explore the Hub and look for the `roberta-large-mnli` checkpoint. What task does it perform? + + +roberta-large-mnli page." + }, + { + text: "Text classification", + explain: "More precisely, it classifies if two sentences are logically linked across three labels (contradiction, neutral, entailment) — a task also called natural language inference.", + correct: true + }, + { + text: "Text generation", + explain: "Look again on the roberta-large-mnli page." + } + ]} +/> + +### 2. What will the following code return? + +```py +from transformers import pipeline + +ner = pipeline("ner", aggregation_strategy="simple") +ner("My name is Sylvain and I work at Hugging Face in Brooklyn.") +``` + +sentiment-analysis pipeline." + }, + { + text: "It will return a generated text completing this sentence.", + explain: "This is incorrect — it would be a text-generation pipeline.", + }, + { + text: "It will return the words representing persons, organizations or locations.", + explain: "Furthermore, with aggregation_strategy="simple", it will group together the words belonging to the same entity, like \"Hugging Face\".", + correct: true + } + ]} +/> + +### 3. What should replace ... in this code sample? + +```py +from transformers import pipeline + +filler = pipeline("fill-mask", model="bert-base-cased") +result = filler("...") +``` + + has been waiting for you.", + explain: "This is incorrect. Check out the bert-base-cased model card and try to spot your mistake." + }, + { + text: "This [MASK] has been waiting for you.", + explain: "This model's mask token is [MASK].", + correct: true + }, + { + text: "This man has been waiting for you.", + explain: "This is incorrect. This pipeline fills in masked words, so it needs a mask token somewhere." + } + ]} +/> + +### 4. Why will this code fail? + +```py +from transformers import pipeline + +classifier = pipeline("zero-shot-classification") +result = classifier("This is a course about the Transformers library") +``` + +candidate_labels=[...].", + correct: true + }, + { + text: "This pipeline requires several sentences, not just one.", + explain: "This is incorrect, though when properly used, this pipeline can take a list of sentences to process (like all other pipelines)." + }, + { + text: "The 🤗 Transformers library is broken, as usual.", + explain: "We won't dignify this answer with a comment!" + }, + { + text: "This pipeline requires longer inputs; this one is too short.", + explain: "This is incorrect. Note that a very long text will be truncated when processed by this pipeline." + } + ]} +/> + +### 5. What does "transfer learning" mean? + + + +### 6. True or false? A language model usually does not need labels for its pretraining. + +self-supervised, which means the labels are created automatically from the inputs (like predicting the next word or filling in some masked words).", + correct: true + }, + { + text: "False", + explain: "This is not the correct answer." + } + ]} +/> + +### 7. Select the sentence that best describes the terms "model", "architecture", and "weights". + + + + +### 8. Which of these types of models would you use for completing prompts with generated text? + + + +### 9. Which of those types of models would you use for summarizing texts? + + + +### 10. Which of these types of models would you use for classifying text inputs according to certain labels? + + + +### 11. What possible source can the bias observed in a model have? + + diff --git a/chapters/en/chapter1/8.mdx b/chapters/en/chapter1/8.mdx index 6be1cb515..de3c0ef1b 100644 --- a/chapters/en/chapter1/8.mdx +++ b/chapters/en/chapter1/8.mdx @@ -1,263 +1,263 @@ -# Deep dive into Text Generation Inference with LLMs[[inference-with-llms]] - - - - - -So far, we've explored the transformer architecture in relation to a range of discrete tasks, like text classification or summarization. However, Large Language Models are most used for text generation, and this is what we'll explore in this chapter. - -In this page, we'll explore the core concepts behind LLM inference, providing a comprehensive understanding of how these models generate text and the key components involved in the inference process. - -## Understanding the Basics - -Let's start with the fundamentals. Inference is the process of using a trained LLM to generate human-like text from a given input prompt. Language models use their knowledge from training to formulate responses one word at a time. The model leverages learned probabilities from billions of parameters to predict and generate the next token in a sequence. This sequential generation is what allows LLMs to produce coherent and contextually relevant text. - -## The Role of Attention - -The attention mechanism is what gives LLMs their ability to understand context and generate coherent responses. When predicting the next word, not every word in a sentence carries equal weight - for example, in the sentence *"The capital of France is ..."*, the words "France" and "capital" are crucial for determining that "Paris" should come next. This ability to focus on relevant information is what we call attention. - -Visual Gif of Attention - -This process of identifying the most relevant words to predict the next token has proven to be incredibly effective. Although the basic principle of training LLMs—predicting the next token—has remained generally consistent since BERT and GPT-2, there have been significant advancements in scaling neural networks and making the attention mechanism work for longer and longer sequences, at lower and lower costs. - -> [!TIP] -> In short, the attention mechanism is the key to LLMs being able to generate text that is both coherent and context-aware. It sets modern LLMs apart from previous generations of language models. - -### Context Length and Attention Span - -Now that we understand attention, let's explore how much context an LLM can actually handle. This brings us to context length, or the model's 'attention span'. - -The context length refers to the maximum number of tokens (words or parts of words) that the LLM can process at once. Think of it as the size of the model's working memory. - -These capabilities are limited by several practical factors: -- The model's architecture and size -- Available computational resources -- The complexity of the input and desired output - -In an ideal world, we could feed unlimited context to the model, but hardware constraints and computational costs make this impractical. This is why different models are designed with different context lengths to balance capability with efficiency. - -> [!TIP] -> The context length is the maximum number of tokens the model can consider at once when generating a response. - -### The Art of Prompting - -When we pass information to LLMs, we structure our input in a way that guides the generation of the LLM toward the desired output. This is called _prompting_. - -Understanding how LLMs process information helps us craft better prompts. Since the model's primary task is to predict the next token by analyzing the importance of each input token, the wording of your input sequence becomes crucial. - -> [!TIP] -> Careful design of the prompt makes it easier **to guide the generation of the LLM toward the desired output**. - -## The Two-Phase Inference Process - -Now that we understand the basic components, let's dive into how LLMs actually generate text. The process can be broken down into two main phases: prefill and decode. These phases work together like an assembly line, each playing a crucial role in producing coherent text. - -### The Prefill Phase - -The prefill phase is like the preparation stage in cooking - it's where all the initial ingredients are processed and made ready. This phase involves three key steps: - -1. **Tokenization**: Converting the input text into tokens (think of these as the basic building blocks the model understands) -2. **Embedding Conversion**: Transforming these tokens into numerical representations that capture their meaning -3. **Initial Processing**: Running these embeddings through the model's neural networks to create a rich understanding of the context - -This phase is computationally intensive because it needs to process all input tokens at once. Think of it as reading and understanding an entire paragraph before starting to write a response. - -You can experiment with different tokenizers in the interactive playground below: - - - -### The Decode Phase - -After the prefill phase has processed the input, we move to the decode phase - this is where the actual text generation happens. The model generates one token at a time in what we call an autoregressive process (where each new token depends on all previous tokens). - -The decode phase involves several key steps that happen for each new token: -1. **Attention Computation**: Looking back at all previous tokens to understand context -2. **Probability Calculation**: Determining the likelihood of each possible next token -3. **Token Selection**: Choosing the next token based on these probabilities -4. **Continuation Check**: Deciding whether to continue or stop generation - -This phase is memory-intensive because the model needs to keep track of all previously generated tokens and their relationships. - -## Sampling Strategies - -Now that we understand how the model generates text, let's explore the various ways we can control this generation process. Just like a writer might choose between being more creative or more precise, we can adjust how the model makes its token selections. - -You can interact with the basic decoding process yourself with SmolLM2 in this Space (remember, it decodes until reaching an **EOS** token which is **<|im_end|>** for this model): - - - -### Understanding Token Selection: From Probabilities to Token Choices - -When the model needs to choose the next token, it starts with raw probabilities (called logits) for every word in its vocabulary. But how do we turn these probabilities into actual choices? Let's break down the process: - -![image](https://huggingface.co/reasoning-course/images/resolve/main/inference/1.png) - -1. **Raw Logits**: Think of these as the model's initial gut feelings about each possible next word -2. **Temperature Control**: Like a creativity dial - higher settings (>1.0) make choices more random and creative, lower settings (<1.0) make them more focused and deterministic -3. **Top-p (Nucleus) Sampling**: Instead of considering all possible words, we only look at the most likely ones that add up to our chosen probability threshold (e.g., top 90%) -4. **Top-k Filtering**: An alternative approach where we only consider the k most likely next words - -### Managing Repetition: Keeping Output Fresh - -One common challenge with LLMs is their tendency to repeat themselves - much like a speaker who keeps returning to the same points. To address this, we use two types of penalties: - -1. **Presence Penalty**: A fixed penalty applied to any token that has appeared before, regardless of how often. This helps prevent the model from reusing the same words. -2. **Frequency Penalty**: A scaling penalty that increases based on how often a token has been used. The more a word appears, the less likely it is to be chosen again. - -![image](https://huggingface.co/reasoning-course/images/resolve/main/inference/2.png) - -These penalties are applied early in the token selection process, adjusting the raw probabilities before other sampling strategies are applied. Think of them as gentle nudges encouraging the model to explore new vocabulary. - -### Controlling Generation Length: Setting Boundaries - -Just as a good story needs proper pacing and length, we need ways to control how much text our LLM generates. This is crucial for practical applications - whether we're generating a tweet-length response or a full blog post. - -We can control generation length in several ways: -1. **Token Limits**: Setting minimum and maximum token counts -2. **Stop Sequences**: Defining specific patterns that signal the end of generation -3. **End-of-Sequence Detection**: Letting the model naturally conclude its response - -For example, if we want to generate a single paragraph, we might set a maximum of 100 tokens and use "\n\n" as a stop sequence. This ensures our output stays focused and appropriately sized for its purpose. - -![image](https://huggingface.co/reasoning-course/images/resolve/main/inference/3.png) - -### Beam Search: Looking Ahead for Better Coherence - -While the strategies we've discussed so far make decisions one token at a time, beam search takes a more holistic approach. Instead of committing to a single choice at each step, it explores multiple possible paths simultaneously - like a chess player thinking several moves ahead. - -![image](https://huggingface.co/reasoning-course/images/resolve/main/inference/4.png) - -Here's how it works: -1. At each step, maintain multiple candidate sequences (typically 5-10) -2. For each candidate, compute probabilities for the next token -3. Keep only the most promising combinations of sequences and next tokens -4. Continue this process until reaching the desired length or stop condition -5. Select the sequence with the highest overall probability - -You can explore beam search visually here: - - - -This approach often produces more coherent and grammatically correct text, though it requires more computational resources than simpler methods. - -## Practical Challenges and Optimization - -As we wrap up our exploration of LLM inference, let's look at the practical challenges you'll face when deploying these models, and how to measure and optimize their performance. - -### Key Performance Metrics - -When working with LLMs, four critical metrics will shape your implementation decisions: - -1. **Time to First Token (TTFT)**: How quickly can you get the first response? This is crucial for user experience and is primarily affected by the prefill phase. -2. **Time Per Output Token (TPOT)**: How fast can you generate subsequent tokens? This determines the overall generation speed. -3. **Throughput**: How many requests can you handle simultaneously? This affects scaling and cost efficiency. -4. **VRAM Usage**: How much GPU memory do you need? This often becomes the primary constraint in real-world applications. - -### The Context Length Challenge - -One of the most significant challenges in LLM inference is managing context length effectively. Longer contexts provide more information but come with substantial costs: - -- **Memory Usage**: Grows quadratically with context length -- **Processing Speed**: Decreases linearly with longer contexts -- **Resource Allocation**: Requires careful balancing of VRAM usage - -Recent models like [Qwen2.5-1M](https://huggingface.co/Qwen/Qwen2.5-14B-Instruct-1M) offer impressive 1M token context windows, but this comes at the cost of significantly slower inference times. The key is finding the right balance for your specific use case. - - -
-
-
-
- Input Text (Raw) -
-
-
- Tokenized Input -
-
-
-
- Context Window
(e.g., 4K tokens) -
-
-
-
-
-
-
-
-
-
-
- Memory Usage
∝ Length² -
-
-
-
- Processing Time
∝ Length -
-
-
-
-
- -### The KV Cache Optimization - -To address these challenges, one of the most powerful optimizations is KV (Key-Value) caching. This technique significantly improves inference speed by storing and reusing intermediate calculations. This optimization: -- Reduces repeated calculations -- Improves generation speed -- Makes long-context generation practical - -The trade-off is additional memory usage, but the performance benefits usually far outweigh this cost. - -## Conclusion - -Understanding LLM inference is crucial for effectively deploying and optimizing these powerful models. We've covered the key components: - -- The fundamental role of attention and context -- The two-phase inference process -- Various sampling strategies for controlling generation -- Practical challenges and optimizations - -By mastering these concepts, you'll be better equipped to build applications that leverage LLMs effectively and efficiently. - -Remember that the field of LLM inference is rapidly evolving, with new techniques and optimizations emerging regularly. Stay curious and keep experimenting with different approaches to find what works best for your specific use cases. +# Deep dive into Text Generation Inference with LLMs[[inference-with-llms]] + + + + + +So far, we've explored the transformer architecture in relation to a range of discrete tasks, like text classification or summarization. However, Large Language Models are most used for text generation, and this is what we'll explore in this chapter. + +In this page, we'll explore the core concepts behind LLM inference, providing a comprehensive understanding of how these models generate text and the key components involved in the inference process. + +## Understanding the Basics + +Let's start with the fundamentals. Inference is the process of using a trained LLM to generate human-like text from a given input prompt. Language models use their knowledge from training to formulate responses one word at a time. The model leverages learned probabilities from billions of parameters to predict and generate the next token in a sequence. This sequential generation is what allows LLMs to produce coherent and contextually relevant text. + +## The Role of Attention + +The attention mechanism is what gives LLMs their ability to understand context and generate coherent responses. When predicting the next word, not every word in a sentence carries equal weight - for example, in the sentence *"The capital of France is ..."*, the words "France" and "capital" are crucial for determining that "Paris" should come next. This ability to focus on relevant information is what we call attention. + +Visual Gif of Attention + +This process of identifying the most relevant words to predict the next token has proven to be incredibly effective. Although the basic principle of training LLMs—predicting the next token—has remained generally consistent since BERT and GPT-2, there have been significant advancements in scaling neural networks and making the attention mechanism work for longer and longer sequences, at lower and lower costs. + +> [!TIP] +> In short, the attention mechanism is the key to LLMs being able to generate text that is both coherent and context-aware. It sets modern LLMs apart from previous generations of language models. + +### Context Length and Attention Span + +Now that we understand attention, let's explore how much context an LLM can actually handle. This brings us to context length, or the model's 'attention span'. + +The context length refers to the maximum number of tokens (words or parts of words) that the LLM can process at once. Think of it as the size of the model's working memory. + +These capabilities are limited by several practical factors: +- The model's architecture and size +- Available computational resources +- The complexity of the input and desired output + +In an ideal world, we could feed unlimited context to the model, but hardware constraints and computational costs make this impractical. This is why different models are designed with different context lengths to balance capability with efficiency. + +> [!TIP] +> The context length is the maximum number of tokens the model can consider at once when generating a response. + +### The Art of Prompting + +When we pass information to LLMs, we structure our input in a way that guides the generation of the LLM toward the desired output. This is called _prompting_. + +Understanding how LLMs process information helps us craft better prompts. Since the model's primary task is to predict the next token by analyzing the importance of each input token, the wording of your input sequence becomes crucial. + +> [!TIP] +> Careful design of the prompt makes it easier **to guide the generation of the LLM toward the desired output**. + +## The Two-Phase Inference Process + +Now that we understand the basic components, let's dive into how LLMs actually generate text. The process can be broken down into two main phases: prefill and decode. These phases work together like an assembly line, each playing a crucial role in producing coherent text. + +### The Prefill Phase + +The prefill phase is like the preparation stage in cooking - it's where all the initial ingredients are processed and made ready. This phase involves three key steps: + +1. **Tokenization**: Converting the input text into tokens (think of these as the basic building blocks the model understands) +2. **Embedding Conversion**: Transforming these tokens into numerical representations that capture their meaning +3. **Initial Processing**: Running these embeddings through the model's neural networks to create a rich understanding of the context + +This phase is computationally intensive because it needs to process all input tokens at once. Think of it as reading and understanding an entire paragraph before starting to write a response. + +You can experiment with different tokenizers in the interactive playground below: + + + +### The Decode Phase + +After the prefill phase has processed the input, we move to the decode phase - this is where the actual text generation happens. The model generates one token at a time in what we call an autoregressive process (where each new token depends on all previous tokens). + +The decode phase involves several key steps that happen for each new token: +1. **Attention Computation**: Looking back at all previous tokens to understand context +2. **Probability Calculation**: Determining the likelihood of each possible next token +3. **Token Selection**: Choosing the next token based on these probabilities +4. **Continuation Check**: Deciding whether to continue or stop generation + +This phase is memory-intensive because the model needs to keep track of all previously generated tokens and their relationships. + +## Sampling Strategies + +Now that we understand how the model generates text, let's explore the various ways we can control this generation process. Just like a writer might choose between being more creative or more precise, we can adjust how the model makes its token selections. + +You can interact with the basic decoding process yourself with SmolLM2 in this Space (remember, it decodes until reaching an **EOS** token which is **<|im_end|>** for this model): + + + +### Understanding Token Selection: From Probabilities to Token Choices + +When the model needs to choose the next token, it starts with raw probabilities (called logits) for every word in its vocabulary. But how do we turn these probabilities into actual choices? Let's break down the process: + +![image](https://huggingface.co/reasoning-course/images/resolve/main/inference/1.png) + +1. **Raw Logits**: Think of these as the model's initial gut feelings about each possible next word +2. **Temperature Control**: Like a creativity dial - higher settings (>1.0) make choices more random and creative, lower settings (<1.0) make them more focused and deterministic +3. **Top-p (Nucleus) Sampling**: Instead of considering all possible words, we only look at the most likely ones that add up to our chosen probability threshold (e.g., top 90%) +4. **Top-k Filtering**: An alternative approach where we only consider the k most likely next words + +### Managing Repetition: Keeping Output Fresh + +One common challenge with LLMs is their tendency to repeat themselves - much like a speaker who keeps returning to the same points. To address this, we use two types of penalties: + +1. **Presence Penalty**: A fixed penalty applied to any token that has appeared before, regardless of how often. This helps prevent the model from reusing the same words. +2. **Frequency Penalty**: A scaling penalty that increases based on how often a token has been used. The more a word appears, the less likely it is to be chosen again. + +![image](https://huggingface.co/reasoning-course/images/resolve/main/inference/2.png) + +These penalties are applied early in the token selection process, adjusting the raw probabilities before other sampling strategies are applied. Think of them as gentle nudges encouraging the model to explore new vocabulary. + +### Controlling Generation Length: Setting Boundaries + +Just as a good story needs proper pacing and length, we need ways to control how much text our LLM generates. This is crucial for practical applications - whether we're generating a tweet-length response or a full blog post. + +We can control generation length in several ways: +1. **Token Limits**: Setting minimum and maximum token counts +2. **Stop Sequences**: Defining specific patterns that signal the end of generation +3. **End-of-Sequence Detection**: Letting the model naturally conclude its response + +For example, if we want to generate a single paragraph, we might set a maximum of 100 tokens and use "\n\n" as a stop sequence. This ensures our output stays focused and appropriately sized for its purpose. + +![image](https://huggingface.co/reasoning-course/images/resolve/main/inference/3.png) + +### Beam Search: Looking Ahead for Better Coherence + +While the strategies we've discussed so far make decisions one token at a time, beam search takes a more holistic approach. Instead of committing to a single choice at each step, it explores multiple possible paths simultaneously - like a chess player thinking several moves ahead. + +![image](https://huggingface.co/reasoning-course/images/resolve/main/inference/4.png) + +Here's how it works: +1. At each step, maintain multiple candidate sequences (typically 5-10) +2. For each candidate, compute probabilities for the next token +3. Keep only the most promising combinations of sequences and next tokens +4. Continue this process until reaching the desired length or stop condition +5. Select the sequence with the highest overall probability + +You can explore beam search visually here: + + + +This approach often produces more coherent and grammatically correct text, though it requires more computational resources than simpler methods. + +## Practical Challenges and Optimization + +As we wrap up our exploration of LLM inference, let's look at the practical challenges you'll face when deploying these models, and how to measure and optimize their performance. + +### Key Performance Metrics + +When working with LLMs, four critical metrics will shape your implementation decisions: + +1. **Time to First Token (TTFT)**: How quickly can you get the first response? This is crucial for user experience and is primarily affected by the prefill phase. +2. **Time Per Output Token (TPOT)**: How fast can you generate subsequent tokens? This determines the overall generation speed. +3. **Throughput**: How many requests can you handle simultaneously? This affects scaling and cost efficiency. +4. **VRAM Usage**: How much GPU memory do you need? This often becomes the primary constraint in real-world applications. + +### The Context Length Challenge + +One of the most significant challenges in LLM inference is managing context length effectively. Longer contexts provide more information but come with substantial costs: + +- **Memory Usage**: Grows quadratically with context length +- **Processing Speed**: Decreases linearly with longer contexts +- **Resource Allocation**: Requires careful balancing of VRAM usage + +Recent models like [Qwen2.5-1M](https://huggingface.co/Qwen/Qwen2.5-14B-Instruct-1M) offer impressive 1M token context windows, but this comes at the cost of significantly slower inference times. The key is finding the right balance for your specific use case. + + +
+
+
+
+ Input Text (Raw) +
+
+
+ Tokenized Input +
+
+
+
+ Context Window
(e.g., 4K tokens) +
+
+
+
+
+
+
+
+
+
+
+ Memory Usage
∝ Length² +
+
+
+
+ Processing Time
∝ Length +
+
+
+
+
+ +### The KV Cache Optimization + +To address these challenges, one of the most powerful optimizations is KV (Key-Value) caching. This technique significantly improves inference speed by storing and reusing intermediate calculations. This optimization: +- Reduces repeated calculations +- Improves generation speed +- Makes long-context generation practical + +The trade-off is additional memory usage, but the performance benefits usually far outweigh this cost. + +## Conclusion + +Understanding LLM inference is crucial for effectively deploying and optimizing these powerful models. We've covered the key components: + +- The fundamental role of attention and context +- The two-phase inference process +- Various sampling strategies for controlling generation +- Practical challenges and optimizations + +By mastering these concepts, you'll be better equipped to build applications that leverage LLMs effectively and efficiently. + +Remember that the field of LLM inference is rapidly evolving, with new techniques and optimizations emerging regularly. Stay curious and keep experimenting with different approaches to find what works best for your specific use cases. diff --git a/chapters/en/chapter1/9.mdx b/chapters/en/chapter1/9.mdx index 13f448a32..bd2bdd5ea 100644 --- a/chapters/en/chapter1/9.mdx +++ b/chapters/en/chapter1/9.mdx @@ -1,32 +1,32 @@ -# Bias and limitations[[bias-and-limitations]] - - - -If your intent is to use a pretrained model or a fine-tuned version in production, please be aware that, while these models are powerful tools, they come with limitations. The biggest of these is that, to enable pretraining on large amounts of data, researchers often scrape all the content they can find, taking the best as well as the worst of what is available on the internet. - -To give a quick illustration, let's go back to the example of a `fill-mask` pipeline with the BERT model: - -```python -from transformers import pipeline - -unmasker = pipeline("fill-mask", model="bert-base-uncased") -result = unmasker("This man works as a [MASK].") -print([r["token_str"] for r in result]) - -result = unmasker("This woman works as a [MASK].") -print([r["token_str"] for r in result]) -``` - -```python out -['lawyer', 'carpenter', 'doctor', 'waiter', 'mechanic'] -['nurse', 'waitress', 'teacher', 'maid', 'prostitute'] -``` - -When asked to fill in the missing word in these two sentences, the model gives only one gender-free answer (waiter/waitress). The others are work occupations usually associated with one specific gender -- and yes, prostitute ended up in the top 5 possibilities the model associates with "woman" and "work." This happens even though BERT is one of the rare Transformer models not built by scraping data from all over the internet, but rather using apparently neutral data (it's trained on the [English Wikipedia](https://huggingface.co/datasets/wikipedia) and [BookCorpus](https://huggingface.co/datasets/bookcorpus) datasets). - -When you use these tools, you therefore need to keep in the back of your mind that the original model you are using could very easily generate sexist, racist, or homophobic content. Fine-tuning the model on your data won't make this intrinsic bias disappear. +# Bias and limitations[[bias-and-limitations]] + + + +If your intent is to use a pretrained model or a fine-tuned version in production, please be aware that, while these models are powerful tools, they come with limitations. The biggest of these is that, to enable pretraining on large amounts of data, researchers often scrape all the content they can find, taking the best as well as the worst of what is available on the internet. + +To give a quick illustration, let's go back to the example of a `fill-mask` pipeline with the BERT model: + +```python +from transformers import pipeline + +unmasker = pipeline("fill-mask", model="bert-base-uncased") +result = unmasker("This man works as a [MASK].") +print([r["token_str"] for r in result]) + +result = unmasker("This woman works as a [MASK].") +print([r["token_str"] for r in result]) +``` + +```python out +['lawyer', 'carpenter', 'doctor', 'waiter', 'mechanic'] +['nurse', 'waitress', 'teacher', 'maid', 'prostitute'] +``` + +When asked to fill in the missing word in these two sentences, the model gives only one gender-free answer (waiter/waitress). The others are work occupations usually associated with one specific gender -- and yes, prostitute ended up in the top 5 possibilities the model associates with "woman" and "work." This happens even though BERT is one of the rare Transformer models not built by scraping data from all over the internet, but rather using apparently neutral data (it's trained on the [English Wikipedia](https://huggingface.co/datasets/wikipedia) and [BookCorpus](https://huggingface.co/datasets/bookcorpus) datasets). + +When you use these tools, you therefore need to keep in the back of your mind that the original model you are using could very easily generate sexist, racist, or homophobic content. Fine-tuning the model on your data won't make this intrinsic bias disappear. diff --git a/chapters/en/chapter10/1.mdx b/chapters/en/chapter10/1.mdx index 4301620cc..718b99390 100644 --- a/chapters/en/chapter10/1.mdx +++ b/chapters/en/chapter10/1.mdx @@ -1,26 +1,26 @@ -# Introduction to Argilla[[introduction-to-argilla]] - - - -In Chapter 5 you learnt how to build a dataset using the 🤗 Datasets library and in Chapter 6 you explored how to fine-tune models for some common NLP tasks. In this chapter, you will learn how to use [Argilla](https://argilla.io) to **annotate and curate datasets** that you can use to train and evaluate your models. - -The key to training models that perform well is to have high-quality data. Although there are some good datasets in the Hub that you could use to train and evaluate your models, these may not be relevant for your specific application or use case. In this scenario, you may want to build and curate a dataset of your own. Argilla will help you to do this efficiently. - -Argilla sign in page. - -With Argilla you can: - -- turn unstructured data into **structured data** to be used in NLP tasks. -- curate a dataset to go from a low-quality dataset to a **high-quality dataset**. -- gather **human feedback** for LLMs and multi-modal models. -- invite experts to collaborate with you in Argilla, or crowdsource annotations! - -Here are some of the things that you will learn in this chapter: - -- How to set up your own Argilla instance. -- How to load a dataset and configure it based on some popular NLP tasks. -- How to use the Argilla UI to annotate your dataset. -- How to use your curated dataset and export it to the Hub. +# Introduction to Argilla[[introduction-to-argilla]] + + + +In Chapter 5 you learnt how to build a dataset using the 🤗 Datasets library and in Chapter 6 you explored how to fine-tune models for some common NLP tasks. In this chapter, you will learn how to use [Argilla](https://argilla.io) to **annotate and curate datasets** that you can use to train and evaluate your models. + +The key to training models that perform well is to have high-quality data. Although there are some good datasets in the Hub that you could use to train and evaluate your models, these may not be relevant for your specific application or use case. In this scenario, you may want to build and curate a dataset of your own. Argilla will help you to do this efficiently. + +Argilla sign in page. + +With Argilla you can: + +- turn unstructured data into **structured data** to be used in NLP tasks. +- curate a dataset to go from a low-quality dataset to a **high-quality dataset**. +- gather **human feedback** for LLMs and multi-modal models. +- invite experts to collaborate with you in Argilla, or crowdsource annotations! + +Here are some of the things that you will learn in this chapter: + +- How to set up your own Argilla instance. +- How to load a dataset and configure it based on some popular NLP tasks. +- How to use the Argilla UI to annotate your dataset. +- How to use your curated dataset and export it to the Hub. diff --git a/chapters/en/chapter10/2.mdx b/chapters/en/chapter10/2.mdx index 447ef04aa..486081796 100644 --- a/chapters/en/chapter10/2.mdx +++ b/chapters/en/chapter10/2.mdx @@ -1,55 +1,55 @@ -# Set up your Argilla instance[[set-up-your-argilla-instance]] - - - -To start using Argilla, you will need to set up your own Argilla instance first. Then you will need to install the Python SDK so that you can manage Argilla using Python code. - -## Deploy the Argilla UI - -The easiest way to set up your Argilla instance is through Hugging Face Spaces. To create your Argilla Space, simply follow [this form](https://huggingface.co/new-space?template=argilla%2Fargilla-template-space). If you need further guidance, check the [Argilla quickstart](https://docs.argilla.io/latest/getting_started/quickstart/). -Space configuration form. - ->[!WARNING] -> ⚠️ You may want to enable **Persistent storage** so the data isn't lost if the Space is paused or restarted. -> You can do that from the Settings of your Space. - -Once Argilla is up and running, you can log in with your credentials. - -## Install and connect the Python SDK - -Now you can go to your Python environment or notebook and install the argilla library: - -`!pip install argilla` - -Let's connect with our Argilla instance. To do that you will need the following information: - -- **Your API URL**: This is the URL where Argilla is running. If you are using a Space, you can open the Space, click on the three dots in the top right corner, then "Embed this Space" and copy the **Direct URL**. It should look something like `https://..hf.space`. -- **Your API key**: To get your key, log in to your Argilla instance and go to "My Settings", then copy the API key. -- **Your HF token**: If your Space is private, you will need to an Access Token in your Hugging Face Hub account with writing permissions. - -```python -import argilla as rg - -HF_TOKEN = "..." # only for private spaces - -client = rg.Argilla( - api_url="...", - api_key="...", - headers={"Authorization": f"Bearer {HF_TOKEN}"}, # only for private spaces -) -``` - -To check that everything is working properly, we'll call `me`. This should return our user: - -```python -client.me -``` - -If this worked, your Argilla instance is up and running and you're connected to it! Congrats! - -We can now get started with loading our first dataset to Argilla. +# Set up your Argilla instance[[set-up-your-argilla-instance]] + + + +To start using Argilla, you will need to set up your own Argilla instance first. Then you will need to install the Python SDK so that you can manage Argilla using Python code. + +## Deploy the Argilla UI + +The easiest way to set up your Argilla instance is through Hugging Face Spaces. To create your Argilla Space, simply follow [this form](https://huggingface.co/new-space?template=argilla%2Fargilla-template-space). If you need further guidance, check the [Argilla quickstart](https://docs.argilla.io/latest/getting_started/quickstart/). +Space configuration form. + +>[!WARNING] +> ⚠️ You may want to enable **Persistent storage** so the data isn't lost if the Space is paused or restarted. +> You can do that from the Settings of your Space. + +Once Argilla is up and running, you can log in with your credentials. + +## Install and connect the Python SDK + +Now you can go to your Python environment or notebook and install the argilla library: + +`!pip install argilla` + +Let's connect with our Argilla instance. To do that you will need the following information: + +- **Your API URL**: This is the URL where Argilla is running. If you are using a Space, you can open the Space, click on the three dots in the top right corner, then "Embed this Space" and copy the **Direct URL**. It should look something like `https://..hf.space`. +- **Your API key**: To get your key, log in to your Argilla instance and go to "My Settings", then copy the API key. +- **Your HF token**: If your Space is private, you will need to an Access Token in your Hugging Face Hub account with writing permissions. + +```python +import argilla as rg + +HF_TOKEN = "..." # only for private spaces + +client = rg.Argilla( + api_url="...", + api_key="...", + headers={"Authorization": f"Bearer {HF_TOKEN}"}, # only for private spaces +) +``` + +To check that everything is working properly, we'll call `me`. This should return our user: + +```python +client.me +``` + +If this worked, your Argilla instance is up and running and you're connected to it! Congrats! + +We can now get started with loading our first dataset to Argilla. diff --git a/chapters/en/chapter10/3.mdx b/chapters/en/chapter10/3.mdx index be70cc469..359e85015 100644 --- a/chapters/en/chapter10/3.mdx +++ b/chapters/en/chapter10/3.mdx @@ -1,108 +1,108 @@ -# Load your dataset to Argilla[[load-your-dataset-to-argilla]] - - - -Depending on the NLP task that you're working with and the specific use case or application, your data and the annotation task will look differently. For this section of the course, we'll use [a dataset collecting news](https://huggingface.co/datasets/SetFit/ag_news) to complete two tasks: a text classification on the topic of each text and a token classification to identify the named entities mentioned. - - - -It is possible to import datasets from the Hub using the Argilla UI directly, but we'll be using the SDK to learn how we can make further edits to the data if needed. - -## Configure your dataset - -The first step is to connect to our Argilla instance as we did in the previous section: - -```python -import argilla as rg - -HF_TOKEN = "..." # only for private spaces - -client = rg.Argilla( - api_url="...", - api_key="...", - headers={"Authorization": f"Bearer {HF_TOKEN}"}, # only for private spaces -) -``` - -We can now think about the settings of our dataset in Argilla. These represent the annotation task we'll do over our data. First, we can load the dataset from the Hub and inspect its features, so that we can make sure that we configure the dataset correctly. - -```python -from datasets import load_dataset - -data = load_dataset("SetFit/ag_news", split="train") -data.features -``` - -These are the features of our dataset: - -```python out -{'text': Value(dtype='string', id=None), - 'label': Value(dtype='int64', id=None), - 'label_text': Value(dtype='string', id=None)} -``` - -It contains a `text` and also some initial labels for the text classification. We'll add those to our dataset settings together with a `spans` question for the named entities: - -```python -settings = rg.Settings( - fields=[rg.TextField(name="text")], - questions=[ - rg.LabelQuestion( - name="label", title="Classify the text:", labels=data.unique("label_text") - ), - rg.SpanQuestion( - name="entities", - title="Highlight all the entities in the text:", - labels=["PERSON", "ORG", "LOC", "EVENT"], - field="text", - ), - ], -) -``` - -Let's dive a bit deeper into what these settings mean. First, we've defined **fields**, these include the information that we'll be annotating. In this case, we only have one field and it comes in the form of a text, so we've choosen a `TextField`. - -Then, we define **questions** that represent the tasks that we want to perform on our data: - -- For the text classification task we've chosen a `LabelQuestion` and we used the unique values of the `label_text` column as our labels, to make sure that the question is compatible with the labels that already exist in the dataset. -- For the token classification task, we'll need a `SpanQuestion`. We've defined a set of labels that we'll be using for that task, plus the field on which we'll be drawing the spans. - -To learn more about all the available types of fields and questions and other advanced settings, like metadata and vectors, go to the [Argilla docs](https://docs.argilla.io/latest/how_to_guides/dataset/#define-dataset-settings). - -## Upload the dataset - -Now that we've defined some settings, we can create the dataset: - -```python -dataset = rg.Dataset(name="ag_news", settings=settings) - -dataset.create() -``` - -The dataset now appears in our Argilla instance, but you will see that it's empty: - -Screenshot of the empty dataset. - -Now we need to add the records that we'll be annotating i.e., the rows in our dataset. To do that, we'll simply need to log the data as records and provide a mapping for those elements that don't have the same name in the hub and Argilla datasets: - -```python -dataset.records.log(data, mapping={"label_text": "label"}) -``` - -In our mapping, we've specified that the `label_text` column in the dataset should be mapped to the question with the name `label`. In this way, we'll use the existing labels in the dataset as pre-annotations so we can annotate faster. - -While the records continue to log, you can already start working with your dataset in the Argilla UI. At this point, it should look like this: - -Screenshot of the dataset in Argilla. - -Now our dataset is ready to start annotating! +# Load your dataset to Argilla[[load-your-dataset-to-argilla]] + + + +Depending on the NLP task that you're working with and the specific use case or application, your data and the annotation task will look differently. For this section of the course, we'll use [a dataset collecting news](https://huggingface.co/datasets/SetFit/ag_news) to complete two tasks: a text classification on the topic of each text and a token classification to identify the named entities mentioned. + + + +It is possible to import datasets from the Hub using the Argilla UI directly, but we'll be using the SDK to learn how we can make further edits to the data if needed. + +## Configure your dataset + +The first step is to connect to our Argilla instance as we did in the previous section: + +```python +import argilla as rg + +HF_TOKEN = "..." # only for private spaces + +client = rg.Argilla( + api_url="...", + api_key="...", + headers={"Authorization": f"Bearer {HF_TOKEN}"}, # only for private spaces +) +``` + +We can now think about the settings of our dataset in Argilla. These represent the annotation task we'll do over our data. First, we can load the dataset from the Hub and inspect its features, so that we can make sure that we configure the dataset correctly. + +```python +from datasets import load_dataset + +data = load_dataset("SetFit/ag_news", split="train") +data.features +``` + +These are the features of our dataset: + +```python out +{'text': Value(dtype='string', id=None), + 'label': Value(dtype='int64', id=None), + 'label_text': Value(dtype='string', id=None)} +``` + +It contains a `text` and also some initial labels for the text classification. We'll add those to our dataset settings together with a `spans` question for the named entities: + +```python +settings = rg.Settings( + fields=[rg.TextField(name="text")], + questions=[ + rg.LabelQuestion( + name="label", title="Classify the text:", labels=data.unique("label_text") + ), + rg.SpanQuestion( + name="entities", + title="Highlight all the entities in the text:", + labels=["PERSON", "ORG", "LOC", "EVENT"], + field="text", + ), + ], +) +``` + +Let's dive a bit deeper into what these settings mean. First, we've defined **fields**, these include the information that we'll be annotating. In this case, we only have one field and it comes in the form of a text, so we've choosen a `TextField`. + +Then, we define **questions** that represent the tasks that we want to perform on our data: + +- For the text classification task we've chosen a `LabelQuestion` and we used the unique values of the `label_text` column as our labels, to make sure that the question is compatible with the labels that already exist in the dataset. +- For the token classification task, we'll need a `SpanQuestion`. We've defined a set of labels that we'll be using for that task, plus the field on which we'll be drawing the spans. + +To learn more about all the available types of fields and questions and other advanced settings, like metadata and vectors, go to the [Argilla docs](https://docs.argilla.io/latest/how_to_guides/dataset/#define-dataset-settings). + +## Upload the dataset + +Now that we've defined some settings, we can create the dataset: + +```python +dataset = rg.Dataset(name="ag_news", settings=settings) + +dataset.create() +``` + +The dataset now appears in our Argilla instance, but you will see that it's empty: + +Screenshot of the empty dataset. + +Now we need to add the records that we'll be annotating i.e., the rows in our dataset. To do that, we'll simply need to log the data as records and provide a mapping for those elements that don't have the same name in the hub and Argilla datasets: + +```python +dataset.records.log(data, mapping={"label_text": "label"}) +``` + +In our mapping, we've specified that the `label_text` column in the dataset should be mapped to the question with the name `label`. In this way, we'll use the existing labels in the dataset as pre-annotations so we can annotate faster. + +While the records continue to log, you can already start working with your dataset in the Argilla UI. At this point, it should look like this: + +Screenshot of the dataset in Argilla. + +Now our dataset is ready to start annotating! diff --git a/chapters/en/chapter10/4.mdx b/chapters/en/chapter10/4.mdx index 59c845502..f7f6e94b3 100644 --- a/chapters/en/chapter10/4.mdx +++ b/chapters/en/chapter10/4.mdx @@ -1,44 +1,44 @@ -# Annotate your dataset[[annotate-your-dataset]] - - - -Now it is time to start working from the Argilla UI to annotate our dataset. - -## Align your team with annotation guidelines - -Before you start annotating your dataset, it is always good practice to write some guidelines, especially if you're working as part of a team. This will help you align on the task and the use of the different labels, and resolve questions or conflicts when they come up. - -In Argilla, you can go to your dataset settings page in the UI and modify the guidelines and the descriptions of your questions to help with alignment. - -Screenshot of the Dataset Settings page in Argilla. - -If you want to dive deeper into the topic of how to write good guidelines, we recommend reading [this blogpost](https://argilla.io/blog/annotation-guidelines-practices) and the bibliographical references mentioned there. - -## Distribute the task - -In the dataset settings page, you can also change the dataset distribution settings. This will help you annotate more efficiently when you're working as part of a team. The default value for the minimum submitted responses is 1, meaning that as soon as a record has 1 submitted response it will be considered complete and count towards the progress in your dataset. - -Sometimes, you want to have more than one submitted response per record, for example, if you want to analyze the inter-annotator agreement in your task. In that case, make sure to change this setting to a higher number, but always smaller or equal to the total number of annotators. If you're working on the task alone, you want this setting to be 1. - -## Annotate records - ->[!TIP] ->💡 If you are deploying Argilla in a Hugging Face Space, any team members will be able to log in using the Hugging Face OAuth. Otherwise, you may need to create users for them following [this guide](https://docs.argilla.io/latest/how_to_guides/user/). - -When you open your dataset, you will realize that the first question is already filled in with some suggested labels. That's because in the previous section we mapped our question called `label` to the `label_text` column in the dataset, so that we simply need to review and correct the already existing labels: - -Screenshot of the dataset in Argilla. - -For the token classification, we'll need to add all labels manually, as we didn't include any suggestions. This is how it might look after the span annotations: - -Screenshot of the dataset in Argilla with spans annotated. - -As you move through the different records, there are different actions you can take: -- submit your responses, once you're done with the record. -- save them as a draft, in case you want to come back to them later. -- discard them, if the record souldn't be part of the dataset or you won't give responses to it. - -In the next section, you will learn how you can export and use those annotations. +# Annotate your dataset[[annotate-your-dataset]] + + + +Now it is time to start working from the Argilla UI to annotate our dataset. + +## Align your team with annotation guidelines + +Before you start annotating your dataset, it is always good practice to write some guidelines, especially if you're working as part of a team. This will help you align on the task and the use of the different labels, and resolve questions or conflicts when they come up. + +In Argilla, you can go to your dataset settings page in the UI and modify the guidelines and the descriptions of your questions to help with alignment. + +Screenshot of the Dataset Settings page in Argilla. + +If you want to dive deeper into the topic of how to write good guidelines, we recommend reading [this blogpost](https://argilla.io/blog/annotation-guidelines-practices) and the bibliographical references mentioned there. + +## Distribute the task + +In the dataset settings page, you can also change the dataset distribution settings. This will help you annotate more efficiently when you're working as part of a team. The default value for the minimum submitted responses is 1, meaning that as soon as a record has 1 submitted response it will be considered complete and count towards the progress in your dataset. + +Sometimes, you want to have more than one submitted response per record, for example, if you want to analyze the inter-annotator agreement in your task. In that case, make sure to change this setting to a higher number, but always smaller or equal to the total number of annotators. If you're working on the task alone, you want this setting to be 1. + +## Annotate records + +>[!TIP] +>💡 If you are deploying Argilla in a Hugging Face Space, any team members will be able to log in using the Hugging Face OAuth. Otherwise, you may need to create users for them following [this guide](https://docs.argilla.io/latest/how_to_guides/user/). + +When you open your dataset, you will realize that the first question is already filled in with some suggested labels. That's because in the previous section we mapped our question called `label` to the `label_text` column in the dataset, so that we simply need to review and correct the already existing labels: + +Screenshot of the dataset in Argilla. + +For the token classification, we'll need to add all labels manually, as we didn't include any suggestions. This is how it might look after the span annotations: + +Screenshot of the dataset in Argilla with spans annotated. + +As you move through the different records, there are different actions you can take: +- submit your responses, once you're done with the record. +- save them as a draft, in case you want to come back to them later. +- discard them, if the record souldn't be part of the dataset or you won't give responses to it. + +In the next section, you will learn how you can export and use those annotations. diff --git a/chapters/en/chapter10/5.mdx b/chapters/en/chapter10/5.mdx index 7a3b01f1b..a8596b8f0 100644 --- a/chapters/en/chapter10/5.mdx +++ b/chapters/en/chapter10/5.mdx @@ -1,69 +1,69 @@ -# Use your annotated dataset[[use-your-annotated-dataset]] - - - -We will learn now how to export and use the annotated data that we have in Argilla. - -## Load the dataset - -First, we'll need to make sure that we're connected to our Argilla instance as in the previous steps: - -```python -import argilla as rg - -HF_TOKEN = "..." # only for private spaces - -client = rg.Argilla( - api_url="...", - api_key="...", - headers={"Authorization": f"Bearer {HF_TOKEN}"}, # only for private spaces -) -``` - -And now, we'll load the dataset that we'll be working with: - -```python -dataset = client.datasets(name="ag_news") -``` - -Loading the dataset and calling its records with `dataset.records` is enough to start using your dataset and records for your own purposes and pipelines. However, we'll also learn how to do a few optional operations, like filtering the records and exporting your dataset to the Hugging Face Hub. - -## Filter the dataset - -Sometimes you only want to use the records that have been completed, so we will first filter the records in our dataset based on their status: - -```python -status_filter = rg.Query(filter=rg.Filter([("status", "==", "completed")])) - -filtered_records = dataset.records(status_filter) -``` - ->[!TIP] ->⚠️ Note that the records with `completed` status (i.e., records that meet the minimum submitted responses configured in the task distribution settings) could have more than one response and that each response can have any status from `submitted`, `draft` or `discarded`. - -Learn more about querying and filtering records in the [Argilla docs](https://docs.argilla.io/latest/how_to_guides/query/). - -## Export to the Hub - -We can now export our annotations to the Hugging Face Hub, so we can share them with others. To do this, we'll need to convert the records into a 🤗 Dataset and then push it to the Hub: - -```python -filtered_records.to_datasets().push_to_hub("argilla/ag_news_annotated") -``` - -Alternatively, we can export directly the complete Argilla dataset (including pending records) like this: - -```python -dataset.to_hub(repo_id="argilla/ag_news_annotated") -``` - -This is an interesting choice in case others want to open the dataset in their Argilla instances, as the settings are automatically saved and they can simply import the full dataset using a single line of code: - -```python -dataset = rg.Dataset.from_hub(repo_id="argilla/ag_news_annotated") -``` +# Use your annotated dataset[[use-your-annotated-dataset]] + + + +We will learn now how to export and use the annotated data that we have in Argilla. + +## Load the dataset + +First, we'll need to make sure that we're connected to our Argilla instance as in the previous steps: + +```python +import argilla as rg + +HF_TOKEN = "..." # only for private spaces + +client = rg.Argilla( + api_url="...", + api_key="...", + headers={"Authorization": f"Bearer {HF_TOKEN}"}, # only for private spaces +) +``` + +And now, we'll load the dataset that we'll be working with: + +```python +dataset = client.datasets(name="ag_news") +``` + +Loading the dataset and calling its records with `dataset.records` is enough to start using your dataset and records for your own purposes and pipelines. However, we'll also learn how to do a few optional operations, like filtering the records and exporting your dataset to the Hugging Face Hub. + +## Filter the dataset + +Sometimes you only want to use the records that have been completed, so we will first filter the records in our dataset based on their status: + +```python +status_filter = rg.Query(filter=rg.Filter([("status", "==", "completed")])) + +filtered_records = dataset.records(status_filter) +``` + +>[!TIP] +>⚠️ Note that the records with `completed` status (i.e., records that meet the minimum submitted responses configured in the task distribution settings) could have more than one response and that each response can have any status from `submitted`, `draft` or `discarded`. + +Learn more about querying and filtering records in the [Argilla docs](https://docs.argilla.io/latest/how_to_guides/query/). + +## Export to the Hub + +We can now export our annotations to the Hugging Face Hub, so we can share them with others. To do this, we'll need to convert the records into a 🤗 Dataset and then push it to the Hub: + +```python +filtered_records.to_datasets().push_to_hub("argilla/ag_news_annotated") +``` + +Alternatively, we can export directly the complete Argilla dataset (including pending records) like this: + +```python +dataset.to_hub(repo_id="argilla/ag_news_annotated") +``` + +This is an interesting choice in case others want to open the dataset in their Argilla instances, as the settings are automatically saved and they can simply import the full dataset using a single line of code: + +```python +dataset = rg.Dataset.from_hub(repo_id="argilla/ag_news_annotated") +``` diff --git a/chapters/en/chapter10/6.mdx b/chapters/en/chapter10/6.mdx index a65b9e3c8..91ba0b45f 100644 --- a/chapters/en/chapter10/6.mdx +++ b/chapters/en/chapter10/6.mdx @@ -1,20 +1,20 @@ -# Argilla, check![[argilla-check]] - - - -That's all! Congrats! 👏 - -In this chapter, you learnt the basic steps to: -- set up Argilla. -- annotate to improve the quality of your dataset. -- adapt an existing dataset and re-use it for a different NLP task. -- share your annotated dataset with the community in the Hugging Face Hub. - -## What's next? -- Check more step-by-step tutorials for other popular tasks in the [tutorials page](https://docs.argilla.io/latest/tutorials/). -- You can also explore other examples of datasets in this [demo](https://demo.argilla.io/sign-in?auth=ZGVtbzoxMjM0NTY3OA==). -- If you'd like to keep learning about Argilla and more advanced features, check the [Argilla documentation](https://docs.argilla.io/latest/). +# Argilla, check![[argilla-check]] + + + +That's all! Congrats! 👏 + +In this chapter, you learnt the basic steps to: +- set up Argilla. +- annotate to improve the quality of your dataset. +- adapt an existing dataset and re-use it for a different NLP task. +- share your annotated dataset with the community in the Hugging Face Hub. + +## What's next? +- Check more step-by-step tutorials for other popular tasks in the [tutorials page](https://docs.argilla.io/latest/tutorials/). +- You can also explore other examples of datasets in this [demo](https://demo.argilla.io/sign-in?auth=ZGVtbzoxMjM0NTY3OA==). +- If you'd like to keep learning about Argilla and more advanced features, check the [Argilla documentation](https://docs.argilla.io/latest/). \ No newline at end of file diff --git a/chapters/en/chapter10/7.mdx b/chapters/en/chapter10/7.mdx index 39214ed70..a704fb398 100644 --- a/chapters/en/chapter10/7.mdx +++ b/chapters/en/chapter10/7.mdx @@ -1,186 +1,186 @@ - - -# End-of-chapter quiz[[end-of-chapter-quiz]] - - - -Let's test what you learned in this chapter! - -### 1. What can you use Argilla for? - - - -### 2. Argilla ONLY works in the Hugging Face Spaces and with Hugging Face Datasets. - - - -### 3. You need a Hugging Face token to connect the Python SDK to your Argilla server. - - - -### 4. What are **fields** in Argilla? How many fields can you use? - - - -### 5. What's the best type of question for a token classification task? - - - -### 6. What is the purpose of the "Save as draft" button? - - - -### 7. Argilla does not offer suggested labels automatically, you need to provide that data yourself. - - - -### 8. Select all the necessary steps to export an Argilla dataset in full to the Hub: - -client= rg.Argilla(api_url='...', api_key='...')", - explain: "Yes, to interact with your server you'll need to instantiate it first.", - correct: true - }, - { - text: "Import the dataset from the hub: dataset = rg.Dataset.from_hub(repo_id='argilla/ag_news_annotated')", - explain: "No. This is to import a dataset from the Hub into your Argilla instance.", - }, - { - text: "Load the dataset: dataset = client.datasets(name='my_dataset')", - explain: "Yes, you'll need this for further operations", - correct: true - }, - { - text: "Convert the Argilla dataset into a Datasets dataset: dataset = dataset.to_datasets()", - explain: "This is not needed if you export the full dataset. Argilla will take care of this for you. However, you might need it if you're working with a subset of records." - }, - { - text: "Use the to_hub method to export the dataset: dataset.to_hub(repo_id='my_username/dataset_name')", - explain: "This will push the dataset to the indicated repo id, and create a new repo if it doesn't exist.", - correct: true - }, - ]} -/> + + +# End-of-chapter quiz[[end-of-chapter-quiz]] + + + +Let's test what you learned in this chapter! + +### 1. What can you use Argilla for? + + + +### 2. Argilla ONLY works in the Hugging Face Spaces and with Hugging Face Datasets. + + + +### 3. You need a Hugging Face token to connect the Python SDK to your Argilla server. + + + +### 4. What are **fields** in Argilla? How many fields can you use? + + + +### 5. What's the best type of question for a token classification task? + + + +### 6. What is the purpose of the "Save as draft" button? + + + +### 7. Argilla does not offer suggested labels automatically, you need to provide that data yourself. + + + +### 8. Select all the necessary steps to export an Argilla dataset in full to the Hub: + +client= rg.Argilla(api_url='...', api_key='...')", + explain: "Yes, to interact with your server you'll need to instantiate it first.", + correct: true + }, + { + text: "Import the dataset from the hub: dataset = rg.Dataset.from_hub(repo_id='argilla/ag_news_annotated')", + explain: "No. This is to import a dataset from the Hub into your Argilla instance.", + }, + { + text: "Load the dataset: dataset = client.datasets(name='my_dataset')", + explain: "Yes, you'll need this for further operations", + correct: true + }, + { + text: "Convert the Argilla dataset into a Datasets dataset: dataset = dataset.to_datasets()", + explain: "This is not needed if you export the full dataset. Argilla will take care of this for you. However, you might need it if you're working with a subset of records." + }, + { + text: "Use the to_hub method to export the dataset: dataset.to_hub(repo_id='my_username/dataset_name')", + explain: "This will push the dataset to the indicated repo id, and create a new repo if it doesn't exist.", + correct: true + }, + ]} +/> diff --git a/chapters/en/chapter11/1.mdx b/chapters/en/chapter11/1.mdx index e6da9f28d..157a67bb7 100644 --- a/chapters/en/chapter11/1.mdx +++ b/chapters/en/chapter11/1.mdx @@ -1,32 +1,32 @@ -# Supervised Fine-Tuning - -In [Chapter 2 Section 2](/course/chapter2/2), we saw that generative language models can be fine-tuned on specific tasks like summarization and question answering. However, nowadays it is far more common to fine-tune language models on a broad range of tasks simultaneously; a method known as supervised fine-tuning (SFT). This process helps models become more versatile and capable of handling diverse use cases. Most LLMs that people interact with on platforms like ChatGPT have undergone SFT to make them more helpful and aligned with human preferences. We will separate this chapter into four sections: - -## 1️⃣ Chat Templates - -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. - -## 2️⃣ Supervised Fine-Tuning - -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 section of the TRL documentation](https://huggingface.co/docs/trl/en/sft_trainer). - -## 3️⃣ Low Rank Adaptation (LoRA) - -Low Rank Adaptation (LoRA) is a technique for fine-tuning language models by adding low-rank matrices to the model's layers. This allows for efficient fine-tuning while preserving the model's pre-trained knowledge. One of the key benefits of LoRA is the significant memory savings it offers, making it possible to fine-tune large models on hardware with limited resources. - -## 4️⃣ Evaluation - -Evaluation is a crucial step in the fine-tuning process. It allows us to measure the performance of the model on a task-specific dataset. - -> [!TIP] -> ⚠️ In order to benefit from all features available with the Model Hub and 🤗 Transformers, we recommend creating an account. - -## References - -- [Transformers documentation on chat templates](https://huggingface.co/docs/transformers/main/en/chat_templating) -- [Script for Supervised Fine-Tuning in TRL](https://github.com/huggingface/trl/blob/main/trl/scripts/sft.py) -- [`SFTTrainer` in TRL](https://huggingface.co/docs/trl/main/en/sft_trainer) -- [Direct Preference Optimization Paper](https://arxiv.org/abs/2305.18290) -- [Supervised Fine-Tuning with TRL](https://huggingface.co/docs/trl/sft_trainer) -- [How to fine-tune Google Gemma with ChatML and Hugging Face TRL](https://github.com/huggingface/alignment-handbook) -- [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) +# Supervised Fine-Tuning + +In [Chapter 2 Section 2](/course/chapter2/2), we saw that generative language models can be fine-tuned on specific tasks like summarization and question answering. However, nowadays it is far more common to fine-tune language models on a broad range of tasks simultaneously; a method known as supervised fine-tuning (SFT). This process helps models become more versatile and capable of handling diverse use cases. Most LLMs that people interact with on platforms like ChatGPT have undergone SFT to make them more helpful and aligned with human preferences. We will separate this chapter into four sections: + +## 1️⃣ Chat Templates + +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. + +## 2️⃣ Supervised Fine-Tuning + +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 section of the TRL documentation](https://huggingface.co/docs/trl/en/sft_trainer). + +## 3️⃣ Low Rank Adaptation (LoRA) + +Low Rank Adaptation (LoRA) is a technique for fine-tuning language models by adding low-rank matrices to the model's layers. This allows for efficient fine-tuning while preserving the model's pre-trained knowledge. One of the key benefits of LoRA is the significant memory savings it offers, making it possible to fine-tune large models on hardware with limited resources. + +## 4️⃣ Evaluation + +Evaluation is a crucial step in the fine-tuning process. It allows us to measure the performance of the model on a task-specific dataset. + +> [!TIP] +> ⚠️ In order to benefit from all features available with the Model Hub and 🤗 Transformers, we recommend creating an account. + +## References + +- [Transformers documentation on chat templates](https://huggingface.co/docs/transformers/main/en/chat_templating) +- [Script for Supervised Fine-Tuning in TRL](https://github.com/huggingface/trl/blob/main/trl/scripts/sft.py) +- [`SFTTrainer` in TRL](https://huggingface.co/docs/trl/main/en/sft_trainer) +- [Direct Preference Optimization Paper](https://arxiv.org/abs/2305.18290) +- [Supervised Fine-Tuning with TRL](https://huggingface.co/docs/trl/sft_trainer) +- [How to fine-tune Google Gemma with ChatML and Hugging Face TRL](https://github.com/huggingface/alignment-handbook) +- [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) diff --git a/chapters/en/chapter11/2.mdx b/chapters/en/chapter11/2.mdx index 08b03f700..00069dcfb 100644 --- a/chapters/en/chapter11/2.mdx +++ b/chapters/en/chapter11/2.mdx @@ -1,249 +1,249 @@ - - -# Chat Templates - -## Introduction - -Chat templates are essential for structuring interactions between language models and users. Whether you're building a simple chatbot or a complex AI agent, understanding how to properly format your conversations is crucial for getting the best results from your model. In this guide, we'll explore what chat templates are, why they matter, and how to use them effectively. - -> [!TIP] -> Chat templates are crucial for: -> - Maintaining consistent conversation structure -> - Ensuring proper role identification -> - Managing context across multiple turns -> - Supporting advanced features like tool use - -## Model Types and Templates - -### Base Models vs Instruct Models -A base model is trained on raw text data to predict the next token, while an instruct model is fine-tuned specifically to follow instructions and engage in conversations. For example, [`SmolLM2-135M`](https://huggingface.co/HuggingFaceTB/SmolLM2-135M) is a base model, while [`SmolLM2-135M-Instruct`](https://huggingface.co/HuggingFaceTB/SmolLM2-135M-Instruct) is its instruction-tuned variant. - -Instruction tuned models are trained to follow a specific conversational structure, making them more suitable for chatbot applications. Moreover, instruct models can handle complex interactions, including tool use, multimodal inputs, and function calling. - -To make a base model behave like an instruct model, we need to format our prompts in a consistent way that the model can understand. This is where chat templates come in. ChatML is one such template format that structures conversations with clear role indicators (system, user, assistant). Here's a guide on [ChatML](https://huggingface.co/HuggingFaceTB/SmolLM2-135M-Instruct/blob/e2c3f7557efbdec707ae3a336371d169783f1da1/tokenizer_config.json#L146). - -> [!WARNING] -> When using an instruct model, always verify you're using the correct chat template format. Using the wrong template can result in poor model performance or unexpected behavior. The easiest way to ensure this is to check the model tokenizer configuration on the Hub. For example, the `SmolLM2-135M-Instruct` model uses this configuration. - -### Common Template Formats - -Before diving into specific implementations, it's important to understand how different models expect their conversations to be formatted. Let's explore some common template formats using a simple example conversation: - -We'll use the following conversation structure for all examples: - -```python -messages = [ - {"role": "system", "content": "You are a helpful assistant."}, - {"role": "user", "content": "Hello!"}, - {"role": "assistant", "content": "Hi! How can I help you today?"}, - {"role": "user", "content": "What's the weather?"}, -] -``` - -This is the ChatML template used in models like SmolLM2 and Qwen 2: - -```sh -<|im_start|>system -You are a helpful assistant.<|im_end|> -<|im_start|>user -Hello!<|im_end|> -<|im_start|>assistant -Hi! How can I help you today?<|im_end|> -<|im_start|>user -What's the weather?<|im_start|>assistant -``` - -This is using the `mistral` template format: - -```sh -[INST] You are a helpful assistant. [/INST] -Hi! How can I help you today? -[INST] Hello! [/INST] -``` - -Key differences between these formats include: -1. **System Message Handling**: - - Llama 2 wraps system messages in `<>` tags - - Llama 3 uses `<|system|>` tags with `` endings - - Mistral includes system message in the first instruction - - Qwen uses explicit `system` role with `<|im_start|>` tags - - ChatGPT uses `SYSTEM:` prefix - -2. **Message Boundaries**: - - Llama 2 uses `[INST]` and `[/INST]` tags - - Llama 3 uses role-specific tags (`<|system|>`, `<|user|>`, `<|assistant|>`) with `` endings - - Mistral uses `[INST]` and `[/INST]` with `` and `` - - Qwen uses role-specific start/end tokens - -3. **Special Tokens**: - - Llama 2 uses `` and `` for conversation boundaries - - Llama 3 uses `` to end each message - - Mistral uses `` and `` for turn boundaries - - Qwen uses role-specific start/end tokens - -Understanding these differences is key to working with various models. Let's look at how the transformers library helps us handle these variations automatically: - -```python -from transformers import AutoTokenizer - -# These will use different templates automatically -mistral_tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1") -qwen_tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen-7B-Chat") -smol_tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct") - -messages = [ - {"role": "system", "content": "You are a helpful assistant."}, - {"role": "user", "content": "Hello!"}, -] - -# Each will format according to its model's template -mistral_chat = mistral_tokenizer.apply_chat_template(messages, tokenize=False) -qwen_chat = qwen_tokenizer.apply_chat_template(messages, tokenize=False) -smol_chat = smol_tokenizer.apply_chat_template(messages, tokenize=False) -``` - -
-Click to see template examples - -Qwen 2 and SmolLM2 ChatML template: - -```sh -<|im_start|>system -You are a helpful assistant.<|im_end|> -<|im_start|>user -Hello!<|im_end|> -<|im_start|>assistant -Hi! How can I help you today?<|im_end|> -<|im_start|>user -What's the weather?<|im_start|>assistant -``` - -Mistral template: - -```sh -[INST] You are a helpful assistant. [/INST] -Hi! How can I help you today? -[INST] Hello! [/INST] -``` - -
- - -### Advanced Features -Chat templates can handle more complex scenarios beyond just conversational interactions, including: - -1. **Tool Use**: When models need to interact with external tools or APIs -2. **Multimodal Inputs**: For handling images, audio, or other media types -3. **Function Calling**: For structured function execution -4. **Multi-turn Context**: For maintaining conversation history - -> [!TIP] -> When implementing advanced features: -> - Test thoroughly with your specific model. Vision and tool use template are particularly diverse. -> - Monitor token usage carefully between each feature and model. -> - Document the expected format for each feature - -For multimodal conversations, chat templates can include image references or base64-encoded images: - -```python -messages = [ - { - "role": "system", - "content": "You are a helpful vision assistant that can analyze images.", - }, - { - "role": "user", - "content": [ - {"type": "text", "text": "What's in this image?"}, - {"type": "image", "image_url": "https://example.com/image.jpg"}, - ], - }, -] -``` - -Here's an example of a chat template with tool use: - -```python -messages = [ - { - "role": "system", - "content": "You are an AI assistant that can use tools. Available tools: calculator, weather_api", - }, - {"role": "user", "content": "What's 123 * 456 and is it raining in Paris?"}, - { - "role": "assistant", - "content": "Let me help you with that.", - "tool_calls": [ - { - "tool": "calculator", - "parameters": {"operation": "multiply", "x": 123, "y": 456}, - }, - {"tool": "weather_api", "parameters": {"city": "Paris", "country": "France"}}, - ], - }, - {"role": "tool", "tool_name": "calculator", "content": "56088"}, - { - "role": "tool", - "tool_name": "weather_api", - "content": "{'condition': 'rain', 'temperature': 15}", - }, -] -``` - -## Best Practices - -### General Guidelines -When working with chat templates, follow these key practices: - -1. **Consistent Formatting**: Always use the same template format throughout your application -2. **Clear Role Definition**: Clearly specify roles (system, user, assistant, tool) for each message -3. **Context Management**: Be mindful of token limits when maintaining conversation history -4. **Error Handling**: Include proper error handling for tool calls and multimodal inputs -5. **Validation**: Validate message structure before sending to the model - -> [!WARNING] -> Common pitfalls to avoid: -> - Mixing different template formats in the same application -> - Exceeding token limits with long conversation histories -> - Not properly escaping special characters in messages -> - Forgetting to validate input message structure -> - Ignoring model-specific template requirements - -## Hands-on Exercise - -Let's practice implementing chat templates with a real-world example. - -> [!TIP] -> Follow these steps to convert the `HuggingFaceTB/smoltalk` dataset into chatml format: -> -> 1. Load the dataset: -> ```python -> from datasets import load_dataset -> -> dataset = load_dataset("HuggingFaceTB/smoltalk") -> ``` -> -> 2. Create a processing function: -> ```python -> def convert_to_chatml(example): -> return { -> "messages": [ -> {"role": "user", "content": example["input"]}, -> {"role": "assistant", "content": example["output"]}, -> ] -> } -> ``` -> -> 3. Apply the chat template using your chosen model's tokenizer -> -> Remember to validate your output format matches your target model's requirements! - -## Additional Resources - -- [Hugging Face Chat Templating Guide](https://huggingface.co/docs/transformers/main/en/chat_templating) -- [Transformers Documentation](https://huggingface.co/docs/transformers) -- [Chat Templates Examples Repository](https://github.com/chujiezheng/chat_templates) + + +# Chat Templates + +## Introduction + +Chat templates are essential for structuring interactions between language models and users. Whether you're building a simple chatbot or a complex AI agent, understanding how to properly format your conversations is crucial for getting the best results from your model. In this guide, we'll explore what chat templates are, why they matter, and how to use them effectively. + +> [!TIP] +> Chat templates are crucial for: +> - Maintaining consistent conversation structure +> - Ensuring proper role identification +> - Managing context across multiple turns +> - Supporting advanced features like tool use + +## Model Types and Templates + +### Base Models vs Instruct Models +A base model is trained on raw text data to predict the next token, while an instruct model is fine-tuned specifically to follow instructions and engage in conversations. For example, [`SmolLM2-135M`](https://huggingface.co/HuggingFaceTB/SmolLM2-135M) is a base model, while [`SmolLM2-135M-Instruct`](https://huggingface.co/HuggingFaceTB/SmolLM2-135M-Instruct) is its instruction-tuned variant. + +Instruction tuned models are trained to follow a specific conversational structure, making them more suitable for chatbot applications. Moreover, instruct models can handle complex interactions, including tool use, multimodal inputs, and function calling. + +To make a base model behave like an instruct model, we need to format our prompts in a consistent way that the model can understand. This is where chat templates come in. ChatML is one such template format that structures conversations with clear role indicators (system, user, assistant). Here's a guide on [ChatML](https://huggingface.co/HuggingFaceTB/SmolLM2-135M-Instruct/blob/e2c3f7557efbdec707ae3a336371d169783f1da1/tokenizer_config.json#L146). + +> [!WARNING] +> When using an instruct model, always verify you're using the correct chat template format. Using the wrong template can result in poor model performance or unexpected behavior. The easiest way to ensure this is to check the model tokenizer configuration on the Hub. For example, the `SmolLM2-135M-Instruct` model uses this configuration. + +### Common Template Formats + +Before diving into specific implementations, it's important to understand how different models expect their conversations to be formatted. Let's explore some common template formats using a simple example conversation: + +We'll use the following conversation structure for all examples: + +```python +messages = [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hello!"}, + {"role": "assistant", "content": "Hi! How can I help you today?"}, + {"role": "user", "content": "What's the weather?"}, +] +``` + +This is the ChatML template used in models like SmolLM2 and Qwen 2: + +```sh +<|im_start|>system +You are a helpful assistant.<|im_end|> +<|im_start|>user +Hello!<|im_end|> +<|im_start|>assistant +Hi! How can I help you today?<|im_end|> +<|im_start|>user +What's the weather?<|im_start|>assistant +``` + +This is using the `mistral` template format: + +```sh +[INST] You are a helpful assistant. [/INST] +Hi! How can I help you today? +[INST] Hello! [/INST] +``` + +Key differences between these formats include: +1. **System Message Handling**: + - Llama 2 wraps system messages in `<>` tags + - Llama 3 uses `<|system|>` tags with `` endings + - Mistral includes system message in the first instruction + - Qwen uses explicit `system` role with `<|im_start|>` tags + - ChatGPT uses `SYSTEM:` prefix + +2. **Message Boundaries**: + - Llama 2 uses `[INST]` and `[/INST]` tags + - Llama 3 uses role-specific tags (`<|system|>`, `<|user|>`, `<|assistant|>`) with `` endings + - Mistral uses `[INST]` and `[/INST]` with `` and `` + - Qwen uses role-specific start/end tokens + +3. **Special Tokens**: + - Llama 2 uses `` and `` for conversation boundaries + - Llama 3 uses `` to end each message + - Mistral uses `` and `` for turn boundaries + - Qwen uses role-specific start/end tokens + +Understanding these differences is key to working with various models. Let's look at how the transformers library helps us handle these variations automatically: + +```python +from transformers import AutoTokenizer + +# These will use different templates automatically +mistral_tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1") +qwen_tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen-7B-Chat") +smol_tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct") + +messages = [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hello!"}, +] + +# Each will format according to its model's template +mistral_chat = mistral_tokenizer.apply_chat_template(messages, tokenize=False) +qwen_chat = qwen_tokenizer.apply_chat_template(messages, tokenize=False) +smol_chat = smol_tokenizer.apply_chat_template(messages, tokenize=False) +``` + +
+Click to see template examples + +Qwen 2 and SmolLM2 ChatML template: + +```sh +<|im_start|>system +You are a helpful assistant.<|im_end|> +<|im_start|>user +Hello!<|im_end|> +<|im_start|>assistant +Hi! How can I help you today?<|im_end|> +<|im_start|>user +What's the weather?<|im_start|>assistant +``` + +Mistral template: + +```sh +[INST] You are a helpful assistant. [/INST] +Hi! How can I help you today? +[INST] Hello! [/INST] +``` + +
+ + +### Advanced Features +Chat templates can handle more complex scenarios beyond just conversational interactions, including: + +1. **Tool Use**: When models need to interact with external tools or APIs +2. **Multimodal Inputs**: For handling images, audio, or other media types +3. **Function Calling**: For structured function execution +4. **Multi-turn Context**: For maintaining conversation history + +> [!TIP] +> When implementing advanced features: +> - Test thoroughly with your specific model. Vision and tool use template are particularly diverse. +> - Monitor token usage carefully between each feature and model. +> - Document the expected format for each feature + +For multimodal conversations, chat templates can include image references or base64-encoded images: + +```python +messages = [ + { + "role": "system", + "content": "You are a helpful vision assistant that can analyze images.", + }, + { + "role": "user", + "content": [ + {"type": "text", "text": "What's in this image?"}, + {"type": "image", "image_url": "https://example.com/image.jpg"}, + ], + }, +] +``` + +Here's an example of a chat template with tool use: + +```python +messages = [ + { + "role": "system", + "content": "You are an AI assistant that can use tools. Available tools: calculator, weather_api", + }, + {"role": "user", "content": "What's 123 * 456 and is it raining in Paris?"}, + { + "role": "assistant", + "content": "Let me help you with that.", + "tool_calls": [ + { + "tool": "calculator", + "parameters": {"operation": "multiply", "x": 123, "y": 456}, + }, + {"tool": "weather_api", "parameters": {"city": "Paris", "country": "France"}}, + ], + }, + {"role": "tool", "tool_name": "calculator", "content": "56088"}, + { + "role": "tool", + "tool_name": "weather_api", + "content": "{'condition': 'rain', 'temperature': 15}", + }, +] +``` + +## Best Practices + +### General Guidelines +When working with chat templates, follow these key practices: + +1. **Consistent Formatting**: Always use the same template format throughout your application +2. **Clear Role Definition**: Clearly specify roles (system, user, assistant, tool) for each message +3. **Context Management**: Be mindful of token limits when maintaining conversation history +4. **Error Handling**: Include proper error handling for tool calls and multimodal inputs +5. **Validation**: Validate message structure before sending to the model + +> [!WARNING] +> Common pitfalls to avoid: +> - Mixing different template formats in the same application +> - Exceeding token limits with long conversation histories +> - Not properly escaping special characters in messages +> - Forgetting to validate input message structure +> - Ignoring model-specific template requirements + +## Hands-on Exercise + +Let's practice implementing chat templates with a real-world example. + +> [!TIP] +> Follow these steps to convert the `HuggingFaceTB/smoltalk` dataset into chatml format: +> +> 1. Load the dataset: +> ```python +> from datasets import load_dataset +> +> dataset = load_dataset("HuggingFaceTB/smoltalk") +> ``` +> +> 2. Create a processing function: +> ```python +> def convert_to_chatml(example): +> return { +> "messages": [ +> {"role": "user", "content": example["input"]}, +> {"role": "assistant", "content": example["output"]}, +> ] +> } +> ``` +> +> 3. Apply the chat template using your chosen model's tokenizer +> +> Remember to validate your output format matches your target model's requirements! + +## Additional Resources + +- [Hugging Face Chat Templating Guide](https://huggingface.co/docs/transformers/main/en/chat_templating) +- [Transformers Documentation](https://huggingface.co/docs/transformers) +- [Chat Templates Examples Repository](https://github.com/chujiezheng/chat_templates) diff --git a/chapters/en/chapter11/3.mdx b/chapters/en/chapter11/3.mdx index 2967f7bbc..eda64dd26 100644 --- a/chapters/en/chapter11/3.mdx +++ b/chapters/en/chapter11/3.mdx @@ -1,378 +1,378 @@ - - -# Supervised Fine-Tuning - -Supervised Fine-Tuning (SFT) is a process primarily used to adapt pre-trained language models to follow instructions, engage in dialogue, and use specific output formats. While pre-trained models have impressive general capabilities, SFT helps transform them into assistant-like models that can better understand and respond to user prompts. This is typically done by training on datasets of human-written conversations and instructions. - -This page provides a step-by-step guide to fine-tuning the [`deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B`](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B) model using the [`SFTTrainer`](https://huggingface.co/docs/trl/en/sft_trainer). By following these steps, you can adapt the model to perform specific tasks more effectively. - -## When to Use SFT - -Before diving into implementation, it's important to understand when SFT is the right choice for your project. As a first step, you should consider whether using an existing instruction-tuned model with well-crafted prompts would suffice for your use case. SFT involves significant computational resources and engineering effort, so it should only be pursued when prompting existing models proves insufficient. - -> [!TIP] -> Consider SFT only if you: -> - Need additional performance beyond what prompting can achieve -> - Have a specific use case where the cost of using a large general-purpose model outweighs the cost of fine-tuning a smaller model -> - Require specialized output formats or domain-specific knowledge that existing models struggle with - -If you determine that SFT is necessary, the decision to proceed depends on two primary factors: - -### Template Control -SFT allows precise control over the model's output structure. This is particularly valuable when you need the model to: -1. Generate responses in a specific chat template format -2. Follow strict output schemas -3. Maintain consistent styling across responses - -### Domain Adaptation -When working in specialized domains, SFT helps align the model with domain-specific requirements by: -1. Teaching domain terminology and concepts -2. Enforcing professional standards -3. Handling technical queries appropriately -4. Following industry-specific guidelines - -> [!TIP] -> Before starting SFT, evaluate whether your use case requires: -> - Precise output formatting -> - Domain-specific knowledge -> - Consistent response patterns -> - Adherence to specific guidelines -> -> This evaluation will help determine if SFT is the right approach for your needs. - -## Dataset Preparation - -The supervised fine-tuning process requires a task-specific dataset structured with input-output pairs. Each pair should consist of: -1. An input prompt -2. The expected model response -3. Any additional context or metadata - -The quality of your training data is crucial for successful fine-tuning. Let's look at how to prepare and validate your dataset: - - - -## Training Configuration - -The success of your fine-tuning depends heavily on choosing the right training parameters. Let's explore each important parameter and how to configure them effectively: - -The SFTTrainer configuration requires consideration of several parameters that control the training process. Let's explore each parameter and their purpose: - -1. **Training Duration Parameters**: - - `num_train_epochs`: Controls total training duration - - `max_steps`: Alternative to epochs, sets maximum number of training steps - - More epochs allow better learning but risk overfitting - -2. **Batch Size Parameters**: - - `per_device_train_batch_size`: Determines memory usage and training stability - - `gradient_accumulation_steps`: Enables larger effective batch sizes - - Larger batches provide more stable gradients but require more memory - -3. **Learning Rate Parameters**: - - `learning_rate`: Controls size of weight updates - - `warmup_ratio`: Portion of training used for learning rate warmup - - Too high can cause instability, too low results in slow learning - -4. **Monitoring Parameters**: - - `logging_steps`: Frequency of metric logging - - `eval_steps`: How often to evaluate on validation data - - `save_steps`: Frequency of model checkpoint saves - -> [!TIP] -> Start with conservative values and adjust based on monitoring: -> - Begin with 1-3 epochs -> - Use smaller batch sizes initially -> - Monitor validation metrics closely -> - Adjust learning rate if training is unstable - -## Implementation with TRL - -Now that we understand the key components, let's implement the training with proper validation and monitoring. We will use the `SFTTrainer` class from the Transformers Reinforcement Learning (TRL) library, which is built on top of the `transformers` library. Here's a complete example using the TRL library: - -```python -from datasets import load_dataset -from trl import SFTConfig, SFTTrainer -import torch - -# Set device -device = "cuda" if torch.cuda.is_available() else "cpu" - -# Load dataset -dataset = load_dataset("HuggingFaceTB/smoltalk", "all") - -# Configure model and tokenizer -model_name = "HuggingFaceTB/SmolLM2-135M" -model = AutoModelForCausalLM.from_pretrained(pretrained_model_name_or_path=model_name).to( - device -) -tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path=model_name) -# Setup chat template -model, tokenizer = setup_chat_format(model=model, tokenizer=tokenizer) - -# Configure trainer -training_args = SFTConfig( - output_dir="./sft_output", - max_steps=1000, - per_device_train_batch_size=4, - learning_rate=5e-5, - logging_steps=10, - save_steps=100, - eval_strategy="steps", - eval_steps=50, -) - -# Initialize trainer -trainer = SFTTrainer( - model=model, - args=training_args, - train_dataset=dataset["train"], - eval_dataset=dataset["test"], - processing_class=tokenizer, -) - -# Start training -trainer.train() -``` - -> [!TIP] -> When using a dataset with a "messages" field (like the example above), the SFTTrainer automatically applies the model's chat template, which it retrieves from the hub. This means you don't need any additional configuration to handle chat-style conversations - the trainer will format the messages according to the model's expected template format. - -## Packing the Dataset - -The SFTTrainer supports example packing to optimize training efficiency. This feature allows multiple short examples to be packed into the same input sequence, maximizing GPU utilization during training. To enable packing, simply set `packing=True` in the SFTConfig constructor. When using packed datasets with `max_steps`, be aware that you may train for more epochs than expected depending on your packing configuration. You can customize how examples are combined using a formatting function - particularly useful when working with datasets that have multiple fields like question-answer pairs. For evaluation datasets, you can disable packing by setting `eval_packing=False` in the SFTConfig. Here's a basic example of customizing the packing configuration: - -```python -# Configure packing -training_args = SFTConfig(packing=True) - -trainer = SFTTrainer(model=model, train_dataset=dataset, args=training_args) - -trainer.train() -``` - -When packing the dataset with multiple fields, you can define a custom formatting function to combine the fields into a single input sequence. This function should take a list of examples and return a dictionary with the packed input sequence. Here's an example of a custom formatting function: - -```python -def formatting_func(example): - text = f"### Question: {example['question']}\n ### Answer: {example['answer']}" - return text - - -training_args = SFTConfig(packing=True) -trainer = SFTTrainer( - "facebook/opt-350m", - train_dataset=dataset, - args=training_args, - formatting_func=formatting_func, -) -``` - -## Monitoring Training Progress - -Effective monitoring is crucial for successful fine-tuning. Let's explore what to watch for during training: - -### Understanding Loss Patterns - -Training loss typically follows three distinct phases: -1. Initial Sharp Drop: Rapid adaptation to new data distribution -2. Gradual Stabilization: Learning rate slows as model fine-tunes -3. Convergence: Loss values stabilize, indicating training completion - -SFTTrainer Training - -### Metrics to Monitor - -Effective monitoring involves tracking quantitative metrics, and evaluating qualitative metrics. Available metrics are: - -- Training loss -- Validation loss -- Learning rate progression -- Gradient norms - -> [!WARNING] -> Watch for these warning signs during training: -> 1. Validation loss increasing while training loss decreases (overfitting) -> 2. No significant improvement in loss values (underfitting) -> 3. Extremely low loss values (potential memorization) -> 4. Inconsistent output formatting (template learning issues) - -### The Path to Convergence - -As training progresses, the loss curve should gradually stabilize. The key indicator of healthy training is a small gap between training and validation loss, suggesting -the model is learning generalizable patterns rather than memorizing specific examples. The absolute loss values will vary depending on your task and dataset. - -### Monitoring Training Progress - -The graph above shows a typical training progression. Notice how both training and validation loss decrease sharply at first, then gradually level off. This pattern indicates the model is learning effectively while maintaining generalization ability. - -### Warning Signs to Watch For - -Several patterns in the loss curves can indicate potential issues. Below we illustrate common warning signs and solutions that we can consider. - -SFTTrainer Training - -If the validation loss decreases at a significantly slower rate than training loss, your model is likely overfitting to the training data. Consider: -- Reducing the training steps -- Increasing the dataset size -- Validating dataset quality and diversity - -SFTTrainer Training - -If the loss doesn't show significant improvement, the model might be: -- Learning too slowly (try increasing the learning rate) -- Struggling with the task (check data quality and task complexity) -- Hitting architecture limitations (consider a different model) - -SFTTrainer Training - -Extremely low loss values could suggest memorization rather than learning. This is particularly concerning if: -- The model performs poorly on new, similar examples -- The outputs lack diversity -- The responses are too similar to training examples - -> [!WARNING] -> Monitor both the loss values and the model's actual outputs during training. Sometimes the loss can look good while the model develops unwanted behaviors. Regular qualitative evaluation of the model's responses helps catch issues that metrics alone might miss. - -We should note that the interpretation of the loss values we outline here is aimed on the most common case, and in fact, loss values can behave on various ways depending on the model, the dataset, the training parameters, etc. If you interested in exploring more about outlined patterns, you should check out this blog post by the people at [Fast AI](https://www.fast.ai/posts/2023-09-04-learning-jumps/). - -## Evaluation after SFT - -In section [11.4](/en/chapter11/4) we will learn how to evaluate the model using benchmark datasets. For now, we will focus on the qualitative evaluation of the model. - -After completing SFT, consider these follow-up actions: - -1. Evaluate the model thoroughly on held-out test data -2. Validate template adherence across various inputs -3. Test domain-specific knowledge retention -4. Monitor real-world performance metrics - -> [!TIP] -> Document your training process, including: -> - Dataset characteristics -> - Training parameters -> - Performance metrics -> - Known limitations -> This documentation will be valuable for future model iterations. - -## Quiz - -### 1. What parameters control the training duration in SFT? - - - -### 2. Which pattern in the loss curves indicates potential overfitting? - - - -### 3. What is gradient_accumulation_steps used for? - - - -### 4. What should you monitor during SFT training? - - - -### 5. What indicates healthy convergence during training? - - - -## 💐 Nice work! - -You've learned how to fine-tune models using SFT! To continue your learning: -1. Try the notebook with different parameters -2. Experiment with other datasets -3. Contribute improvements to the course material - -## Additional Resources - -- [TRL Documentation](https://huggingface.co/docs/trl) -- [SFT Examples Repository](https://github.com/huggingface/trl/blob/main/trl/scripts/sft.py) -- [Fine-tuning Best Practices](https://huggingface.co/docs/transformers/training) + + +# Supervised Fine-Tuning + +Supervised Fine-Tuning (SFT) is a process primarily used to adapt pre-trained language models to follow instructions, engage in dialogue, and use specific output formats. While pre-trained models have impressive general capabilities, SFT helps transform them into assistant-like models that can better understand and respond to user prompts. This is typically done by training on datasets of human-written conversations and instructions. + +This page provides a step-by-step guide to fine-tuning the [`deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B`](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B) model using the [`SFTTrainer`](https://huggingface.co/docs/trl/en/sft_trainer). By following these steps, you can adapt the model to perform specific tasks more effectively. + +## When to Use SFT + +Before diving into implementation, it's important to understand when SFT is the right choice for your project. As a first step, you should consider whether using an existing instruction-tuned model with well-crafted prompts would suffice for your use case. SFT involves significant computational resources and engineering effort, so it should only be pursued when prompting existing models proves insufficient. + +> [!TIP] +> Consider SFT only if you: +> - Need additional performance beyond what prompting can achieve +> - Have a specific use case where the cost of using a large general-purpose model outweighs the cost of fine-tuning a smaller model +> - Require specialized output formats or domain-specific knowledge that existing models struggle with + +If you determine that SFT is necessary, the decision to proceed depends on two primary factors: + +### Template Control +SFT allows precise control over the model's output structure. This is particularly valuable when you need the model to: +1. Generate responses in a specific chat template format +2. Follow strict output schemas +3. Maintain consistent styling across responses + +### Domain Adaptation +When working in specialized domains, SFT helps align the model with domain-specific requirements by: +1. Teaching domain terminology and concepts +2. Enforcing professional standards +3. Handling technical queries appropriately +4. Following industry-specific guidelines + +> [!TIP] +> Before starting SFT, evaluate whether your use case requires: +> - Precise output formatting +> - Domain-specific knowledge +> - Consistent response patterns +> - Adherence to specific guidelines +> +> This evaluation will help determine if SFT is the right approach for your needs. + +## Dataset Preparation + +The supervised fine-tuning process requires a task-specific dataset structured with input-output pairs. Each pair should consist of: +1. An input prompt +2. The expected model response +3. Any additional context or metadata + +The quality of your training data is crucial for successful fine-tuning. Let's look at how to prepare and validate your dataset: + + + +## Training Configuration + +The success of your fine-tuning depends heavily on choosing the right training parameters. Let's explore each important parameter and how to configure them effectively: + +The SFTTrainer configuration requires consideration of several parameters that control the training process. Let's explore each parameter and their purpose: + +1. **Training Duration Parameters**: + - `num_train_epochs`: Controls total training duration + - `max_steps`: Alternative to epochs, sets maximum number of training steps + - More epochs allow better learning but risk overfitting + +2. **Batch Size Parameters**: + - `per_device_train_batch_size`: Determines memory usage and training stability + - `gradient_accumulation_steps`: Enables larger effective batch sizes + - Larger batches provide more stable gradients but require more memory + +3. **Learning Rate Parameters**: + - `learning_rate`: Controls size of weight updates + - `warmup_ratio`: Portion of training used for learning rate warmup + - Too high can cause instability, too low results in slow learning + +4. **Monitoring Parameters**: + - `logging_steps`: Frequency of metric logging + - `eval_steps`: How often to evaluate on validation data + - `save_steps`: Frequency of model checkpoint saves + +> [!TIP] +> Start with conservative values and adjust based on monitoring: +> - Begin with 1-3 epochs +> - Use smaller batch sizes initially +> - Monitor validation metrics closely +> - Adjust learning rate if training is unstable + +## Implementation with TRL + +Now that we understand the key components, let's implement the training with proper validation and monitoring. We will use the `SFTTrainer` class from the Transformers Reinforcement Learning (TRL) library, which is built on top of the `transformers` library. Here's a complete example using the TRL library: + +```python +from datasets import load_dataset +from trl import SFTConfig, SFTTrainer +import torch + +# Set device +device = "cuda" if torch.cuda.is_available() else "cpu" + +# Load dataset +dataset = load_dataset("HuggingFaceTB/smoltalk", "all") + +# Configure model and tokenizer +model_name = "HuggingFaceTB/SmolLM2-135M" +model = AutoModelForCausalLM.from_pretrained(pretrained_model_name_or_path=model_name).to( + device +) +tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path=model_name) +# Setup chat template +model, tokenizer = setup_chat_format(model=model, tokenizer=tokenizer) + +# Configure trainer +training_args = SFTConfig( + output_dir="./sft_output", + max_steps=1000, + per_device_train_batch_size=4, + learning_rate=5e-5, + logging_steps=10, + save_steps=100, + eval_strategy="steps", + eval_steps=50, +) + +# Initialize trainer +trainer = SFTTrainer( + model=model, + args=training_args, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], + processing_class=tokenizer, +) + +# Start training +trainer.train() +``` + +> [!TIP] +> When using a dataset with a "messages" field (like the example above), the SFTTrainer automatically applies the model's chat template, which it retrieves from the hub. This means you don't need any additional configuration to handle chat-style conversations - the trainer will format the messages according to the model's expected template format. + +## Packing the Dataset + +The SFTTrainer supports example packing to optimize training efficiency. This feature allows multiple short examples to be packed into the same input sequence, maximizing GPU utilization during training. To enable packing, simply set `packing=True` in the SFTConfig constructor. When using packed datasets with `max_steps`, be aware that you may train for more epochs than expected depending on your packing configuration. You can customize how examples are combined using a formatting function - particularly useful when working with datasets that have multiple fields like question-answer pairs. For evaluation datasets, you can disable packing by setting `eval_packing=False` in the SFTConfig. Here's a basic example of customizing the packing configuration: + +```python +# Configure packing +training_args = SFTConfig(packing=True) + +trainer = SFTTrainer(model=model, train_dataset=dataset, args=training_args) + +trainer.train() +``` + +When packing the dataset with multiple fields, you can define a custom formatting function to combine the fields into a single input sequence. This function should take a list of examples and return a dictionary with the packed input sequence. Here's an example of a custom formatting function: + +```python +def formatting_func(example): + text = f"### Question: {example['question']}\n ### Answer: {example['answer']}" + return text + + +training_args = SFTConfig(packing=True) +trainer = SFTTrainer( + "facebook/opt-350m", + train_dataset=dataset, + args=training_args, + formatting_func=formatting_func, +) +``` + +## Monitoring Training Progress + +Effective monitoring is crucial for successful fine-tuning. Let's explore what to watch for during training: + +### Understanding Loss Patterns + +Training loss typically follows three distinct phases: +1. Initial Sharp Drop: Rapid adaptation to new data distribution +2. Gradual Stabilization: Learning rate slows as model fine-tunes +3. Convergence: Loss values stabilize, indicating training completion + +SFTTrainer Training + +### Metrics to Monitor + +Effective monitoring involves tracking quantitative metrics, and evaluating qualitative metrics. Available metrics are: + +- Training loss +- Validation loss +- Learning rate progression +- Gradient norms + +> [!WARNING] +> Watch for these warning signs during training: +> 1. Validation loss increasing while training loss decreases (overfitting) +> 2. No significant improvement in loss values (underfitting) +> 3. Extremely low loss values (potential memorization) +> 4. Inconsistent output formatting (template learning issues) + +### The Path to Convergence + +As training progresses, the loss curve should gradually stabilize. The key indicator of healthy training is a small gap between training and validation loss, suggesting +the model is learning generalizable patterns rather than memorizing specific examples. The absolute loss values will vary depending on your task and dataset. + +### Monitoring Training Progress + +The graph above shows a typical training progression. Notice how both training and validation loss decrease sharply at first, then gradually level off. This pattern indicates the model is learning effectively while maintaining generalization ability. + +### Warning Signs to Watch For + +Several patterns in the loss curves can indicate potential issues. Below we illustrate common warning signs and solutions that we can consider. + +SFTTrainer Training + +If the validation loss decreases at a significantly slower rate than training loss, your model is likely overfitting to the training data. Consider: +- Reducing the training steps +- Increasing the dataset size +- Validating dataset quality and diversity + +SFTTrainer Training + +If the loss doesn't show significant improvement, the model might be: +- Learning too slowly (try increasing the learning rate) +- Struggling with the task (check data quality and task complexity) +- Hitting architecture limitations (consider a different model) + +SFTTrainer Training + +Extremely low loss values could suggest memorization rather than learning. This is particularly concerning if: +- The model performs poorly on new, similar examples +- The outputs lack diversity +- The responses are too similar to training examples + +> [!WARNING] +> Monitor both the loss values and the model's actual outputs during training. Sometimes the loss can look good while the model develops unwanted behaviors. Regular qualitative evaluation of the model's responses helps catch issues that metrics alone might miss. + +We should note that the interpretation of the loss values we outline here is aimed on the most common case, and in fact, loss values can behave on various ways depending on the model, the dataset, the training parameters, etc. If you interested in exploring more about outlined patterns, you should check out this blog post by the people at [Fast AI](https://www.fast.ai/posts/2023-09-04-learning-jumps/). + +## Evaluation after SFT + +In section [11.4](/en/chapter11/4) we will learn how to evaluate the model using benchmark datasets. For now, we will focus on the qualitative evaluation of the model. + +After completing SFT, consider these follow-up actions: + +1. Evaluate the model thoroughly on held-out test data +2. Validate template adherence across various inputs +3. Test domain-specific knowledge retention +4. Monitor real-world performance metrics + +> [!TIP] +> Document your training process, including: +> - Dataset characteristics +> - Training parameters +> - Performance metrics +> - Known limitations +> This documentation will be valuable for future model iterations. + +## Quiz + +### 1. What parameters control the training duration in SFT? + + + +### 2. Which pattern in the loss curves indicates potential overfitting? + + + +### 3. What is gradient_accumulation_steps used for? + + + +### 4. What should you monitor during SFT training? + + + +### 5. What indicates healthy convergence during training? + + + +## 💐 Nice work! + +You've learned how to fine-tune models using SFT! To continue your learning: +1. Try the notebook with different parameters +2. Experiment with other datasets +3. Contribute improvements to the course material + +## Additional Resources + +- [TRL Documentation](https://huggingface.co/docs/trl) +- [SFT Examples Repository](https://github.com/huggingface/trl/blob/main/trl/scripts/sft.py) +- [Fine-tuning Best Practices](https://huggingface.co/docs/transformers/training) diff --git a/chapters/en/chapter11/4.mdx b/chapters/en/chapter11/4.mdx index 838cfff75..3625e23dd 100644 --- a/chapters/en/chapter11/4.mdx +++ b/chapters/en/chapter11/4.mdx @@ -1,164 +1,164 @@ - - -# LoRA (Low-Rank Adaptation) - -Fine-tuning large language models is a resource intensive process. LoRA is a technique that allows us to fine-tune large language models with a small number of parameters. It works by adding and optimizing smaller matrices to the attention weights, typically reducing trainable parameters by about 90%. - -## Understanding LoRA - -LoRA (Low-Rank Adaptation) is a parameter-efficient fine-tuning technique that freezes the pre-trained model weights and injects trainable rank decomposition matrices into the model's layers. Instead of training all model parameters during fine-tuning, LoRA decomposes the weight updates into smaller matrices through low-rank decomposition, significantly reducing the number of trainable parameters while maintaining model performance. For example, when applied to GPT-3 175B, LoRA reduced trainable parameters by 10,000x and GPU memory requirements by 3x compared to full fine-tuning. You can read more about LoRA in the [LoRA paper](https://arxiv.org/pdf/2106.09685). - -LoRA works by adding pairs of rank decomposition matrices to transformer layers, typically focusing on attention weights. During inference, these adapter weights can be merged with the base model, resulting in no additional latency overhead. LoRA is particularly useful for adapting large language models to specific tasks or domains while keeping resource requirements manageable. - -## Key advantages of LoRA - -1. **Memory Efficiency**: - - Only adapter parameters are stored in GPU memory - - Base model weights remain frozen and can be loaded in lower precision - - Enables fine-tuning of large models on consumer GPUs - -2. **Training Features**: - - Native PEFT/LoRA integration with minimal setup - - Support for QLoRA (Quantized LoRA) for even better memory efficiency - -3. **Adapter Management**: - - Adapter weight saving during checkpoints - - Features to merge adapters back into base model - -## Loading LoRA Adapters with PEFT - -[PEFT](https://github.com/huggingface/peft) is a library that provides a unified interface for loading and managing PEFT methods, including LoRA. It allows you to easily load and switch between different PEFT methods, making it easier to experiment with different fine-tuning techniques. - -Adapters can be loaded onto a pretrained model with `load_adapter()`, which is useful for trying out different adapters whose weights aren't merged. Set the active adapter weights with the `set_adapter()` function. To return the base model, you could use unload() to unload all of the LoRA modules. This makes it easy to switch between different task-specific weights. - -```python -from peft import PeftModel, PeftConfig - -config = PeftConfig.from_pretrained("ybelkada/opt-350m-lora") -model = AutoModelForCausalLM.from_pretrained(config.base_model_name_or_path) -lora_model = PeftModel.from_pretrained(model, "ybelkada/opt-350m-lora") -``` - -![lora_load_adapter](https://github.com/huggingface/smol-course/raw/main/v1/3_parameter_efficient_finetuning/images/lora_adapter.png) - -## Fine-tune LLM using `trl` and the `SFTTrainer` with LoRA - -The [SFTTrainer](https://huggingface.co/docs/trl/sft_trainer) from `trl` provides integration with LoRA adapters through the [PEFT](https://huggingface.co/docs/peft/en/index) library. This means that we can fine-tune a model in the same way as we did with SFT, but use LoRA to reduce the number of parameters we need to train. - -We'll use the `LoRAConfig` class from PEFT in our example. The setup requires just a few configuration steps: - -1. Define the LoRA configuration (rank, alpha, dropout) -2. Create the SFTTrainer with PEFT config -3. Train and save the adapter weights - -## LoRA Configuration - -Let's walk through the LoRA configuration and key parameters. - -| Parameter | Description | -|-----------|-------------| -| `r` (rank) | Dimension of the low-rank matrices used for weight updates. Typically between 4-32. Lower values provide more compression but potentially less expressiveness. | -| `lora_alpha` | Scaling factor for LoRA layers, usually set to 2x the rank value. Higher values result in stronger adaptation effects. | -| `lora_dropout` | Dropout probability for LoRA layers, typically 0.05-0.1. Higher values help prevent overfitting during training. | -| `bias` | Controls training of bias terms. Options are "none", "all", or "lora_only". "none" is most common for memory efficiency. | -| `target_modules` | Specifies which model modules to apply LoRA to. Can be "all-linear" or specific modules like "q_proj,v_proj". More modules enable greater adaptability but increase memory usage. | - -> [!TIP] -> When implementing PEFT methods, start with small rank values (4-8) for LoRA and monitor training loss. Use validation sets to prevent overfitting and compare results with full fine-tuning baselines when possible. The effectiveness of different methods can vary by task, so experimentation is key. - -## Using TRL with PEFT - -PEFT methods can be combined with TRL for fine-tuning to reduce memory requirements. We can pass the `LoraConfig` to the model when loading it. - -```python -from peft import LoraConfig - -# r: rank dimension for LoRA update matrices (smaller = more compression) -rank_dimension = 6 -# lora_alpha: scaling factor for LoRA layers (higher = stronger adaptation) -lora_alpha = 8 -# lora_dropout: dropout probability for LoRA layers (helps prevent overfitting) -lora_dropout = 0.05 - -peft_config = LoraConfig( - r=rank_dimension, # Rank dimension - typically between 4-32 - lora_alpha=lora_alpha, # LoRA scaling factor - typically 2x rank - lora_dropout=lora_dropout, # Dropout probability for LoRA layers - bias="none", # Bias type for LoRA. the corresponding biases will be updated during training. - target_modules="all-linear", # Which modules to apply LoRA to - task_type="CAUSAL_LM", # Task type for model architecture -) -``` - -Above, we used `device_map="auto"` to automatically assign the model to the correct device. You can also manually assign the model to a specific device using `device_map={"": device_index}`. - -We will also need to define the `SFTTrainer` with the LoRA configuration. - -```python -# Create SFTTrainer with LoRA configuration -trainer = SFTTrainer( - model=model, - args=args, - train_dataset=dataset["train"], - peft_config=peft_config, # LoRA configuration - max_seq_length=max_seq_length, # Maximum sequence length - processing_class=tokenizer, -) -``` - -> [!TIP] -> ✏️ **Try it out!** Build on your fine-tuned model from the previous section, but fine-tune it with LoRA. Use the `HuggingFaceTB/smoltalk` dataset to fine-tune a `deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B` model, using the LoRA configuration we defined above. - -## Merging LoRA Adapters - -After training with LoRA, you might want to merge the adapter weights back into the base model for easier deployment. This creates a single model with the combined weights, eliminating the need to load adapters separately during inference. - -The merging process requires attention to memory management and precision. Since you'll need to load both the base model and adapter weights simultaneously, ensure sufficient GPU/CPU memory is available. Using `device_map="auto"` in `transformers` will find the correct device for the model based on your hardware. - -Maintain consistent precision (e.g., float16) throughout the process, matching the precision used during training and saving the merged model in the same format for deployment. - -## Merging Implementation - -After training a LoRA adapter, you can merge the adapter weights back into the base model. Here's how to do it: - -```python -import torch -from transformers import AutoModelForCausalLM -from peft import PeftModel - -# 1. Load the base model -base_model = AutoModelForCausalLM.from_pretrained( - "base_model_name", torch_dtype=torch.float16, device_map="auto" -) - -# 2. Load the PEFT model with adapter -peft_model = PeftModel.from_pretrained( - base_model, "path/to/adapter", torch_dtype=torch.float16 -) - -# 3. Merge adapter weights with base model -merged_model = peft_model.merge_and_unload() -``` - -If you encounter size discrepancies in the saved model, ensure you're also saving the tokenizer: - -```python -# Save both model and tokenizer -tokenizer = AutoTokenizer.from_pretrained("base_model_name") -merged_model.save_pretrained("path/to/save/merged_model") -tokenizer.save_pretrained("path/to/save/merged_model") -``` - -> [!TIP] -> ✏️ **Try it out!** Merge the adapter weights back into the base model. Use the `HuggingFaceTB/smoltalk` dataset to fine-tune a `deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B` model, using the LoRA configuration we defined above. - - -# Resources - -- [LoRA: Low-Rank Adaptation of Large Language Models](https://arxiv.org/pdf/2106.09685) -- [PEFT Documentation](https://huggingface.co/docs/peft) -- [Hugging Face blog post on PEFT](https://huggingface.co/blog/peft) + + +# LoRA (Low-Rank Adaptation) + +Fine-tuning large language models is a resource intensive process. LoRA is a technique that allows us to fine-tune large language models with a small number of parameters. It works by adding and optimizing smaller matrices to the attention weights, typically reducing trainable parameters by about 90%. + +## Understanding LoRA + +LoRA (Low-Rank Adaptation) is a parameter-efficient fine-tuning technique that freezes the pre-trained model weights and injects trainable rank decomposition matrices into the model's layers. Instead of training all model parameters during fine-tuning, LoRA decomposes the weight updates into smaller matrices through low-rank decomposition, significantly reducing the number of trainable parameters while maintaining model performance. For example, when applied to GPT-3 175B, LoRA reduced trainable parameters by 10,000x and GPU memory requirements by 3x compared to full fine-tuning. You can read more about LoRA in the [LoRA paper](https://arxiv.org/pdf/2106.09685). + +LoRA works by adding pairs of rank decomposition matrices to transformer layers, typically focusing on attention weights. During inference, these adapter weights can be merged with the base model, resulting in no additional latency overhead. LoRA is particularly useful for adapting large language models to specific tasks or domains while keeping resource requirements manageable. + +## Key advantages of LoRA + +1. **Memory Efficiency**: + - Only adapter parameters are stored in GPU memory + - Base model weights remain frozen and can be loaded in lower precision + - Enables fine-tuning of large models on consumer GPUs + +2. **Training Features**: + - Native PEFT/LoRA integration with minimal setup + - Support for QLoRA (Quantized LoRA) for even better memory efficiency + +3. **Adapter Management**: + - Adapter weight saving during checkpoints + - Features to merge adapters back into base model + +## Loading LoRA Adapters with PEFT + +[PEFT](https://github.com/huggingface/peft) is a library that provides a unified interface for loading and managing PEFT methods, including LoRA. It allows you to easily load and switch between different PEFT methods, making it easier to experiment with different fine-tuning techniques. + +Adapters can be loaded onto a pretrained model with `load_adapter()`, which is useful for trying out different adapters whose weights aren't merged. Set the active adapter weights with the `set_adapter()` function. To return the base model, you could use unload() to unload all of the LoRA modules. This makes it easy to switch between different task-specific weights. + +```python +from peft import PeftModel, PeftConfig + +config = PeftConfig.from_pretrained("ybelkada/opt-350m-lora") +model = AutoModelForCausalLM.from_pretrained(config.base_model_name_or_path) +lora_model = PeftModel.from_pretrained(model, "ybelkada/opt-350m-lora") +``` + +![lora_load_adapter](https://github.com/huggingface/smol-course/raw/main/v1/3_parameter_efficient_finetuning/images/lora_adapter.png) + +## Fine-tune LLM using `trl` and the `SFTTrainer` with LoRA + +The [SFTTrainer](https://huggingface.co/docs/trl/sft_trainer) from `trl` provides integration with LoRA adapters through the [PEFT](https://huggingface.co/docs/peft/en/index) library. This means that we can fine-tune a model in the same way as we did with SFT, but use LoRA to reduce the number of parameters we need to train. + +We'll use the `LoRAConfig` class from PEFT in our example. The setup requires just a few configuration steps: + +1. Define the LoRA configuration (rank, alpha, dropout) +2. Create the SFTTrainer with PEFT config +3. Train and save the adapter weights + +## LoRA Configuration + +Let's walk through the LoRA configuration and key parameters. + +| Parameter | Description | +|-----------|-------------| +| `r` (rank) | Dimension of the low-rank matrices used for weight updates. Typically between 4-32. Lower values provide more compression but potentially less expressiveness. | +| `lora_alpha` | Scaling factor for LoRA layers, usually set to 2x the rank value. Higher values result in stronger adaptation effects. | +| `lora_dropout` | Dropout probability for LoRA layers, typically 0.05-0.1. Higher values help prevent overfitting during training. | +| `bias` | Controls training of bias terms. Options are "none", "all", or "lora_only". "none" is most common for memory efficiency. | +| `target_modules` | Specifies which model modules to apply LoRA to. Can be "all-linear" or specific modules like "q_proj,v_proj". More modules enable greater adaptability but increase memory usage. | + +> [!TIP] +> When implementing PEFT methods, start with small rank values (4-8) for LoRA and monitor training loss. Use validation sets to prevent overfitting and compare results with full fine-tuning baselines when possible. The effectiveness of different methods can vary by task, so experimentation is key. + +## Using TRL with PEFT + +PEFT methods can be combined with TRL for fine-tuning to reduce memory requirements. We can pass the `LoraConfig` to the model when loading it. + +```python +from peft import LoraConfig + +# r: rank dimension for LoRA update matrices (smaller = more compression) +rank_dimension = 6 +# lora_alpha: scaling factor for LoRA layers (higher = stronger adaptation) +lora_alpha = 8 +# lora_dropout: dropout probability for LoRA layers (helps prevent overfitting) +lora_dropout = 0.05 + +peft_config = LoraConfig( + r=rank_dimension, # Rank dimension - typically between 4-32 + lora_alpha=lora_alpha, # LoRA scaling factor - typically 2x rank + lora_dropout=lora_dropout, # Dropout probability for LoRA layers + bias="none", # Bias type for LoRA. the corresponding biases will be updated during training. + target_modules="all-linear", # Which modules to apply LoRA to + task_type="CAUSAL_LM", # Task type for model architecture +) +``` + +Above, we used `device_map="auto"` to automatically assign the model to the correct device. You can also manually assign the model to a specific device using `device_map={"": device_index}`. + +We will also need to define the `SFTTrainer` with the LoRA configuration. + +```python +# Create SFTTrainer with LoRA configuration +trainer = SFTTrainer( + model=model, + args=args, + train_dataset=dataset["train"], + peft_config=peft_config, # LoRA configuration + max_seq_length=max_seq_length, # Maximum sequence length + processing_class=tokenizer, +) +``` + +> [!TIP] +> ✏️ **Try it out!** Build on your fine-tuned model from the previous section, but fine-tune it with LoRA. Use the `HuggingFaceTB/smoltalk` dataset to fine-tune a `deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B` model, using the LoRA configuration we defined above. + +## Merging LoRA Adapters + +After training with LoRA, you might want to merge the adapter weights back into the base model for easier deployment. This creates a single model with the combined weights, eliminating the need to load adapters separately during inference. + +The merging process requires attention to memory management and precision. Since you'll need to load both the base model and adapter weights simultaneously, ensure sufficient GPU/CPU memory is available. Using `device_map="auto"` in `transformers` will find the correct device for the model based on your hardware. + +Maintain consistent precision (e.g., float16) throughout the process, matching the precision used during training and saving the merged model in the same format for deployment. + +## Merging Implementation + +After training a LoRA adapter, you can merge the adapter weights back into the base model. Here's how to do it: + +```python +import torch +from transformers import AutoModelForCausalLM +from peft import PeftModel + +# 1. Load the base model +base_model = AutoModelForCausalLM.from_pretrained( + "base_model_name", torch_dtype=torch.float16, device_map="auto" +) + +# 2. Load the PEFT model with adapter +peft_model = PeftModel.from_pretrained( + base_model, "path/to/adapter", torch_dtype=torch.float16 +) + +# 3. Merge adapter weights with base model +merged_model = peft_model.merge_and_unload() +``` + +If you encounter size discrepancies in the saved model, ensure you're also saving the tokenizer: + +```python +# Save both model and tokenizer +tokenizer = AutoTokenizer.from_pretrained("base_model_name") +merged_model.save_pretrained("path/to/save/merged_model") +tokenizer.save_pretrained("path/to/save/merged_model") +``` + +> [!TIP] +> ✏️ **Try it out!** Merge the adapter weights back into the base model. Use the `HuggingFaceTB/smoltalk` dataset to fine-tune a `deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B` model, using the LoRA configuration we defined above. + + +# Resources + +- [LoRA: Low-Rank Adaptation of Large Language Models](https://arxiv.org/pdf/2106.09685) +- [PEFT Documentation](https://huggingface.co/docs/peft) +- [Hugging Face blog post on PEFT](https://huggingface.co/blog/peft) diff --git a/chapters/en/chapter11/5.mdx b/chapters/en/chapter11/5.mdx index 479521698..24b3c50b4 100644 --- a/chapters/en/chapter11/5.mdx +++ b/chapters/en/chapter11/5.mdx @@ -1,251 +1,251 @@ -# Evaluation - -With a finetuned model through either SFT or LoRA SFT, we should evaluate it on standard benchmarks. As machine learning engineers you should maintain a suite of relevant evaluations for your targeted domain of interest. In this page, we will look at some of the most common benchmarks and how to use them to evaluate your model. We'll also look at how to create custom benchmarks for your specific use case. - -## Automatic Benchmarks - -Automatic benchmarks serve as standardized tools for evaluating language models across different tasks and capabilities. While they provide a useful starting point for understanding model performance, it's important to recognize that they represent only one piece of a comprehensive evaluation strategy. - -## Understanding Automatic Benchmarks - -Automatic benchmarks typically consist of curated datasets with predefined tasks and evaluation metrics. These benchmarks aim to assess various aspects of model capability, from basic language understanding to complex reasoning. The key advantage of using automatic benchmarks is their standardization - they allow for consistent comparison across different models and provide reproducible results. - -However, it's crucial to understand that benchmark performance doesn't always translate directly to real-world effectiveness. A model that excels at academic benchmarks may still struggle with specific domain applications or practical use cases. - -## General Knowledge Benchmarks - -[MMLU](https://huggingface.co/datasets/cais/mmlu) (Massive Multitask Language Understanding) tests knowledge across 57 subjects, from science to humanities. While comprehensive, it may not reflect the depth of expertise needed for specific domains. TruthfulQA evaluates a model's tendency to reproduce common misconceptions, though it can't capture all forms of misinformation. - -## Reasoning Benchmarks - -[BBH](https://huggingface.co/datasets/lukaemon/bbh) (Big Bench Hard) and [GSM8K](https://huggingface.co/datasets/openai/gsm8k) focus on complex reasoning tasks. BBH tests logical thinking and planning, while GSM8K specifically targets mathematical problem-solving. These benchmarks help assess analytical capabilities but may not capture the nuanced reasoning required in real-world scenarios. - -## Language Understanding - -[HELM](https://github.com/stanford-crfm/helm) provides a holistic evaluation framework. Benchmarks like HELM offer insights into language processing capabilities on aspects like commonsense, world knowledge, and reasoning. But may not fully represent the complexity of natural conversation or domain-specific terminology. - -## Domain-Specific Benchmarks - -Let's look at a few benchmarks that focus on specific domains like math, coding, and chat. - -The [MATH benchmark](https://huggingface.co/papers/2103.03874) is another important evaluation tool for mathematical reasoning. It consists of 12,500 problems from mathematics competitions, covering algebra, geometry, number theory, counting, probability, and more. What makes MATH particularly challenging is that it requires multi-step reasoning, formal mathematical notation understanding, and the ability to generate step-by-step solutions. Unlike simpler arithmetic tasks, MATH problems often demand sophisticated problem-solving strategies and mathematical concept applications. - -The [HumanEval Benchmark](https://github.com/openai/human-eval) is a coding-focused evaluation dataset consisting of 164 programming problems. The benchmark tests a model's ability to generate functionally correct Python code that solves the given programming tasks. What makes HumanEval particularly valuable is that it evaluates both code generation capabilities and functional correctness through actual test case execution, rather than just superficial similarity to reference solutions. The problems range from basic string manipulation to more complex algorithms and data structures. - -[Alpaca Eval](https://tatsu-lab.github.io/alpaca_eval/) is an automated evaluation framework designed to assess the quality of instruction-following language models. It uses GPT-4 as a judge to evaluate model outputs across various dimensions including helpfulness, honesty, and harmlessness. The framework includes a dataset of 805 carefully curated prompts and can evaluate responses against multiple reference models like Claude, GPT-4, and others. What makes Alpaca Eval particularly useful is its ability to provide consistent, scalable evaluations without requiring human annotators, while still capturing nuanced aspects of model performance that traditional metrics might miss. - -## Alternative Evaluation Approaches - -Many organizations have developed alternative evaluation methods to address the limitations of standard benchmarks: - -### LLM-as-Judge - -Using one language model to evaluate another's outputs has become increasingly popular. This approach can provide more nuanced feedback than traditional metrics, though it comes with its own biases and limitations. - -### Evaluation Arenas - -Evaluation arenas like [Chatbot Arena](https://lmarena.ai/) offer a unique approach to LLM assessment through crowdsourced feedback. In these platforms, users engage in anonymous "battles" between two LLMs, asking questions and voting on which model provides better responses. This approach captures real-world usage patterns and preferences through diverse, challenging questions, with studies showing strong agreement between crowd-sourced votes and expert evaluations. While powerful, these platforms have limitations including potential user base bias, skewed prompt distributions, and a primary focus on helpfulness rather than safety considerations. - -### Custom Benchmark Suites - -Organizations often develop internal benchmark suites tailored to their specific needs and use cases. These might include domain-specific knowledge tests or evaluation scenarios that mirror actual deployment conditions. - -## Custom Evaluation - -While standard benchmarks provide a useful baseline, they shouldn't be your only evaluation method. Here's how to develop a more comprehensive approach: - -1. Start with relevant standard benchmarks to establish a baseline and enable comparison with other models. - -2. Identify the specific requirements and challenges of your use case. What tasks will your model actually perform? What kinds of errors would be most problematic? - -3. Develop custom evaluation datasets that reflect your actual use case. This might include: - - Real user queries from your domain - - Common edge cases you've encountered - - Examples of particularly challenging scenarios - -4. Consider implementing a multi-layered evaluation strategy: - - Automated metrics for quick feedback - - Human evaluation for nuanced understanding - - Domain expert review for specialized applications - - A/B testing in controlled environments - -## Implementing Custom Evaluations - -In this section, we will implement evaluation for our finetuned model. We can use [`lighteval`](https://github.com/huggingface/lighteval) to evaluate our finetuned model on standard benchmarks, which contains a wide range of tasks built into the library. We just need to define the tasks we want to evaluate and the parameters for the evaluation. - -LightEval tasks are defined using a specific format: - -``` -{suite}|{task}|{num_few_shot}|{auto_reduce} -``` - -| Parameter | Description | -|-----------|-------------| -| `suite` | The benchmark suite (e.g., 'mmlu', 'truthfulqa') | -| `task` | Specific task within the suite (e.g., 'abstract_algebra') | -| `num_few_shot` | Number of examples to include in prompt (0 for zero-shot) | -| `auto_reduce` | Whether to automatically reduce few-shot examples if prompt is too long (0 or 1) | - -Example: `"mmlu|abstract_algebra|0|0"` evaluates on MMLU's abstract algebra task with zero-shot inference. - -## Example Evaluation Pipeline - -Let's set up an evaluation pipeline for our finetuned model. We will evaluate the model on set of sub tasks that relate to the domain of medicine. - -Here's a complete example of evaluating on automatic benchmarks relevant to one specific domain using Lighteval with the VLLM backend: - -```bash -lighteval accelerate \ - "pretrained=your-model-name" \ - "mmlu|anatomy|0|0" \ - "mmlu|high_school_biology|0|0" \ - "mmlu|high_school_chemistry|0|0" \ - "mmlu|professional_medicine|0|0" \ - --max_samples 40 \ - --batch_size 1 \ - --output_path "./results" \ - --save_generations true -``` - -Results are displayed in a tabular format showing: - -``` -| Task |Version|Metric|Value | |Stderr| -|----------------------------------------|------:|------|-----:|---|-----:| -|all | |acc |0.3333|± |0.1169| -|leaderboard:mmlu:_average:5 | |acc |0.3400|± |0.1121| -|leaderboard:mmlu:anatomy:5 | 0|acc |0.4500|± |0.1141| -|leaderboard:mmlu:high_school_biology:5 | 0|acc |0.1500|± |0.0819| -``` - -Lighteval also include a python API for more detailed evaluation tasks, which is useful for manipulating the results in a more flexible way. Check out the [Lighteval documentation](https://huggingface.co/docs/lighteval/using-the-python-api) for more information. - -> [!TIP] -> ✏️ **Try it out!** Evaluate your finetuned model on a specific task in lighteval. - -# End-of-chapter quiz[[end-of-chapter-quiz]] - - - -### 1. What are the main advantages of using automatic benchmarks for model evaluation? - - - -### 2. Which benchmark specifically tests knowledge across 57 different subjects? - - - -### 3. What is LLM-as-Judge? - - - -### 4. What should be included in a comprehensive evaluation strategy? - - - -### 5. What is a limitation of automatic benchmarks? - - - -### 6. What is the purpose of creating custom evaluation datasets? - - +# Evaluation + +With a finetuned model through either SFT or LoRA SFT, we should evaluate it on standard benchmarks. As machine learning engineers you should maintain a suite of relevant evaluations for your targeted domain of interest. In this page, we will look at some of the most common benchmarks and how to use them to evaluate your model. We'll also look at how to create custom benchmarks for your specific use case. + +## Automatic Benchmarks + +Automatic benchmarks serve as standardized tools for evaluating language models across different tasks and capabilities. While they provide a useful starting point for understanding model performance, it's important to recognize that they represent only one piece of a comprehensive evaluation strategy. + +## Understanding Automatic Benchmarks + +Automatic benchmarks typically consist of curated datasets with predefined tasks and evaluation metrics. These benchmarks aim to assess various aspects of model capability, from basic language understanding to complex reasoning. The key advantage of using automatic benchmarks is their standardization - they allow for consistent comparison across different models and provide reproducible results. + +However, it's crucial to understand that benchmark performance doesn't always translate directly to real-world effectiveness. A model that excels at academic benchmarks may still struggle with specific domain applications or practical use cases. + +## General Knowledge Benchmarks + +[MMLU](https://huggingface.co/datasets/cais/mmlu) (Massive Multitask Language Understanding) tests knowledge across 57 subjects, from science to humanities. While comprehensive, it may not reflect the depth of expertise needed for specific domains. TruthfulQA evaluates a model's tendency to reproduce common misconceptions, though it can't capture all forms of misinformation. + +## Reasoning Benchmarks + +[BBH](https://huggingface.co/datasets/lukaemon/bbh) (Big Bench Hard) and [GSM8K](https://huggingface.co/datasets/openai/gsm8k) focus on complex reasoning tasks. BBH tests logical thinking and planning, while GSM8K specifically targets mathematical problem-solving. These benchmarks help assess analytical capabilities but may not capture the nuanced reasoning required in real-world scenarios. + +## Language Understanding + +[HELM](https://github.com/stanford-crfm/helm) provides a holistic evaluation framework. Benchmarks like HELM offer insights into language processing capabilities on aspects like commonsense, world knowledge, and reasoning. But may not fully represent the complexity of natural conversation or domain-specific terminology. + +## Domain-Specific Benchmarks + +Let's look at a few benchmarks that focus on specific domains like math, coding, and chat. + +The [MATH benchmark](https://huggingface.co/papers/2103.03874) is another important evaluation tool for mathematical reasoning. It consists of 12,500 problems from mathematics competitions, covering algebra, geometry, number theory, counting, probability, and more. What makes MATH particularly challenging is that it requires multi-step reasoning, formal mathematical notation understanding, and the ability to generate step-by-step solutions. Unlike simpler arithmetic tasks, MATH problems often demand sophisticated problem-solving strategies and mathematical concept applications. + +The [HumanEval Benchmark](https://github.com/openai/human-eval) is a coding-focused evaluation dataset consisting of 164 programming problems. The benchmark tests a model's ability to generate functionally correct Python code that solves the given programming tasks. What makes HumanEval particularly valuable is that it evaluates both code generation capabilities and functional correctness through actual test case execution, rather than just superficial similarity to reference solutions. The problems range from basic string manipulation to more complex algorithms and data structures. + +[Alpaca Eval](https://tatsu-lab.github.io/alpaca_eval/) is an automated evaluation framework designed to assess the quality of instruction-following language models. It uses GPT-4 as a judge to evaluate model outputs across various dimensions including helpfulness, honesty, and harmlessness. The framework includes a dataset of 805 carefully curated prompts and can evaluate responses against multiple reference models like Claude, GPT-4, and others. What makes Alpaca Eval particularly useful is its ability to provide consistent, scalable evaluations without requiring human annotators, while still capturing nuanced aspects of model performance that traditional metrics might miss. + +## Alternative Evaluation Approaches + +Many organizations have developed alternative evaluation methods to address the limitations of standard benchmarks: + +### LLM-as-Judge + +Using one language model to evaluate another's outputs has become increasingly popular. This approach can provide more nuanced feedback than traditional metrics, though it comes with its own biases and limitations. + +### Evaluation Arenas + +Evaluation arenas like [Chatbot Arena](https://lmarena.ai/) offer a unique approach to LLM assessment through crowdsourced feedback. In these platforms, users engage in anonymous "battles" between two LLMs, asking questions and voting on which model provides better responses. This approach captures real-world usage patterns and preferences through diverse, challenging questions, with studies showing strong agreement between crowd-sourced votes and expert evaluations. While powerful, these platforms have limitations including potential user base bias, skewed prompt distributions, and a primary focus on helpfulness rather than safety considerations. + +### Custom Benchmark Suites + +Organizations often develop internal benchmark suites tailored to their specific needs and use cases. These might include domain-specific knowledge tests or evaluation scenarios that mirror actual deployment conditions. + +## Custom Evaluation + +While standard benchmarks provide a useful baseline, they shouldn't be your only evaluation method. Here's how to develop a more comprehensive approach: + +1. Start with relevant standard benchmarks to establish a baseline and enable comparison with other models. + +2. Identify the specific requirements and challenges of your use case. What tasks will your model actually perform? What kinds of errors would be most problematic? + +3. Develop custom evaluation datasets that reflect your actual use case. This might include: + - Real user queries from your domain + - Common edge cases you've encountered + - Examples of particularly challenging scenarios + +4. Consider implementing a multi-layered evaluation strategy: + - Automated metrics for quick feedback + - Human evaluation for nuanced understanding + - Domain expert review for specialized applications + - A/B testing in controlled environments + +## Implementing Custom Evaluations + +In this section, we will implement evaluation for our finetuned model. We can use [`lighteval`](https://github.com/huggingface/lighteval) to evaluate our finetuned model on standard benchmarks, which contains a wide range of tasks built into the library. We just need to define the tasks we want to evaluate and the parameters for the evaluation. + +LightEval tasks are defined using a specific format: + +``` +{suite}|{task}|{num_few_shot}|{auto_reduce} +``` + +| Parameter | Description | +|-----------|-------------| +| `suite` | The benchmark suite (e.g., 'mmlu', 'truthfulqa') | +| `task` | Specific task within the suite (e.g., 'abstract_algebra') | +| `num_few_shot` | Number of examples to include in prompt (0 for zero-shot) | +| `auto_reduce` | Whether to automatically reduce few-shot examples if prompt is too long (0 or 1) | + +Example: `"mmlu|abstract_algebra|0|0"` evaluates on MMLU's abstract algebra task with zero-shot inference. + +## Example Evaluation Pipeline + +Let's set up an evaluation pipeline for our finetuned model. We will evaluate the model on set of sub tasks that relate to the domain of medicine. + +Here's a complete example of evaluating on automatic benchmarks relevant to one specific domain using Lighteval with the VLLM backend: + +```bash +lighteval accelerate \ + "pretrained=your-model-name" \ + "mmlu|anatomy|0|0" \ + "mmlu|high_school_biology|0|0" \ + "mmlu|high_school_chemistry|0|0" \ + "mmlu|professional_medicine|0|0" \ + --max_samples 40 \ + --batch_size 1 \ + --output_path "./results" \ + --save_generations true +``` + +Results are displayed in a tabular format showing: + +``` +| Task |Version|Metric|Value | |Stderr| +|----------------------------------------|------:|------|-----:|---|-----:| +|all | |acc |0.3333|± |0.1169| +|leaderboard:mmlu:_average:5 | |acc |0.3400|± |0.1121| +|leaderboard:mmlu:anatomy:5 | 0|acc |0.4500|± |0.1141| +|leaderboard:mmlu:high_school_biology:5 | 0|acc |0.1500|± |0.0819| +``` + +Lighteval also include a python API for more detailed evaluation tasks, which is useful for manipulating the results in a more flexible way. Check out the [Lighteval documentation](https://huggingface.co/docs/lighteval/using-the-python-api) for more information. + +> [!TIP] +> ✏️ **Try it out!** Evaluate your finetuned model on a specific task in lighteval. + +# End-of-chapter quiz[[end-of-chapter-quiz]] + + + +### 1. What are the main advantages of using automatic benchmarks for model evaluation? + + + +### 2. Which benchmark specifically tests knowledge across 57 different subjects? + + + +### 3. What is LLM-as-Judge? + + + +### 4. What should be included in a comprehensive evaluation strategy? + + + +### 5. What is a limitation of automatic benchmarks? + + + +### 6. What is the purpose of creating custom evaluation datasets? + + diff --git a/chapters/en/chapter11/6.mdx b/chapters/en/chapter11/6.mdx index 093de47d6..7ddf87b6e 100644 --- a/chapters/en/chapter11/6.mdx +++ b/chapters/en/chapter11/6.mdx @@ -1,13 +1,13 @@ -# Conclusion - -In this chapter, we explored the essential components of fine-tuning language models: - -1. **Chat Templates** provide structure to model interactions, ensuring consistent and appropriate responses through standardized formatting. - -2. **Supervised Fine-Tuning (SFT)** allows adaptation of pre-trained models to specific tasks while maintaining their foundational knowledge. - -3. **LoRA** offers an efficient approach to fine-tuning by reducing trainable parameters while preserving model performance. - -4. **Evaluation** helps measure and validate the effectiveness of fine-tuning through various metrics and benchmarks. - -These techniques, when combined, enable the creation of specialized language models that can excel at specific tasks while remaining computationally efficient. Whether you're building a customer service bot or a domain-specific assistant, understanding these concepts is crucial for successful model adaptation. +# Conclusion + +In this chapter, we explored the essential components of fine-tuning language models: + +1. **Chat Templates** provide structure to model interactions, ensuring consistent and appropriate responses through standardized formatting. + +2. **Supervised Fine-Tuning (SFT)** allows adaptation of pre-trained models to specific tasks while maintaining their foundational knowledge. + +3. **LoRA** offers an efficient approach to fine-tuning by reducing trainable parameters while preserving model performance. + +4. **Evaluation** helps measure and validate the effectiveness of fine-tuning through various metrics and benchmarks. + +These techniques, when combined, enable the creation of specialized language models that can excel at specific tasks while remaining computationally efficient. Whether you're building a customer service bot or a domain-specific assistant, understanding these concepts is crucial for successful model adaptation. diff --git a/chapters/en/chapter11/7.mdx b/chapters/en/chapter11/7.mdx index 0e644ed8b..5000d9a8c 100644 --- a/chapters/en/chapter11/7.mdx +++ b/chapters/en/chapter11/7.mdx @@ -1,33 +1,33 @@ -# Exam Time! - -It's time to put your knowledge to the test! We've prepared a short quiz for you to test your understanding of the concepts covered in this chapter. - -To take the quiz, you will need to follow these steps: - -1. Sign in to your Hugging Face account. -2. Answer the questions in the quiz. -3. Submit your answers. - - -## Multiple Choice Quiz - -In this quiz, you will be asked to select the correct answer from a list of options. We'll test you on the fundamentals of supervised finetuning. - - - - -## Code Quiz - -In this quiz, you will be asked to write code to complete a task. We'll test you on the code you've studied in the course from libraries like `datasets`, `transformers`, `peft`, and `TRL`. - - +# Exam Time! + +It's time to put your knowledge to the test! We've prepared a short quiz for you to test your understanding of the concepts covered in this chapter. + +To take the quiz, you will need to follow these steps: + +1. Sign in to your Hugging Face account. +2. Answer the questions in the quiz. +3. Submit your answers. + + +## Multiple Choice Quiz + +In this quiz, you will be asked to select the correct answer from a list of options. We'll test you on the fundamentals of supervised finetuning. + + + + +## Code Quiz + +In this quiz, you will be asked to write code to complete a task. We'll test you on the code you've studied in the course from libraries like `datasets`, `transformers`, `peft`, and `TRL`. + + diff --git a/chapters/en/chapter12/1.mdx b/chapters/en/chapter12/1.mdx index 773f2c808..7a93676ae 100644 --- a/chapters/en/chapter12/1.mdx +++ b/chapters/en/chapter12/1.mdx @@ -1,90 +1,90 @@ -# Open R1 for Students - -Welcome to an exciting journey into the world of open-source AI with reinforcement learning! This chapter is designed to help students understand reinforcement learning and its role in LLMs. - -We will also explore [Open R1](https://github.com/huggingface/open-r1), a groundbreaking community project that's making advanced AI accessible to everyone. Specifically, this course is to help students and learners to use and contribute to [Open R1](https://github.com/huggingface/open-r1). - -## What You'll Learn - -In this chapter, we'll break down complex concepts into easy-to-understand pieces and show you how you can be part of this exciting project to make LLMs reason on complex problems. - -LLMs have shown excellent performance on many generative tasks. However, up until recently they have struggled on complex problems that require reasoning. For example, they struggle to deal with puzzles or math problems that require multiple steps of reasoning. - -Open R1 is a project that aims to make LLMs reason on complex problems. It does this by using reinforcement learning to encourage LLMs to 'think' and reason. - -In simple terms, the model is trained to generate thoughts as well as outputs, and to structure these thoughts and outputs so that they can be handled separately by the user. - -Let's take a look at an example. As we gave ourself the task of solving the following problem, we might think like this: - -```sh -Problem: "I have 3 apples and 2 oranges. How many pieces of fruit do I have in total?" - -Thought: "I need to add the number of apples and oranges to get the total number of pieces of fruit." - -Answer: "5" -``` - -We can then structure this thought and answer so that they can be handled separately by the user. For reasoning tasks, LLMs can be trained to generate thoughts and answers in the following format: - -```sh -I need to add the number of apples and oranges to get the total number of pieces of fruit. -5 -``` - -As a user, we can then extract the thought and answer from the model's output and use them to solve the problem. - -## Why This Matters for Students - -As a student, understanding Open R1 and the role of reinforcement learning in LLMs is valuable because: -- It shows you how cutting-edge AI is developed -- It gives you hands-on opportunities to learn and contribute -- It helps you understand where AI technology is heading -- It opens doors to future career opportunities in AI - -## Chapter Overview - -This chapter is divided into four sections, each focusing on a different aspect of Open R1: - -### 1️⃣ Introduction to Reinforcement Learning and its Role in LLMs -We'll explore the basics of Reinforcement Learning (RL) and its role in training LLMs. -- What is RL? -- How is RL used in LLMs? -- What is DeepSeek R1? -- What are the key innovations of DeepSeek R1? - -### 2️⃣ Understanding the DeepSeek R1 Paper -We'll break down the research paper that inspired [Open R1](https://huggingface.co/open-r1): -- Key innovations and breakthroughs -- The training process and architecture -- Results and their significance - -### 3️⃣ Implementing GRPO in TRL -We'll get practical with code examples: -- How to use the Transformer Reinforcement Learning (TRL) library -- Setting up GRPO training - -### 4️⃣ Practical use case to align a model -We'll look at a practical use case to align a model using Open R1. -- How to train a model using GRPO in TRL -- Share your model on the [Hugging Face Hub](https://huggingface.co/models) - -## Prerequisites - -To get the most out of this chapter, it's helpful to have: -- Solid understanding of Python programming -- Familiarity with machine learning concepts -- Interest in AI and language models - -Don't worry if you're missing some of these – we'll explain key concepts as we go along! 🚀 - -> [!TIP] -> If you don't have all the prerequisites, check out this [course](/course/chapter1/1) from units 1 to 11 - -## How to Use This Chapter - -1. **Read Sequentially**: The sections build on each other, so it's best to read them in order -2. **Share Notes**: Write down key concepts and questions and discuss them within the community in [Discord](https://discord.gg/UrrTSsSyjb) -3. **Try the Code**: When we get to practical examples, try them yourself -4. **Join the Community**: Use the resources we provide to connect with other learners - -Let's begin our exploration of Open R1 and discover how you can be part of making AI more accessible to everyone! 🚀 +# Open R1 for Students + +Welcome to an exciting journey into the world of open-source AI with reinforcement learning! This chapter is designed to help students understand reinforcement learning and its role in LLMs. + +We will also explore [Open R1](https://github.com/huggingface/open-r1), a groundbreaking community project that's making advanced AI accessible to everyone. Specifically, this course is to help students and learners to use and contribute to [Open R1](https://github.com/huggingface/open-r1). + +## What You'll Learn + +In this chapter, we'll break down complex concepts into easy-to-understand pieces and show you how you can be part of this exciting project to make LLMs reason on complex problems. + +LLMs have shown excellent performance on many generative tasks. However, up until recently they have struggled on complex problems that require reasoning. For example, they struggle to deal with puzzles or math problems that require multiple steps of reasoning. + +Open R1 is a project that aims to make LLMs reason on complex problems. It does this by using reinforcement learning to encourage LLMs to 'think' and reason. + +In simple terms, the model is trained to generate thoughts as well as outputs, and to structure these thoughts and outputs so that they can be handled separately by the user. + +Let's take a look at an example. As we gave ourself the task of solving the following problem, we might think like this: + +```sh +Problem: "I have 3 apples and 2 oranges. How many pieces of fruit do I have in total?" + +Thought: "I need to add the number of apples and oranges to get the total number of pieces of fruit." + +Answer: "5" +``` + +We can then structure this thought and answer so that they can be handled separately by the user. For reasoning tasks, LLMs can be trained to generate thoughts and answers in the following format: + +```sh +I need to add the number of apples and oranges to get the total number of pieces of fruit. +5 +``` + +As a user, we can then extract the thought and answer from the model's output and use them to solve the problem. + +## Why This Matters for Students + +As a student, understanding Open R1 and the role of reinforcement learning in LLMs is valuable because: +- It shows you how cutting-edge AI is developed +- It gives you hands-on opportunities to learn and contribute +- It helps you understand where AI technology is heading +- It opens doors to future career opportunities in AI + +## Chapter Overview + +This chapter is divided into four sections, each focusing on a different aspect of Open R1: + +### 1️⃣ Introduction to Reinforcement Learning and its Role in LLMs +We'll explore the basics of Reinforcement Learning (RL) and its role in training LLMs. +- What is RL? +- How is RL used in LLMs? +- What is DeepSeek R1? +- What are the key innovations of DeepSeek R1? + +### 2️⃣ Understanding the DeepSeek R1 Paper +We'll break down the research paper that inspired [Open R1](https://huggingface.co/open-r1): +- Key innovations and breakthroughs +- The training process and architecture +- Results and their significance + +### 3️⃣ Implementing GRPO in TRL +We'll get practical with code examples: +- How to use the Transformer Reinforcement Learning (TRL) library +- Setting up GRPO training + +### 4️⃣ Practical use case to align a model +We'll look at a practical use case to align a model using Open R1. +- How to train a model using GRPO in TRL +- Share your model on the [Hugging Face Hub](https://huggingface.co/models) + +## Prerequisites + +To get the most out of this chapter, it's helpful to have: +- Solid understanding of Python programming +- Familiarity with machine learning concepts +- Interest in AI and language models + +Don't worry if you're missing some of these – we'll explain key concepts as we go along! 🚀 + +> [!TIP] +> If you don't have all the prerequisites, check out this [course](/course/chapter1/1) from units 1 to 11 + +## How to Use This Chapter + +1. **Read Sequentially**: The sections build on each other, so it's best to read them in order +2. **Share Notes**: Write down key concepts and questions and discuss them within the community in [Discord](https://discord.gg/UrrTSsSyjb) +3. **Try the Code**: When we get to practical examples, try them yourself +4. **Join the Community**: Use the resources we provide to connect with other learners + +Let's begin our exploration of Open R1 and discover how you can be part of making AI more accessible to everyone! 🚀 diff --git a/chapters/en/chapter12/2.mdx b/chapters/en/chapter12/2.mdx index 0d4743967..15f82cf27 100644 --- a/chapters/en/chapter12/2.mdx +++ b/chapters/en/chapter12/2.mdx @@ -1,240 +1,240 @@ -# Introduction to Reinforcement Learning and its Role in LLMs - -Welcome to the first page! - -We're going to start our journey into the exciting world of Reinforcement Learning (RL) and discover how it's revolutionizing the way we train Language Models like the ones you might use every day. - -> [!TIP] -> In this chapter, we are focusing on reinforcement learning for language models. However, reinforcement learning is a broad field with many applications beyond language models. If you're interested in learning more about reinforcement learning, you should check out the [Deep Reinforcement Learning course](https://huggingface.co/courses/deep-rl-course/en/unit1/introduction). - -This page will give you a friendly and clear introduction to RL, even if you've never encountered it before. We'll break down the core ideas and see why RL is becoming so important in the field of Large Language Models (LLMs). - -## What is Reinforcement Learning (RL)? - -Imagine you're training a dog. You want to teach it to sit. You might say "Sit!" and then, if the dog sits, you give it a treat and praise. If it doesn't sit, you might gently guide it or just try again. Over time, the dog learns to associate sitting with the positive reward (treat and praise) and is more likely to sit when you say "Sit!" again. In reinforcement learning, we refer to this feedback as a **reward**. - -That, in a nutshell, is the basic idea behind Reinforcement Learning! Instead of a dog, we have a **language model** (in reinforcement learning, we call it an **agent**), and instead of you, we have the **environment** that gives feedback. - -![RL terms Process](https://huggingface.co/reasoning-course/images/resolve/main/grpo/3.jpg) - -Let's break down the key pieces of RL: - -### Agent - -This is our learner. In the dog example, the dog is the agent. In the context of LLMs, the LLM itself becomes the agent we want to train. The agent is the one making decisions and learning from the environment and its rewards. - -### Environment - -This is the world the agent lives in and interacts with. For the dog, the environment is your house and you. For an LLM, the environment is a bit more abstract – it could be the users it interacts with, or a simulated scenario we set up for it. The environment provides feedback to the agent. - -### Action - -These are the choices the agent can make in the environment. The dog's actions are things like "sit", "stand", "bark", etc. For an LLM, actions could be generating words in a sentence, choosing which answer to give to a question, or deciding how to respond in a conversation. - -### Reward - -This is the feedback the environment gives to the agent after it takes an action. Rewards are usually numbers. - -**Positive rewards** are like treats and praise – they tell the agent "good job, you did something right!". - -**Negative rewards** (or penalties) are like a gentle "no" – they tell the agent "that wasn't quite right, try something else". For the dog, the treat is the reward. - -For an LLM, rewards are designed to reflect how well the LLM is doing at a specific task – maybe it's how helpful, truthful, or harmless its response is. - -### Policy - -This is the agent's strategy for choosing actions. It's like the dog's understanding of what it should do when you say "Sit!". In RL, the policy is what we're really trying to learn and improve. It's a set of rules or a function that tells the agent what action to take in different situations. Initially, the policy might be random, but as the agent learns, the policy becomes better at choosing actions that lead to higher rewards. - -## The RL Process: Trial and Error - -![RL Process](https://huggingface.co/reasoning-course/images/resolve/main/grpo/1.jpg) - -Reinforcement Learning happens through a process of trial and error: - -| Step | Process | Description | -|------|---------|-------------| -| 1. Observation | The agent observes the environment | The agent takes in information about its current state and surroundings | -| 2. Action | The agent takes an action based on its current policy | Using its learned strategy (policy), the agent decides what to do next | -| 3. Feedback | The environment gives the agent a reward | The agent receives feedback on how good or bad its action was | -| 4. Learning | The agent updates its policy based on the reward | The agent adjusts its strategy - reinforcing actions that led to high rewards and avoiding those that led low rewards | -| 5. Iteration | Repeat the process | This cycle continues, allowing the agent to continuously improve its decision-making | - -Think about learning to ride a bike. You might wobble and fall at first (negative reward!). But when you manage to balance and pedal smoothly, you feel good (positive reward!). You adjust your actions based on this feedback – leaning slightly, pedaling faster, etc. – until you learn to ride well. RL is similar – it's about learning through interaction and feedback. - -## Role of RL in Large Language Models (LLMs) - -Now, why is RL so important for Large Language Models? - -Well, training really good LLMs is tricky. We can train them on massive amounts of text from the internet, and they become very good at predicting the next word in a sentence. This is how they learn to generate fluent and grammatically correct text, as we learned in [chapter 2](/course/chapter2/1). - -However, just being fluent isn't enough. We want our LLMs to be more than just good at stringing words together. We want them to be: - -* **Helpful:** Provide useful and relevant information. -* **Harmless:** Avoid generating toxic, biased, or harmful content. -* **Aligned with Human Preferences:** Respond in ways that humans find natural, helpful, and engaging. - -Pre-training LLM methods, which mostly rely on predicting the next word from text data, sometimes fall short on these aspects. - -Whilst supervised training is excellent at producing structured outputs, it can be less effective at producing helpful, harmless, and aligned responses. We explore supervised training in [chapter 11](/course/chapter11/1). - -Fine-tuned models might generate fluent and structured text that is still factually incorrect, biased, or doesn't really answer the user's question in a helpful way. - -**Enter Reinforcement Learning\!** RL gives us a way to fine-tune these pre-trained LLMs to better achieve these desired qualities. It's like giving our LLM dog extra training to become a well-behaved and helpful companion, not just a dog that knows how to bark fluently\! - -## Reinforcement Learning from Human Feedback (RLHF) - -A very popular technique for aligning language models is **Reinforcement Learning from Human Feedback (RLHF)**. In RLHF, we use human feedback as a proxy for the "reward" signal in RL. Here's how it works: - -1. **Get Human Preferences:** We might ask humans to compare different responses generated by the LLM for the same input prompt and tell us which response they prefer. For example, we might show a human two different answers to the question "What is the capital of France?" and ask them "Which answer is better?". - -2. **Train a Reward Model:** We use this human preference data to train a separate model called a **reward model**. This reward model learns to predict what kind of responses humans will prefer. It learns to score responses based on helpfulness, harmlessness, and alignment with human preferences. - -3. **Fine-tune the LLM with RL:** Now we use the reward model as the environment for our LLM agent. The LLM generates responses (actions), and the reward model scores these responses (provides rewards). In essence, we're training the LLM to produce text that our reward model (which learned from human preferences) thinks is good. - -![RL Basic Concept](https://huggingface.co/reasoning-course/images/resolve/main/grpo/2.jpg) - -From a general perspective, let's look at the benefits of using RL in LLMs: - -| Benefit | Description | -|---------|-------------| -| Improved Control | RL allows us to have more control over the kind of text LLMs generate. We can guide them to produce text that is more aligned with specific goals, like being helpful, creative, or concise. | -| Enhanced Alignment with Human Values | RLHF, in particular, helps us align LLMs with complex and often subjective human preferences. It's hard to write down rules for "what makes a good answer," but humans can easily judge and compare responses. RLHF lets the model learn from these human judgments. | -| Mitigating Undesirable Behaviors | RL can be used to reduce negative behaviors in LLMs, such as generating toxic language, spreading misinformation, or exhibiting biases. By designing rewards that penalize these behaviors, we can nudge the model to avoid them. | - -Reinforcement Learning from Human Feedback has been used to train many of the most popular LLMs today, such as OpenAI's GPT-4, Google's Gemini, and DeepSeek's R1. There are a wide range of techniques for RLHF, with varying degrees of complexity and sophistication. In this chapter, we will focus on Group Relative Policy Optimization (GRPO), which is a technique for RLHF that has been shown to be effective at training LLMs that are helpful, harmless, and aligned with human preferences. - -## Why should we care about GRPO (Group Relative Policy Optimization)? - -There are many techniques for RLHF but this course is focused on GRPO because it represents a significant advancement in reinforcement learning for language models. - -Let's briefly consider two of other popular techniques for RLHF: - -- Proximal Policy Optimization (PPO) -- Direct Preference Optimization (DPO) - -Proximal Policy Optimization (PPO) was one of the first highly effective techniques for RLHF. It uses a policy gradient method to update the policy based on the reward from a separate reward model. - -Direct Preference Optimization (DPO) was later developed as a simpler technique that eliminates the need for a separate reward model using preference data directly. Essentially, framing the problem as a classification task between the chosen and rejected responses. - -> [!TIP] -> DPO and PPO are complex reinforcement learning algorithms in their own right, which we will not cover in this course. If you're interested in learning more about them, you can check out the following resources: -> -> - [Proximal Policy Optimization](https://huggingface.co/docs/trl/main/en/ppo_trainer) -> - [Direct Preference Optimization](https://huggingface.co/docs/trl/main/en/dpo_trainer) - -Unlike DPO and PPO, GRPO groups similar samples together and compares them as a group. The group-based approach provides more stable gradients and better convergence properties compared to other methods. - -GRPO does not use preference data like DPO, but instead compares groups of similar samples using a reward signal from a model or function. - -GRPO is flexible in how it obtains reward signals - it can work with a reward model (like PPO does) but doesn't strictly require one. This is because GRPO can incorporate reward signals from any function or model that can evaluate the quality of responses. - -For example, we could use a length function to reward shorter responses, a mathematical solver to verify solution correctness, or a factual correctness function to reward responses that are more factually accurate. This flexibility makes GRPO particularly versatile for different types of alignment tasks. - ---- - -Congratulations on completing Module 1\! You've now got a solid introduction to Reinforcement Learning and its crucial role in shaping the future of Large Language Models. You understand the basic concepts of RL, why it's used for LLMs, and you've been introduced to GRPO, a key algorithm in this field. - -In the next module, we'll get our hands dirty and dive into the DeepSeek R1 paper to see these concepts in action\! - -## Quiz - -### 1. What are the key components of Reinforcement Learning? - -