From 9b8c6459fd8b6cc0cddc843a9ae2f08bb2c6eda7 Mon Sep 17 00:00:00 2001 From: sergiopaniego Date: Tue, 27 Aug 2024 15:57:46 +0200 Subject: [PATCH 01/43] Updated .bin to .safetensors --- chapters/en/chapter2/3.mdx | 4 ++-- chapters/fa/chapter2/3.mdx | 4 ++-- chapters/fr/chapter2/3.mdx | 4 ++-- chapters/it/chapter2/3.mdx | 4 ++-- chapters/ja/chapter2/3.mdx | 4 ++-- chapters/ko/chapter2/3.mdx | 4 ++-- chapters/pt/chapter2/3.mdx | 4 ++-- chapters/ru/chapter2/3.mdx | 4 ++-- chapters/th/chapter2/3.mdx | 4 ++-- chapters/vi/chapter2/3.mdx | 4 ++-- chapters/zh-CN/chapter2/3.mdx | 4 ++-- chapters/zh-TW/chapter2/3.mdx | 6 +++--- 12 files changed, 25 insertions(+), 25 deletions(-) diff --git a/chapters/en/chapter2/3.mdx b/chapters/en/chapter2/3.mdx index acc653704..700dcca98 100644 --- a/chapters/en/chapter2/3.mdx +++ b/chapters/en/chapter2/3.mdx @@ -158,7 +158,7 @@ This saves two files to your disk: ``` ls directory_on_my_computer -config.json pytorch_model.bin +config.json model.safetensors ``` {:else} ``` @@ -171,7 +171,7 @@ config.json tf_model.h5 If you take a look at the *config.json* file, you'll recognize the attributes necessary to build the model architecture. This file also contains some metadata, such as where the checkpoint originated and what 🤗 Transformers version you were using when you last saved the checkpoint. {#if fw === 'pt'} -The *pytorch_model.bin* file is known as the *state dictionary*; it contains all your model's weights. The two files go hand in hand; the configuration is necessary to know your model's architecture, while the model weights are your model's parameters. +The *model.safetensors* file is known as the *state dictionary*; it contains all your model's weights. The two files go hand in hand; the configuration is necessary to know your model's architecture, while the model weights are your model's parameters. {:else} The *tf_model.h5* file is known as the *state dictionary*; it contains all your model's weights. The two files go hand in hand; the configuration is necessary to know your model's architecture, while the model weights are your model's parameters. diff --git a/chapters/fa/chapter2/3.mdx b/chapters/fa/chapter2/3.mdx index cff6876fd..45fb2a5c3 100644 --- a/chapters/fa/chapter2/3.mdx +++ b/chapters/fa/chapter2/3.mdx @@ -188,7 +188,7 @@ model.save_pretrained("directory_on_my_computer") ``` ls directory_on_my_computer -config.json pytorch_model.bin +config.json model.safetensors ``` {:else} ``` @@ -204,7 +204,7 @@ config.json tf_model.h5 {#if fw === 'pt'} -فایل *pytorch_model.bin* در واقع *دیکشنری وضعیت‌ها* است و حاوی تمام وزن‌های مدل شماست. این دو فایل به همراه هم کاربرد دارند؛ فایل تنظیمات برای دانستن معماری به کار رفته در مدل ضروری است و پارامترهای مدل هم که همان وزن‌های داخل فایل دوم هستند. +فایل *model.safetensors* در واقع *دیکشنری وضعیت‌ها* است و حاوی تمام وزن‌های مدل شماست. این دو فایل به همراه هم کاربرد دارند؛ فایل تنظیمات برای دانستن معماری به کار رفته در مدل ضروری است و پارامترهای مدل هم که همان وزن‌های داخل فایل دوم هستند. {:else} diff --git a/chapters/fr/chapter2/3.mdx b/chapters/fr/chapter2/3.mdx index c6dc2af76..a5df3eec2 100644 --- a/chapters/fr/chapter2/3.mdx +++ b/chapters/fr/chapter2/3.mdx @@ -164,7 +164,7 @@ Cela enregistre deux fichiers sur votre disque : ``` ls directory_on_my_computer -config.json pytorch_model.bin +config.json model.safetensors ``` {:else} ``` @@ -177,7 +177,7 @@ config.json tf_model.h5 Si vous jetez un coup d'œil au fichier *config.json*, vous reconnaîtrez les attributs nécessaires pour construire l'architecture du modèle. Ce fichier contient également certaines métadonnées, comme l'origine du *checkpoint* et la version de la bibliothèque 🤗 *Transformers* que vous utilisiez lors du dernier enregistrement du point *checkpoint*. {#if fw === 'pt'} -Le fichier *pytorch_model.bin* est connu comme le *dictionnaire d'état*. Il contient tous les poids de votre modèle. Les deux fichiers vont de pair : la configuration est nécessaire pour connaître l'architecture de votre modèle, tandis que les poids du modèle sont les paramètres de votre modèle. +Le fichier *model.safetensors* est connu comme le *dictionnaire d'état*. Il contient tous les poids de votre modèle. Les deux fichiers vont de pair : la configuration est nécessaire pour connaître l'architecture de votre modèle, tandis que les poids du modèle sont les paramètres de votre modèle. {:else} Le fichier *tf_model.h5* est connu comme le *dictionnaire d'état*. Il contient tous les poids de votre modèle. Les deux fichiers vont de pair : la configuration est nécessaire pour connaître l'architecture de votre modèle, tandis que les poids du modèle sont les paramètres de votre modèle. diff --git a/chapters/it/chapter2/3.mdx b/chapters/it/chapter2/3.mdx index 644f37755..6c1d9b3ea 100644 --- a/chapters/it/chapter2/3.mdx +++ b/chapters/it/chapter2/3.mdx @@ -160,7 +160,7 @@ In questo modo si salvano due file sul disco: ``` ls directory_on_my_computer -config.json pytorch_model.bin +config.json model.safetensors ``` {:else} ``` @@ -174,7 +174,7 @@ Se si dà un'occhiata al file *config.json*, si riconoscono gli attributi necess {#if fw === 'pt'} -Il file *pytorch_model.bin* è noto come *state dictionary*; contiene tutti i pesi del modello. I due file vanno di pari passo: la configurazione è necessaria per conoscere l'architettura del modello, mentre i pesi del modello sono i suoi parametri. +Il file *model.safetensors* è noto come *state dictionary*; contiene tutti i pesi del modello. I due file vanno di pari passo: la configurazione è necessaria per conoscere l'architettura del modello, mentre i pesi del modello sono i suoi parametri. {:else} diff --git a/chapters/ja/chapter2/3.mdx b/chapters/ja/chapter2/3.mdx index 1c25a3b8f..88573c4f2 100644 --- a/chapters/ja/chapter2/3.mdx +++ b/chapters/ja/chapter2/3.mdx @@ -160,7 +160,7 @@ model.save_pretrained("directory_on_my_computer") ``` ls directory_on_my_computer -config.json pytorch_model.bin +config.json model.safetensors ``` {:else} ``` @@ -173,7 +173,7 @@ config.json tf_model.h5 *config.json* ファイルを見てみると、モデルアーキテクチャを構築するために必要な属性がわかると思います。このファイルには、チェックポイントがどこで発生したのか、最後にチェックポイントを保存したときに使用していた🤗 Transformersのバージョンなどのメタデータも含まれています。 {#if fw === 'pt'} -*pytorch_model.bin* ファイルは *state dictionary* として知られており、モデルのすべての重みが含まれています。この2つのファイルは密接に関係しています。コンフィギュレーションはモデルのアーキテクチャを知るために必要であり、モデルの重みはモデルのパラメータです。 +*model.safetensors* ファイルは *state dictionary* として知られており、モデルのすべての重みが含まれています。この2つのファイルは密接に関係しています。コンフィギュレーションはモデルのアーキテクチャを知るために必要であり、モデルの重みはモデルのパラメータです。 {:else} *tf_model.h5*ファイルは*state dictionary*として知られており、すべてのモデルの重みが含まれています。この2つのファイルは密接に関係しています。設定はモデルのアーキテクチャを知るために必要であり、モデルの重みはモデルのパラメータです。 diff --git a/chapters/ko/chapter2/3.mdx b/chapters/ko/chapter2/3.mdx index 9380926dc..81d74f581 100644 --- a/chapters/ko/chapter2/3.mdx +++ b/chapters/ko/chapter2/3.mdx @@ -161,7 +161,7 @@ model.save_pretrained("directory_on_my_computer") ``` ls directory_on_my_computer -config.json pytorch_model.bin +config.json model.safetensors ``` {:else} ``` @@ -174,7 +174,7 @@ config.json tf_model.h5 *config.json* 파일은 모델 아키텍처를 구축하는 데 필요한 속성을 알려줍니다. 이 파일에는 체크포인트가 어디에서 생성되었는지, 마지막으로 체크포인트를 저장할 때 사용한 🤗 Transformers 버전 등의 메타데이터도 포함되어 있습니다. {#if fw === 'pt'} -The *pytorch_model.bin* file is known as the *state dictionary*; it contains all your model's weights. The two files go hand in hand; the configuration is necessary to know your model's architecture, while the model weights are your model's parameters. +The *model.safetensors* file is known as the *state dictionary*; it contains all your model's weights. The two files go hand in hand; the configuration is necessary to know your model's architecture, while the model weights are your model's parameters. {:else} The *tf_model.h5* file is known as the *state dictionary*; it contains all your model's weights. The two files go hand in hand; the configuration is necessary to know your model's architecture, while the model weights are your model's parameters. diff --git a/chapters/pt/chapter2/3.mdx b/chapters/pt/chapter2/3.mdx index f11570d46..4c888326d 100644 --- a/chapters/pt/chapter2/3.mdx +++ b/chapters/pt/chapter2/3.mdx @@ -160,7 +160,7 @@ Isto salva dois arquivos em seu disco: ``` ls path_no_seu_computador -config.json pytorch_model.bin +config.json model.safetensors ``` {:else} ``` @@ -173,7 +173,7 @@ config.json tf_model.h5 Se você der uma olhada no arquivo *config.json*, você reconhecerá os atributos necessários para construir a arquitetura modelo. Este arquivo também contém alguns metadados, como a origem do checkpoint e a versão 🤗 Transformers que você estava usando quando salvou o checkpoint pela última vez. {#if fw === 'pt'} -O arquivo *pytorch_model.bin* é conhecido como o *dicionário de estado*; ele contém todos os pesos do seu modelo. Os dois arquivos andam de mãos dadas; a configuração é necessária para conhecer a arquitetura de seu modelo, enquanto os pesos do modelo são os parâmetros de seu modelo. +O arquivo *model.safetensors* é conhecido como o *dicionário de estado*; ele contém todos os pesos do seu modelo. Os dois arquivos andam de mãos dadas; a configuração é necessária para conhecer a arquitetura de seu modelo, enquanto os pesos do modelo são os parâmetros de seu modelo. {:else} O arquivo *tf_model.h5* é conhecido como o *dicionário de estado*; ele contém todos os pesos do seu modelo. Os dois arquivos andam de mãos dadas; a configuração é necessária para conhecer a arquitetura de seu modelo, enquanto os pesos do modelo são os parâmetros de seu modelo. diff --git a/chapters/ru/chapter2/3.mdx b/chapters/ru/chapter2/3.mdx index 42296bcba..ddfa2040d 100644 --- a/chapters/ru/chapter2/3.mdx +++ b/chapters/ru/chapter2/3.mdx @@ -158,7 +158,7 @@ model.save_pretrained("directory_on_my_computer") ``` ls directory_on_my_computer -config.json pytorch_model.bin +config.json model.safetensors ``` {:else} ``` @@ -171,7 +171,7 @@ config.json tf_model.h5 Если вы посмотрите на файл *config.json*, то узнаете атрибуты, необходимые для построения архитектуры модели. Этот файл также содержит некоторые метаданные, такие как место создания контрольной точки и версию 🤗 Transformers, которую вы использовали при последнем сохранении контрольной точки. {#if fw === 'pt'} -Файл *pytorch_model.bin* известен как *словарь состояний (state dictionary)*; он содержит все веса вашей модели. Эти два файла неразрывно связаны друг с другом; конфигурация необходима для того, чтобы знать архитектуру модели, а веса модели - это ее параметры. +Файл *model.safetensors* известен как *словарь состояний (state dictionary)*; он содержит все веса вашей модели. Эти два файла неразрывно связаны друг с другом; конфигурация необходима для того, чтобы знать архитектуру модели, а веса модели - это ее параметры. {:else} Файл *tf_model.h5* известен как *словарь состояний (state dictionary)*; он содержит все веса вашей модели. Эти два файла неразрывно связаны друг с другом; конфигурация необходима для того, чтобы знать архитектуру модели, а веса модели - это ее параметры. diff --git a/chapters/th/chapter2/3.mdx b/chapters/th/chapter2/3.mdx index a0ac5f873..99eae6508 100644 --- a/chapters/th/chapter2/3.mdx +++ b/chapters/th/chapter2/3.mdx @@ -158,7 +158,7 @@ model.save_pretrained("directory_on_my_computer") ``` ls directory_on_my_computer -config.json pytorch_model.bin +config.json model.safetensors ``` {:else} ``` @@ -171,7 +171,7 @@ config.json tf_model.h5 ุุ้ถ้าคุณไปดูที่ไฟล์ *config.json* คุณจะพอนึกออกถึงคุณสมบัติ(attributes) ที่จำเป็นในการสร้างสถาปัตยกรรมของโมเดล ไฟล์นี้ประกอบด้วย metadata เช่น checkpoint เกิดมาจากที่ใด และ 🤗 Transformers เวอร์ชันใดที่คุณใช้ในการบันทึก checkpoint ล่าสุด {#if fw === 'pt'} -ไฟล์ *pytorch_model.bin* เป็นที่รู้จักในนาม *state dictionary*; มันประกอบด้วย weights ทัั้งหมดของโมเดลคุณ สองไฟล์ที่มีความเชื่อมโยงกัน ไฟล์ configuration จำเป็นที่จะต้องรู้สถาปัตยกรรมของโมเดลของคุณ ในขณะที่ weights ของโมเดลคุณ ก็คือ ตัวแปร(parameters) ของโมเดลคุณ +ไฟล์ *model.safetensors* เป็นที่รู้จักในนาม *state dictionary*; มันประกอบด้วย weights ทัั้งหมดของโมเดลคุณ สองไฟล์ที่มีความเชื่อมโยงกัน ไฟล์ configuration จำเป็นที่จะต้องรู้สถาปัตยกรรมของโมเดลของคุณ ในขณะที่ weights ของโมเดลคุณ ก็คือ ตัวแปร(parameters) ของโมเดลคุณ {:else} ไฟล์ *tf_model.h5* เป็นที่รู้จักในนาม *state dictionary*; มันประกอบด้วย weights ทัั้งหมดของโมเดลคุณ สองไฟล์ที่มีความเชื่อมโยงกัน ไฟล์ configuration จำเป็นที่จะต้องรู้สถาปัตยกรรมของโมเดลของคุณ ในขณะที่ weights ของโมเดลคุณ ก็คือ ตัวแปร(parameters) ของโมเดลคุณ diff --git a/chapters/vi/chapter2/3.mdx b/chapters/vi/chapter2/3.mdx index 2db14c065..627e11c6f 100644 --- a/chapters/vi/chapter2/3.mdx +++ b/chapters/vi/chapter2/3.mdx @@ -187,7 +187,7 @@ Thao tác này sẽ lưu hai tệp vào đĩa của bạn: ``` ls directory_on_my_computer -config.json pytorch_model.bin +config.json model.safetensors ``` {:else} @@ -204,7 +204,7 @@ Nếu bạn xem tệp _config.json_, bạn sẽ nhận ra các thuộc tính c {#if fw === 'pt'} -Tệp _pytorch_model.bin_ được gọi là _state dictionary_ (_từ điển trạng thái_); nó chứa tất cả các trọng số mô hình của bạn. Hai tập tin đi đôi với nhau; cấu hình là cần thiết để biết kiến trúc mô hình của bạn, trong khi trọng số mô hình là thông số của mô hình của bạn. +Tệp _model.safetensors_ được gọi là _state dictionary_ (_từ điển trạng thái_); nó chứa tất cả các trọng số mô hình của bạn. Hai tập tin đi đôi với nhau; cấu hình là cần thiết để biết kiến trúc mô hình của bạn, trong khi trọng số mô hình là thông số của mô hình của bạn. {:else} diff --git a/chapters/zh-CN/chapter2/3.mdx b/chapters/zh-CN/chapter2/3.mdx index 47a19592e..a408c3b70 100644 --- a/chapters/zh-CN/chapter2/3.mdx +++ b/chapters/zh-CN/chapter2/3.mdx @@ -182,7 +182,7 @@ model.save_pretrained("directory_on_my_computer") ``` ls directory_on_my_computer -config.json pytorch_model.bin +config.json model.safetensors ``` {:else} ``` @@ -197,7 +197,7 @@ config.json 文件,您将识别构建模型体系结构所需的属性。该文件还包含一些元数据,例如*checkpoint*的来源以及上次保存检查点时使用的🤗 Transformers版本。 {#if fw === 'pt'} -这个 *pytorch_model.bin* 文件就是众所周知的*state dictionary*; 它包含模型的所有权重。这两个文件密切相关;这个配置是了解您的模型架构所必需的,而模型权重则是您模型的参数。 +这个 *model.safetensors* 文件就是众所周知的*state dictionary*; 它包含模型的所有权重。这两个文件密切相关;这个配置是了解您的模型架构所必需的,而模型权重则是您模型的参数。 {:else} 这个 *tf_model.h5* 文件就是众所周知的*state dictionary*; 它包含模型的所有权重。这两个文件密切相关;这个配置是了解您的模型架构所必需的,而模型权重则是您模型的参数。 diff --git a/chapters/zh-TW/chapter2/3.mdx b/chapters/zh-TW/chapter2/3.mdx index b93ad440e..6bee4a3b8 100644 --- a/chapters/zh-TW/chapter2/3.mdx +++ b/chapters/zh-TW/chapter2/3.mdx @@ -184,7 +184,7 @@ model.save_pretrained("directory_on_my_computer") ``` ls directory_on_my_computer -config.json pytorch_model.bin +config.json model.safetensors ``` {:else} ``` @@ -199,10 +199,10 @@ config.json 文件,您將識別構建模型體系結構所需的屬性。該文件還包含一些元數據,例如檢查點的來源以及上次保存檢查點時使用的🤗 Transformers版本。 {#if fw === 'pt'} -這個 *pytorch_model.bin* 文件就是眾所周知的*state dictionary*; 它包含模型的所有權重。這兩個文件齊頭並進;配置是瞭解模型體系結構所必需的,而模型權重是模型的參數。 +這個 *model.safetensors* 文件就是眾所周知的*state dictionary*; 它包含模型的所有權重。這兩個文件齊頭並進;配置是瞭解模型體系結構所必需的,而模型權重是模型的參數。 {:else} -這個 *pytorch_model.bin* 文件就是眾所周知的*state dictionary*; 它包含模型的所有權重。這兩個文件齊頭並進;配置是瞭解模型體系結構所必需的,而模型權重是模型的參數。 +這個 *model.safetensors* 文件就是眾所周知的*state dictionary*; 它包含模型的所有權重。這兩個文件齊頭並進;配置是瞭解模型體系結構所必需的,而模型權重是模型的參數。 {/if} From 1ae66008a6d7dab01712473c1428b6bf2ae787f3 Mon Sep 17 00:00:00 2001 From: Thomas Liang Date: Mon, 2 Jun 2025 12:58:47 +0000 Subject: [PATCH 02/43] [zh-TW] Added chapters 1-11 --- chapters/zh-TW/chapter1/11.mdx | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 chapters/zh-TW/chapter1/11.mdx diff --git a/chapters/zh-TW/chapter1/11.mdx b/chapters/zh-TW/chapter1/11.mdx new file mode 100644 index 000000000..db174793d --- /dev/null +++ b/chapters/zh-TW/chapter1/11.mdx @@ -0,0 +1,21 @@ +# 測驗時間! + +是時候測試你的知識了!我們為你準備了一個簡短的測驗,來測試你對本章節所涵蓋概念的理解程度。 + +要參加測驗,你需要按照以下步驟進行: + +1. 登入你的 Hugging Face 帳戶 +2. 回答測驗中的問題 +3. 提交你的答案 + + +## 多選題測驗 + +在這個測驗中,你需要從選項列表中選擇正確答案。我們將測試你對監督式微調基礎知識的掌握程度。 + + \ No newline at end of file From 50c2ce2e380cdf69818cf231bed1aae64d5642ec Mon Sep 17 00:00:00 2001 From: Thomas Liang Date: Mon, 2 Jun 2025 21:57:21 +0800 Subject: [PATCH 03/43] add toctree file --- chapters/zh-TW/_toctree.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/chapters/zh-TW/_toctree.yml b/chapters/zh-TW/_toctree.yml index fecc7863f..43681adbf 100644 --- a/chapters/zh-TW/_toctree.yml +++ b/chapters/zh-TW/_toctree.yml @@ -25,6 +25,8 @@ title: 總結 - local: chapter1/10 title: 章末小測驗 + - local: chapter1/11 + title: 認證測驗 quiz: 1 - title: 2. 使用 🤗 Transformers From 5902cb169e851bd0ab19ce2754762bb57fc37254 Mon Sep 17 00:00:00 2001 From: Thomas Liang Date: Mon, 2 Jun 2025 12:58:47 +0000 Subject: [PATCH 04/43] [zh-TW] Added chapters 1-11 --- chapters/zh-TW/chapter1/11.mdx | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 chapters/zh-TW/chapter1/11.mdx diff --git a/chapters/zh-TW/chapter1/11.mdx b/chapters/zh-TW/chapter1/11.mdx new file mode 100644 index 000000000..db174793d --- /dev/null +++ b/chapters/zh-TW/chapter1/11.mdx @@ -0,0 +1,21 @@ +# 測驗時間! + +是時候測試你的知識了!我們為你準備了一個簡短的測驗,來測試你對本章節所涵蓋概念的理解程度。 + +要參加測驗,你需要按照以下步驟進行: + +1. 登入你的 Hugging Face 帳戶 +2. 回答測驗中的問題 +3. 提交你的答案 + + +## 多選題測驗 + +在這個測驗中,你需要從選項列表中選擇正確答案。我們將測試你對監督式微調基礎知識的掌握程度。 + + \ No newline at end of file From 30d57f552e4bea670f4ad1b150915de8404f2fb8 Mon Sep 17 00:00:00 2001 From: Thomas Liang Date: Mon, 2 Jun 2025 21:57:21 +0800 Subject: [PATCH 05/43] add toctree file --- chapters/zh-TW/_toctree.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/chapters/zh-TW/_toctree.yml b/chapters/zh-TW/_toctree.yml index fecc7863f..43681adbf 100644 --- a/chapters/zh-TW/_toctree.yml +++ b/chapters/zh-TW/_toctree.yml @@ -25,6 +25,8 @@ title: 總結 - local: chapter1/10 title: 章末小測驗 + - local: chapter1/11 + title: 認證測驗 quiz: 1 - title: 2. 使用 🤗 Transformers From 9bd5fa86afb53595b88340834088490ca1bcc681 Mon Sep 17 00:00:00 2001 From: Rahul Konda Date: Mon, 23 Jun 2025 16:22:20 +0530 Subject: [PATCH 06/43] added te/chapter1/2-3 --- chapters/te/_toctree.yml | 4 + chapters/te/chapter1/2.mdx | 56 +++++ chapters/te/chapter1/3.mdx | 425 +++++++++++++++++++++++++++++++++++++ 3 files changed, 485 insertions(+) create mode 100644 chapters/te/chapter1/2.mdx create mode 100644 chapters/te/chapter1/3.mdx diff --git a/chapters/te/_toctree.yml b/chapters/te/_toctree.yml index dc9644297..0afdb7624 100644 --- a/chapters/te/_toctree.yml +++ b/chapters/te/_toctree.yml @@ -6,3 +6,7 @@ sections: - local: chapter1/1 title: పరిచయం + - local: chapter1/2 + title: Natural Language Processing (NLP) మరియు Large Language Models (LLMs) + - local: chapter1/3 + title: ట్రాన్స్‌ఫార్మర్‌లు, అవి ఏమి చేయగలవు? diff --git a/chapters/te/chapter1/2.mdx b/chapters/te/chapter1/2.mdx new file mode 100644 index 000000000..fa7996c5d --- /dev/null +++ b/chapters/te/chapter1/2.mdx @@ -0,0 +1,56 @@ +# Natural Language Processing (NLP) మరియు Large Language Models (LLMs)[[natural-language-processing-and-large-language-models]] + + + +Transformer మోడల్స్‌లోకి వెళ్లే ముందు, Natural Language Processing అంటే ఏమిటి, Large Language Models ఈ రంగాన్ని ఎలా మార్చాయి మరియు మనం దాని గురించి ఎందుకు శ్రద్ధ వహించాలి అనే దానిపై త్వరగా ఒక అవలోకనం చేద్దాం. + +## NLP అంటే ఏమిటి?[[what-is-nlp]] + + + +NLP అనేది మానవ భాషకు సంబంధించిన ప్రతిదాన్ని అర్థం చేసుకోవడంపై దృష్టి సారించే భాషాశాస్త్రం మరియు మెషిన్ లెర్నింగ్ రంగం. NLP పనుల లక్ష్యం కేవలం ఒక్కొక్క పదాన్ని వ్యక్తిగతంగా అర్థం చేసుకోవడం మాత్రమే కాదు, ఆ పదాల సందర్భాన్ని అర్థం చేసుకోగలగడం. + +సాధారణ NLP పనుల జాబితా క్రింద ఇవ్వబడింది, ప్రతిదానికి కొన్ని ఉదాహరణలతో: + +- **మొత్తం వాక్యాలను వర్గీకరించడం**: ఒక సమీక్ష యొక్క భావనను పొందడం, ఒక ఇమెయిల్ స్పామా కాదా అని గుర్తించడం, ఒక వాక్యం వ్యాకరణపరంగా సరైనదా లేదా రెండు వాక్యాలు తార్కికంగా సంబంధం కలిగి ఉన్నాయా లేదా అని నిర్ణయించడం. +- **ఒక వాక్యంలో ప్రతి పదాన్ని వర్గీకరించడం**: ఒక వాక్యం యొక్క వ్యాకరణ భాగాలను (నామవాచకం, క్రియ, విశేషణం) లేదా పేరున్న ఎంటిటీలను (వ్యక్తి, స్థలం, సంస్థ) గుర్తించడం +- **వచన కంటెంట్‌ను రూపొందించడం**: స్వయంచాలకంగా సృష్టించబడిన వచనంతో ఒక ప్రాంప్ట్‌ను పూర్తి చేయడం, మాస్క్ చేయబడిన పదాలతో ఒక వచనంలో ఖాళీలను పూరించడం. +- **ఒక వచనం నుండి సమాధానాన్ని సేకరించడం**: ఒక ప్రశ్న మరియు సందర్భం ఇచ్చినప్పుడు, సందర్భంలో అందించబడిన సమాచారం ఆధారంగా ప్రశ్నకు సమాధానాన్ని సేకరించడం. +- **ఇన్‌పుట్ వచనం నుండి కొత్త వాక్యాన్ని రూపొందించడం**: ఒక వచనాన్ని మరొక భాషలోకి అనువదించడం, ఒక వచనాన్ని సంగ్రహించడం. + +NLP కేవలం వ్రాతపూర్వక వచనానికి మాత్రమే పరిమితం కాదు. ఇది ప్రసంగ గుర్తింపు మరియు కంప్యూటర్ విజన్‌లో సంక్లిష్ట సవాళ్లను కూడా పరిష్కరిస్తుంది, ఉదాహరణకు ఆడియో నమూనా యొక్క ట్రాన్స్‌క్రిప్ట్ లేదా చిత్రం యొక్క వివరణను రూపొందించడం వంటివి. + +## Large Language Models (LLMs) పెరుగుదల[[rise-of-llms]] + +ఇటీవలి సంవత్సరాలలో, NLP రంగం Large Language Models (LLMs) ద్వారా విప్లవాత్మకంగా మారింది. GPT (Generative Pre-trained Transformer) మరియు [Llama](https://huggingface.co/meta-llama), వంటి ఆర్కిటెక్చర్లను కలిగి ఉన్న ఈ మోడల్స్, భాషా ప్రాసెసింగ్‌లో సాధ్యమయ్యే వాటిని మార్చాయి. + + + +ఒక Large Language Model (LLM) అనేది భారీ మొత్తంలో వచన డేటాపై శిక్షణ పొందిన ఒక AI మోడల్, ఇది మానవ-వంటి వచనాన్ని అర్థం చేసుకోగలదు మరియు ఉత్పత్తి చేయగలదు, భాషలో నమూనాలను గుర్తించగలదు మరియు టాస్క్-నిర్దిష్ట శిక్షణ లేకుండా విస్తృత శ్రేణి భాషా పనులను చేయగలదు. అవి Natural Language Processing (NLP) రంగంలో గణనీయమైన పురోగతిని సూచిస్తాయి. + + + +LLMలు వీటి ద్వారా వర్గీకరించబడతాయి: + +- **ప్రమాణం**: ఇవి లక్షల, బిలియన్ల లేదా సెంట్స్ బిలియన్ల పరామితులను కలిగి ఉంటాయి +- **సామాన్య సామర్థ్యాలు**: ఇవి టాస్క్-నిర్దిష్ట శిక్షణ లేకుండా అనేక పనులను నిర్వహించగలవు +- **ఇన్-కాంటెక్స్ట్ లెర్నింగ్**: ఇవి ప్రాంప్ట్‌లో అందించిన ఉదాహరణల నుండి నేర్చుకోవచ్చు +- **ఉద్భవించే సామర్థ్యాలు**: ఈ మోడల్స్ పరిమాణంలో పెరిగేకొద్దీ, అవి స్పష్టంగా ప్రోగ్రామ్ చేయబడని లేదా ఊహించని సామర్థ్యాలను ప్రదర్శిస్తాయి + +LLMల ఉద్భవం, ప్రత్యేక NLP పనుల కోసం ప్రత్యేక మోడల్స్‌ను నిర్మించడంనుంచి, విస్తృత శ్రేణా భాషా పనులను పరిష్కరించడానికి ప్రాంప్ట్ చేయబడిన లేదా ఫైన్-ట్యూన్ చేయబడిన ఒక పెద్ద మోడల్‌ను ఉపయోగించడం వరకు మార్పు తీసుకువచ్చింది. ఇది సాంకేతిక భాషా ప్రాసెసింగ్‌ను మరింత అందుబాటులోకి తెచ్చింది, కానీ సమర్థత, నైతికత మరియు అమలు వంటి కొత్త సవాళ్లను కూడా పరిచయం చేసింది. + +## LLMలు మరియు వాటి పరిమితులు[[llms-and-their-limitations]] + +LLMలు కూడా ముఖ్యమైన పరిమితులను కలిగి ఉంటాయి: + +- **హాల్యూసినేషన్స్**: అవి తప్పు సమాచారాన్ని నమ్మకంగా ఉత్పత్తి చేయగలవు +- **నిజమైన అర్థం లేకపోవడం**: అవి ప్రపంచాన్ని నిజంగా అర్థం చేసుకోలేవు మరియు కేవలం గణాంక నమూనాలపై పనిచేస్తాయి +- **పక్షపాతం**: అవి శిక్షణ డేటా లేదా ఇన్‌పుట్‌లో ఉన్న పక్షపాతాన్ని పునరావృతించవచ్చు +- **కాంటెక్స్ట్ విండోలు**: అవి పరిమిత సందర్భ విండోలను కలిగి ఉంటాయి (అయితే ఇది మెరుగుపడుతోంది) +- **కంప్యూటేషనల్ వనరులు**: అవి గణనీయమైన కంప్యూటేషనల్ వనరులను అవసరం + +## భాషా ప్రాసెసింగ్ ఎందుకు సవాలుగా ఉంది?[[why-is-it-challenging]] + +కంప్యూటర్లు మానవులు ప్రాసెస్ చేసే విధంగా సమాచారాన్ని ప్రాసెస్ చేయవు. ఉదాహరణకు, మనం "I am hungry" అనే వాక్యాన్ని చదివినప్పుడు, మనం దాని అర్థాన్ని సులభంగా అర్థం చేసుకోగలం. అదేవిధంగా, "I am hungry" మరియు "I am sad" వంటి రెండు వాక్యాలు ఇచ్చినప్పుడు, అవి ఎంత సారూప్యంగా ఉన్నాయో మనం సులభంగా నిర్ణయించగలం. మెషిన్ లెర్నింగ్ (ML) మోడల్స్‌కు, అటువంటి పనులు మరింత కష్టం. మోడల్ దాని నుండి నేర్చుకోవడానికి వీలుగా వచనాన్ని ప్రాసెస్ చేయాలి. మరియు భాష సంక్లిష్టంగా ఉన్నందున, ఈ ప్రాసెసింగ్ ఎలా చేయబడాలి అనే దాని గురించి మనం జాగ్రత్తగా ఆలోచించాలి. వచనాన్ని ఎలా సూచించాలో చాలా పరిశోధనలు జరిగాయి, మరియు తదుపరి అధ్యాయంలో కొన్ని పద్ధతులను చూద్దాం. + +LLMలలో పురోగతి ఉన్నప్పటికీ, అనేక ప్రాథమిక సవాళ్లు అలాగే ఉన్నాయి. వీటిలో అస్పష్టత, సాంస్కృతిక సందర్భం, వ్యంగ్యం మరియు హాస్యం అర్థం చేసుకోవడం ఉన్నాయి. LLMలు విభిన్న డేటాసెట్‌లపై భారీ శిక్షణ ద్వారా ఈ సవాళ్లను పరిష్కరిస్తాయి, అయితే అనేక సంక్లిష్ట దృశ్యాలలో మానవ-స్థాయి అవగాహనకు తరచుగా తక్కువగా ఉంటాయి. diff --git a/chapters/te/chapter1/3.mdx b/chapters/te/chapter1/3.mdx new file mode 100644 index 000000000..28f4e3755 --- /dev/null +++ b/chapters/te/chapter1/3.mdx @@ -0,0 +1,425 @@ +# ట్రాన్స్‌ఫార్మర్‌లు, అవి ఏమి చేయగలవు?[[transformers-what-can-they-do]] + + + +ఈ విభాగంలో, Transformer మోడల్స్ ఏమి చేయగలవో చూద్దాం మరియు 🤗 Transformers లైబ్రరీ నుండి మా మొదటి సాధనం: `pipeline()` ఫంక్షన్‌ను ఉపయోగిద్దాం. + + +👀 కుడివైపు పైభాగంలో ఉన్న Open in Colab బటన్ చూడండి? దానిపై క్లిక్ చేసి, ఈ విభాగానికి సంబంధించిన అన్ని కోడ్ నమూనాలతో ఉన్న Google Colab నోట్‌బుక్‌ను తెరవండి. కోడ్ ఉదాహరణలు ఉన్న ఏ విభాగంలోనైనా ఈ బటన్ ఉంటుంది. + +మీరు ఉదాహరణలను స్థానికంగా అమలు చేయాలనుకుంటే, మేము సెటప్ ను చూడమని సిఫార్సు చేస్తాము. + + + +## ట్రాన్స్‌ఫార్మర్‌లు ప్రతిచోటా ఉన్నాయి![[transformers-are-everywhere]] + +Transformer మోడల్స్ సహజ భాషా ప్రాసెసింగ్ (NLP), కంప్యూటర్ విజన్, ఆడియో ప్రాసెసింగ్ మరియు మరిన్ని వంటి వివిధ రంగాలలో అన్ని రకాల పనులను పరిష్కరించడానికి ఉపయోగిస్తారు. ఇక్కడ కొన్ని కంపెనీలు మరియు సంస్థలు ఉన్నాయి, ఇవి Hugging Face మరియు Transformer మోడల్స్ ను ఉపయోగిస్తున్నాయి, మరియు వారి మోడల్స్‌ను పంచుకోవడం ద్వారా సమాజానికి తిరిగి తోడ్పడతాయి: + +Companies using Hugging Face + +[🤗 Transformers లైబ్రరీ](https://github.com/huggingface/transformers) ఆ పంచుకున్న మోడల్స్‌ను సృష్టించడానికి మరియు ఉపయోగించడానికి ఫంక్షనాలిటీని అందిస్తుంది. [మోడల్ హబ్](https://huggingface.co/models) లో మిలియన్ల కొద్దీ ముందుగా శిక్షణ పొందిన మోడల్స్ ఉన్నాయి, వాటిని ఎవరైనా డౌన్‌లోడ్ చేసి ఉపయోగించవచ్చు. మీరు మీ స్వంత మోడల్స్‌ను కూడా హబ్‌కు అప్‌లోడ్ చేయవచ్చు! + + + +⚠️ Hugging Face హబ్ కేవలం Transformer మోడల్స్ కి మాత్రమే పరిమితం కాదు. ఎవరైనా ఏ రకమైన మోడల్స్ లేదా డేటాసెట్స్‌ను అయినా పంచుకోవచ్చు! అందుబాటులో ఉన్న అన్ని ఫీచర్ల నుండి ప్రయోజనం పొందడానికి huggingface.co ఖాతాను సృష్టించుకోండి! + + + +Transformer మోడల్స్ తెర వెనుక ఎలా పనిచేస్తాయో లోతుగా పరిశీలించే ముందు, కొన్ని ఆసక్తికరమైన NLP సమస్యలను పరిష్కరించడానికి అవి ఎలా ఉపయోగించబడతాయో కొన్ని ఉదాహరణలు చూద్దాం. + +## పైప్‌లైన్‌లతో పని చేయడం[[working-with-pipelines]] + + + +🤗 Transformers లైబ్రరీలోని అత్యంత ప్రాథమిక వస్తువు `pipeline()` ఫంక్షన్. ఇది ఒక మోడల్‌ను దాని అవసరమైన ప్రిప్రాసెసింగ్ మరియు పోస్ట్ ప్రాసెసింగ్ దశలతో కలుపుతుంది, తద్వారా మనం నేరుగా ఏదైనా టెక్స్ట్‌ను ఇన్పుట్ చేసి అర్థవంతమైన సమాధానాన్ని పొందవచ్చు: + +```python +from transformers import pipeline + +classifier = pipeline("sentiment-analysis") +classifier("I've been waiting for a HuggingFace course my whole life.") +``` + +```python out +[{'label': 'POSITIVE', 'score': 0.9598047137260437}] +``` + +మనం అనేక వాక్యాలను కూడా పంపవచ్చు! + +```python +classifier( + ["I've been waiting for a HuggingFace course my whole life.", "I hate this so much!"] +) +``` + +```python out +[{'label': 'POSITIVE', 'score': 0.9598047137260437}, + {'label': 'NEGATIVE', 'score': 0.9994558095932007}] +``` + +డిఫాల్ట్‌గా, ఈ పైప్‌లైన్ ఇంగ్లీష్‌లో సెంటిమెంట్ విశ్లేషణ కోసం ఫైన్-ట్యూన్ చేయబడిన ఒక నిర్దిష్ట ప్రీ-ట్రైన్డ్ మోడల్‌ను ఎంచుకుంటుంది. మీరు `classifier` ఆబ్జెక్ట్‌ను సృష్టించినప్పుడు మోడల్ డౌన్‌లోడ్ చేయబడి కాష్ చేయబడుతుంది. మీరు ఆదేశాన్ని మళ్లీ అమలు చేస్తే, కాష్ చేయబడిన మోడల్ ఉపయోగించబడుతుంది మరియు మోడల్‌ను మళ్లీ డౌన్‌లోడ్ చేయాల్సిన అవసరం లేదు. + +మీరు కొన్ని టెక్స్ట్‌ను పైప్‌లైన్‌కు పంపినప్పుడు మూడు ప్రధాన దశలు ఉంటాయి: + +1. మోడల్ అర్థం చేసుకోగల ఫార్మాట్‌లోకి టెక్స్ట్ ప్రిప్రాసెస్ చేయబడుతుంది. +2. ప్రిప్రాసెస్ చేయబడిన ఇన్‌పుట్‌లు మోడల్‌కు పంపబడతాయి. +3. మోడల్ యొక్క అంచనాలు పోస్ట్-ప్రాసెస్ చేయబడతాయి, తద్వారా మీరు వాటిని అర్థం చేసుకోవచ్చు. + +## వివిధ మాధ్యమాల కోసం అందుబాటులో ఉన్న పైప్‌లైన్‌లు + +`pipeline()` ఫంక్షన్ బహుళ మాధ్యమాలను సపోర్ట్ చేస్తుంది, టెక్స్ట్, చిత్రాలు, ఆడియో మరియు మల్టీమోడల్ పనులతో కూడా పని చేయడానికి మిమ్మల్ని అనుమతిస్తుంది. ఈ కోర్సులో మనం టెక్స్ట్ పనులపై దృష్టి పెడతాము, కానీ ట్రాన్స్‌ఫార్మర్ ఆర్కిటెక్చర్ యొక్క సామర్థ్యాన్ని అర్థం చేసుకోవడం ఉపయోగకరం, కాబట్టి మనం దానిని క్లుప్తంగా వివరిస్తాము. + +ఇక్కడ అందుబాటులో ఉన్న వాటి యొక్క స్థూలదృష్టి ఉంది: + + + +పైప్‌లైన్‌ల పూర్తి మరియు నవీకరించబడిన జాబితా కోసం, [🤗 Transformers డాక్యుమెంటేషన్](https://huggingface.co/docs/hub/en/models-tasks) ను చూడండి. + + + +### టెక్స్ట్ పైప్‌లైన్‌లు + +- `text-generation`: ఒక ప్రాంప్ట్ నుండి టెక్స్ట్‌ను రూపొందించడం +- `text-classification`: టెక్స్ట్‌ను ముందుగా నిర్వచించిన వర్గాలలోకి వర్గీకరించడం +- `summarization`: ముఖ్యమైన సమాచారాన్ని కాపాడుకుంటూ టెక్స్ట్ యొక్క చిన్న వెర్షన్‌ను సృష్టించడం +- `translation`: ఒక భాష నుండి మరొక భాషకు టెక్స్ట్‌ను అనువదించడం +- `zero-shot-classification`: నిర్దిష్ట లేబుల్స్‌పై ముందస్తు శిక్షణ లేకుండా టెక్స్ట్‌ను వర్గీకరించడం +- `feature-extraction`: టెక్స్ట్ యొక్క వెక్టర్ ప్రాతినిధ్యాలను సంగ్రహించడం + +### చిత్ర పైప్‌లైన్‌లు + +- `image-to-text`: చిత్రాల యొక్క టెక్స్ట్ వివరణలను రూపొందించడం +- `image-classification`: ఒక చిత్రంలోని వస్తువులను గుర్తించడం +- `object-detection`: చిత్రాలలో వస్తువులను గుర్తించి వాటి స్థానాన్ని కనుగొనడం + +### ఆడియో పైప్‌లైన్‌లు + +- `automatic-speech-recognition`: ప్రసంగాన్ని టెక్స్ట్‌గా మార్చడం +- `audio-classification`: ఆడియోను వర్గాలలోకి వర్గీకరించడం +- `text-to-speech`: టెక్స్ట్‌ను మాట్లాడే ఆడియోగా మార్చడం + +### మల్టీమోడల్ పైప్‌లైన్‌లు + +- `image-text-to-text`: ఒక టెక్స్ట్ ప్రాంప్ట్ ఆధారంగా చిత్రానికి ప్రతిస్పందించడం + +ఈ పైప్‌లైన్‌లలో కొన్నింటిని మరింత వివరంగా అన్వేషిద్దాం! + +## జీరో-షాట్ క్లాసిఫికేషన్[[zero-shot-classification]] + +లేబుల్ చేయని టెక్స్ట్‌లను వర్గీకరించాల్సిన మరింత సవాలుతో కూడిన పనితో ప్రారంభిద్దాం. ఇది వాస్తవ ప్రపంచ ప్రాజెక్టులలో ఒక సాధారణ దృశ్యం ఎందుకంటే టెక్స్ట్‌ను వ్యాఖ్యానించడం సాధారణంగా సమయం తీసుకుంటుంది మరియు డొమైన్ నైపుణ్యం అవసరం. ఈ వినియోగ సందర్భం కోసం, `zero-shot-classification` పైప్‌లైన్ చాలా శక్తివంతమైనది: ఇది వర్గీకరణ కోసం ఏ లేబుల్స్ ఉపయోగించాలో నిర్దేశించడానికి మిమ్మల్ని అనుమతిస్తుంది, కాబట్టి మీరు ముందుగా శిక్షణ పొందిన మోడల్ యొక్క లేబుల్స్‌పై ఆధారపడాల్సిన అవసరం లేదు. మోడల్ ఆ రెండు లేబుల్స్ ఉపయోగించి ఒక వాక్యాన్ని పాజిటివ్ లేదా నెగటివ్‌గా ఎలా వర్గీకరించగలదో మీరు ఇప్పటికే చూశారు — కానీ ఇది మీకు నచ్చిన ఏ ఇతర లేబుల్స్ సెట్‌ను ఉపయోగించి కూడా టెక్స్ట్‌ను వర్గీకరించగలదు. + +```python +from transformers import pipeline + +classifier = pipeline("zero-shot-classification") +classifier( + "This is a course about the Transformers library", + candidate_labels=["education", "politics", "business"], +) +``` + +```python out +{'sequence': 'This is a course about the Transformers library', + 'labels': ['education', 'business', 'politics'], + 'scores': [0.8445963859558105, 0.111976258456707, 0.043427448719739914]} +``` + +ఈ పైప్‌లైన్‌ను _జీరో-షాట్_ అని అంటారు ఎందుకంటే దాన్ని ఉపయోగించడానికి మీరు మీ డేటాపై మోడల్‌ను ఫైన్-ట్యూన్ చేయాల్సిన అవసరం లేదు. ఇది మీకు కావలసిన లేబుల్స్ జాబితా కోసం నేరుగా సంభావ్యత స్కోర్‌లను తిరిగి ఇవ్వగలదు! + + + +✏️ **ప్రయత్నించి చూడండి!** మీ స్వంత సీక్వెన్సులు మరియు లేబుల్స్‌తో ఆడుకోండి మరియు మోడల్ ఎలా ప్రవర్తిస్తుందో చూడండి. + + + +## టెక్స్ట్ జనరేషన్[[text-generation]] + +ఇప్పుడు కొన్ని టెక్స్ట్‌ను రూపొందించడానికి పైప్‌లైన్‌ను ఎలా ఉపయోగించాలో చూద్దాం. ఇక్కడ ప్రధాన ఆలోచన ఏమిటంటే మీరు ఒక ప్రాంప్ట్ అందిస్తారు మరియు మోడల్ మిగిలిన టెక్స్ట్‌ను రూపొందించడం ద్వారా దానిని స్వయంచాలకంగా పూర్తి చేస్తుంది. ఇది అనేక ఫోన్‌లలో కనిపించే ప్రిడిక్టివ్ టెక్స్ట్ ఫీచర్‌కు సమానంగా ఉంటుంది. టెక్స్ట్ జనరేషన్ యాదృచ్ఛికతను కలిగి ఉంటుంది, కాబట్టి క్రింద చూపిన ఫలితాలు మీకు లభించకపోవడం సాధారణం. + +```python +from transformers import pipeline + +generator = pipeline("text-generation") +generator("In this course, we will teach you how to") +``` + +```python out +[{'generated_text': 'In this course, we will teach you how to understand and use ' + 'data flow and data interchange when handling user data. We ' + 'will be working with one or more of the most commonly used ' + 'data flows — data flows of various types, as seen by the ' + 'HTTP'}] +``` + +మీరు `num_return_sequences` ఆర్గ్యుమెంట్‌తో ఎన్ని వేర్వేరు సీక్వెన్సులను రూపొందించాలో మరియు `max_length` ఆర్గ్యుమెంట్‌తో అవుట్‌పుట్ టెక్స్ట్ యొక్క మొత్తం పొడవును నియంత్రించవచ్చు. + + + +✏️ **ప్రయత్నించి చూడండి!** `num_return_sequences` మరియు `max_length` ఆర్గ్యుమెంట్‌లను ఉపయోగించి 15 పదాల పొడవు గల రెండు వాక్యాలను రూపొందించండి. + + + +## హబ్ నుండి ఏ మోడల్‌నైనా పైప్‌లైన్‌లో ఉపయోగించడం[[using-any-model-from-the-hub-in-a-pipeline]] + +మునుపటి ఉదాహరణలు పని కోసం డిఫాల్ట్ మోడల్‌ను ఉపయోగించాయి, కానీ మీరు ఒక నిర్దిష్ట పని కోసం పైప్‌లైన్‌లో ఉపయోగించడానికి హబ్ నుండి ఒక నిర్దిష్ట మోడల్‌ను కూడా ఎంచుకోవచ్చు — ఉదాహరణకు, టెక్స్ట్ జనరేషన్. [మోడల్ హబ్](https://huggingface.co/models) కు వెళ్లి, ఆ పని కోసం మద్దతు ఉన్న మోడల్స్‌ను మాత్రమే ప్రదర్శించడానికి ఎడమవైపున ఉన్న సంబంధిత ట్యాగ్‌పై క్లిక్ చేయండి. మీరు [ఈ పేజీ](https://huggingface.co/models?pipeline_tag=text-generation)のようなページにたどり着くはずです. + +[`HuggingFaceTB/SmolLM2-360M`](https://huggingface.co/HuggingFaceTB/SmolLM2-360M) మోడల్‌ను ప్రయత్నిద్దాం! మునుపటి పైప్‌లైన్‌లో దాన్ని ఎలా లోడ్ చేయాలో ఇక్కడ ఉంది: + +```python +from transformers import pipeline + +generator = pipeline("text-generation", model="HuggingFaceTB/SmolLM2-360M") +generator( + "In this course, we will teach you how to", + max_length=30, + num_return_sequences=2, +) +``` + +```python out +[{'generated_text': 'In this course, we will teach you how to manipulate the world and ' + 'move your mental and physical capabilities to your advantage.'}, + {'generated_text': 'In this course, we will teach you how to become an expert and ' + 'practice realtime, and with a hands on experience on both real ' + 'time and real'}] +``` + +మీరు భాషా ట్యాగ్‌లపై క్లిక్ చేయడం ద్వారా మోడల్ కోసం మీ శోధనను మెరుగుపరచవచ్చు మరియు మరొక భాషలో టెక్స్ట్‌ను రూపొందించే మోడల్‌ను ఎంచుకోవచ్చు. మోడల్ హబ్ అనేక భాషలకు మద్దతు ఇచ్చే బహుభాషా మోడల్స్ కోసం చెక్‌పాయింట్లను కూడా కలిగి ఉంది. + +మీరు దానిపై క్లిక్ చేయడం ద్వారా ఒక మోడల్‌ను ఎంచుకున్న తర్వాత, దాన్ని నేరుగా ఆన్‌లైన్‌లో ప్రయత్నించడానికి ఒక విడ్జెట్ ఉందని మీరు చూస్తారు. ఈ విధంగా మీరు మోడల్‌ను డౌన్‌లోడ్ చేయడానికి ముందు దాని సామర్థ్యాలను త్వరగా పరీక్షించవచ్చు. + + + +✏️ **ప్రయత్నించి చూడండి!** మరొక భాష కోసం టెక్స్ట్ జనరేషన్ మోడల్‌ను కనుగొనడానికి ఫిల్టర్‌లను ఉపయోగించండి. విడ్జెట్‌తో ఆడుకోవడానికి సంకోచించకండి మరియు దానిని పైప్‌లైన్‌లో ఉపయోగించండి! + + + +### ఇన్ఫరెన్స్ ప్రొవైడర్లు[[inference-providers]] + +అన్ని మోడల్స్‌ను Hugging Face [వెబ్‌సైట్](https://huggingface.co/docs/inference-providers/en/index) లో అందుబాటులో ఉన్న ఇన్ఫరెన్స్ ప్రొవైడర్ల ద్వారా మీ బ్రౌజర్ ద్వారా నేరుగా పరీక్షించవచ్చు. మీరు కస్టమ్ టెక్స్ట్‌ను ఇన్‌పుట్ చేసి మరియు మోడల్ ఇన్‌పుట్ డేటాను ప్రాసెస్ చేయడాన్ని చూడటం ద్వారా ఈ పేజీలో నేరుగా మోడల్‌తో ఆడవచ్చు. + +విడ్జెట్‌ను శక్తివంతం చేసే ఇన్ఫరెన్స్ ప్రొవైడర్లు చెల్లింపు ఉత్పత్తిగా కూడా అందుబాటులో ఉన్నాయి, ఇది మీ వర్క్‌ఫ్లోల కోసం అవసరమైతే ఉపయోగపడుతుంది. మరిన్ని వివరాల కోసం [ధరల పేజీ](https://huggingface.co/docs/inference-providers/en/pricing)ని చూడండి. + +## మాస్క్ ఫిల్లింగ్[[mask-filling]] + +మీరు ప్రయత్నించే తదుపరి పైప్‌లైన్ `fill-mask`. ఈ పని యొక్క ఆలోచన ఇచ్చిన టెక్స్ట్‌లోని ఖాళీలను పూరించడం: + +```python +from transformers import pipeline + +unmasker = pipeline("fill-mask") +unmasker("This course will teach you all about models.", top_k=2) +``` + +```python out +[{'sequence': 'This course will teach you all about mathematical models.', + 'score': 0.19619831442832947, + 'token': 30412, + 'token_str': ' mathematical'}, + {'sequence': 'This course will teach you all about computational models.', + 'score': 0.04052725434303284, + 'token': 38163, + 'token_str': ' computational'}] +``` + +`top_k` ఆర్గ్యుమెంట్ మీరు ఎన్ని అవకాశాలను ప్రదర్శించాలనుకుంటున్నారో నియంత్రిస్తుంది. ఇక్కడ మోడల్ ప్రత్యేక `` పదాన్ని నింపుతుందని గమనించండి, దీనిని తరచుగా _మాస్క్ టోకెన్_ అని అంటారు. ఇతర మాస్క్-ఫిల్లింగ్ మోడల్స్ వేర్వేరు మాస్క్ టోకెన్‌లను కలిగి ఉండవచ్చు, కాబట్టి ఇతర మోడల్స్‌ను అన్వేషించేటప్పుడు సరైన మాస్క్ పదాన్ని ధృవీకరించడం ఎల్లప్పుడూ మంచిది. దానిని తనిఖీ చేయడానికి ఒక మార్గం విడ్జెట్‌లో ఉపయోగించిన మాస్క్ పదాన్ని చూడటం. + + + +✏️ **ప్రయత్నించి చూడండి!** హబ్‌లో `bert-base-cased` మోడల్ కోసం శోధించి మరియు ఇన్ఫరెన్స్ API విడ్జెట్‌లో దాని మాస్క్ పదాన్ని గుర్తించండి. మా `pipeline` ఉదాహరణలోని వాక్యానికి ఈ మోడల్ ఏమి అంచనా వేస్తుంది? + + + +## నేమ్డ్ ఎంటిటీ రికగ్నిషన్[[named-entity-recognition]] + +నేమ్డ్ ఎంటిటీ రికగ్నిషన్ (NER) అనేది ఒక పని, ఇక్కడ మోడల్ ఇన్‌పుట్ టెక్స్ట్‌లోని ఏ భాగాలు వ్యక్తులు, ప్రదేశాలు లేదా సంస్థల వంటి ఎంటిటీలకు సంబంధించినవో కనుగొనాలి. ఒక ఉదాహరణ చూద్దాం: + +```python +from transformers import pipeline + +ner = pipeline("ner", grouped_entities=True) +ner("My name is Sylvain and I work at Hugging Face in Brooklyn.") +``` + +```python out +[{'entity_group': 'PER', 'score': 0.99816, 'word': 'Sylvain', 'start': 11, 'end': 18}, + {'entity_group': 'ORG', 'score': 0.97960, 'word': 'Hugging Face', 'start': 33, 'end': 45}, + {'entity_group': 'LOC', 'score': 0.99321, 'word': 'Brooklyn', 'start': 49, 'end': 57} +] +``` + +ఇక్కడ మోడల్ సిల్వైన్ ఒక వ్యక్తి (PER), Hugging Face ఒక సంస్థ (ORG), మరియు బ్రూక్లిన్ ఒక ప్రదేశం (LOC) అని సరిగ్గా గుర్తించింది. + +వాక్యంలోని ఒకే ఎంటిటీకి సంబంధించిన భాగాలను తిరిగి సమూహపరచమని పైప్‌లైన్‌కు చెప్పడానికి మేము పైప్‌లైన్ సృష్టి ఫంక్షన్‌లో `grouped_entities=True` ఎంపికను పాస్ చేస్తాము: ఇక్కడ మోడల్ "Hugging" మరియు "Face" ను ఒకే సంస్థగా సరిగ్గా సమూహపరిచింది, పేరు అనేక పదాలతో ఉన్నప్పటికీ. నిజానికి, మనం తదుపరి అధ్యాయంలో చూస్తాము, ప్రిప్రాసెసింగ్ కొన్ని పదాలను చిన్న భాగాలుగా కూడా విభజిస్తుంది. ఉదాహరణకు, `Sylvain` ను నాలుగు ముక్కలుగా విభజించారు: `S`, `##yl`, `##va`, మరియు `##in`. పోస్ట్-ప్రాసెసింగ్ దశలో, పైప్‌లైన్ ఆ ముక్కలను విజయవంతంగా తిరిగి సమూహపరిచింది. + + + +✏️ **ప్రయత్నించి చూడండి!** ఇంగ్లీషులో పార్ట్-ఆఫ్-స్పీచ్ ట్యాగింగ్ (సాధారణంగా POS అని సంక్షిప్తం) చేయగల మోడల్ కోసం మోడల్ హబ్‌ను శోధించండి. పై ఉదాహరణలోని వాక్యానికి ఈ మోడల్ ఏమి అంచనా వేస్తుంది? + + + +## ప్రశ్న సమాధానం[[question-answering]] + +`question-answering` పైప్‌లైన్ ఇచ్చిన సందర్భం నుండి సమాచారాన్ని ఉపయోగించి ప్రశ్నలకు సమాధానమిస్తుంది: + +```python +from transformers import pipeline + +question_answerer = pipeline("question-answering") +question_answerer( + question="Where do I work?", + context="My name is Sylvain and I work at Hugging Face in Brooklyn", +) +``` + +```python out +{'score': 0.6385916471481323, 'start': 33, 'end': 45, 'answer': 'Hugging Face'} +``` + +ఈ పైప్‌లైన్ అందించిన సందర్భం నుండి సమాచారాన్ని సంగ్రహించడం ద్వారా పనిచేస్తుందని గమనించండి; ఇది సమాధానాన్ని రూపొందించదు. + +## సారాంశీకరణ[[summarization]] + +సారాంశీకరణ అనేది టెక్స్ట్‌లో ప్రస్తావించిన అన్ని (లేదా చాలా) ముఖ్యమైన అంశాలను ఉంచుతూ టెక్స్ట్‌ను చిన్న టెక్స్ట్‌గా తగ్గించడం. ఇక్కడ ఒక ఉదాహరణ ఉంది: + +```python +from transformers import pipeline + +summarizer = pipeline("summarization") +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 + the premier American universities engineering curricula now concentrate on + and encourage largely the study of engineering science. As a result, there + are declining offerings in engineering subjects dealing with infrastructure, + the environment, and related issues, and greater concentration on high + technology subjects, largely supporting increasingly complex scientific + developments. While the latter is important, it should not be at the expense + of more traditional engineering. + + Rapidly developing economies such as China and India, as well as other + industrial countries in Europe and Asia, continue to encourage and advance + the teaching of engineering. Both China and India, respectively, graduate + six and eight times as many traditional engineers as does the United States. + 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 +[{'summary_text': ' America has changed dramatically during recent years . The ' + 'number of engineering graduates in the U.S. has declined in ' + 'traditional engineering disciplines such as mechanical, civil ' + ', electrical, chemical, and aeronautical engineering . Rapidly ' + 'developing economies such as China and India, as well as other ' + 'industrial countries in Europe and Asia, continue to encourage ' + 'and advance engineering .'}] +``` + +టెక్స్ట్ జనరేషన్ లాగే, మీరు ఫలితం కోసం `max_length` లేదా `min_length` ను నిర్దేశించవచ్చు. + +## అనువాదం[[translation]] + +అనువాదం కోసం, మీరు టాస్క్ పేరులో ఒక భాషా జతను (ఉదాహరణకు `"translation_en_to_fr"`) అందిస్తే డిఫాల్ట్ మోడల్‌ను ఉపయోగించవచ్చు, కానీ సులభమైన మార్గం మీరు [మోడల్ హబ్](https://huggingface.co/models) లో ఉపయోగించాలనుకుంటున్న మోడల్‌ను ఎంచుకోవడం. ఇక్కడ మేము ఫ్రెంచ్ నుండి ఇంగ్లీష్‌లోకి అనువదించడానికి ప్రయత్నిస్తాము: + +```python +from transformers import pipeline + +translator = pipeline("translation", model="Helsinki-NLP/opus-mt-fr-en") +translator("Ce cours est produit par Hugging Face.") +``` + +```python out +[{'translation_text': 'This course is produced by Hugging Face.'}] +``` + +టెక్స్ట్ జనరేషన్ మరియు సారాంశీకరణ లాగే, మీరు ఫలితం కోసం `max_length` లేదా `min_length` ను నిర్దేశించవచ్చు. + + + +✏️ **ప్రయత్నించి చూడండి!** ఇతర భాషలలో అనువాద మోడల్స్ కోసం శోధించి, మునుపటి వాక్యాన్ని కొన్ని వేర్వేరు భాషలలోకి అనువదించడానికి ప్రయత్నించండి. + + + +## ఇమేజ్ మరియు ఆడియో పైప్‌లైన్‌లు + +టెక్స్ట్‌తో పాటు, Transformer మోడల్స్ ఇమేజ్‌లు మరియు ఆడియోతో కూడా పనిచేయగలవు. ఇక్కడ కొన్ని ఉదాహరణలు ఉన్నాయి: + +### ఇమేజ్ వర్గీకరణ + +```python +from transformers import pipeline + +image_classifier = pipeline( + task="image-classification", model="google/vit-base-patch16-224" +) +result = image_classifier( + "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +) +print(result) +``` + +```python out +[{'label': 'lynx, catamount', 'score': 0.43350091576576233}, + {'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor', + 'score': 0.034796204417943954}, + {'label': 'snow leopard, ounce, Panthera uncia', + 'score': 0.03240183740854263}, + {'label': 'Egyptian cat', 'score': 0.02394474856555462}, + {'label': 'tiger cat', 'score': 0.02288915030658245}] +``` + +### ఆటోమేటిక్ స్పీచ్ రికగ్నిషన్ + +```python +from transformers import pipeline + +transcriber = pipeline( + task="automatic-speech-recognition", model="openai/whisper-large-v3" +) +result = transcriber( + "https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac" +) +print(result) +``` + +```python out +{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'} +``` + +## బహుళ మూలాల నుండి డేటాను కలపడం + +Transformer మోడల్స్ యొక్క ఒక శక్తివంతమైన అప్లికేషన్ వాటికి బహుళ మూలాల నుండి డేటాను కలపడం మరియు ప్రాసెస్ చేసే సామర్థ్యం. ఇది మీకు అవసరమైనప్పుడు ప్రత్యేకంగా ఉపయోగపడుతుంది: + +1. బహుళ డేటాబేస్‌లు లేదా రిపోజిటరీలలో శోధించడం +2. విభిన్న ఫార్మాట్ల నుండి సమాచారాన్ని ఏకీకృతం చేయడం (టెక్స్ట్, చిత్రాలు, ఆడియో) +3. సంబంధిత సమాచారం యొక్క ఏకీకృత వీక్షణను సృష్టించడం + +ఉదాహరణకు, మీరు ఒక సిస్టమ్‌ను నిర్మించవచ్చు: + +- టెక్స్ట్ మరియు ఇమేజ్ వంటి బహుళ మాధ్యమాలలో డేటాబేస్‌లలో సమాచారం కోసం శోధించడం. +- విభిన్న మూలాల నుండి ఫలితాలను ఒకే పొందికైన ప్రతిస్పందనగా కలపడం. ఉదాహరణకు, ఒక ఆడియో ఫైల్ మరియు టెక్స్ట్ వివరణ నుండి. +- పత్రాలు మరియు మెటాడేటా యొక్క డేటాబేస్ నుండి అత్యంత సంబంధిత సమాచారాన్ని ప్రదర్శించడం. + +## ముగింపు + +ఈ అధ్యాయంలో చూపిన పైప్‌లైన్‌లు చాలావరకు ప్రదర్శన ప్రయోజనాల కోసం. అవి నిర్దిష్ట పనుల కోసం ప్రోగ్రామ్ చేయబడ్డాయి మరియు వాటి వైవిధ్యాలను నిర్వహించలేవు. తదుపరి అధ్యాయంలో, మీరు `pipeline()` ఫంక్షన్ లోపల ఏమి ఉందో మరియు దాని ప్రవర్తనను ఎలా అనుకూలీకరించాలో నేర్చుకుంటారు. From 26fe94b196f91c4acd6e937a8f2b42171a21c6d5 Mon Sep 17 00:00:00 2001 From: Rahul Konda Date: Tue, 24 Jun 2025 05:51:16 +0530 Subject: [PATCH 07/43] Update 2.mdx Removed heading [[llms-and-their-limitations]] --- chapters/te/chapter1/2.mdx | 2 -- 1 file changed, 2 deletions(-) diff --git a/chapters/te/chapter1/2.mdx b/chapters/te/chapter1/2.mdx index fa7996c5d..ab759edbc 100644 --- a/chapters/te/chapter1/2.mdx +++ b/chapters/te/chapter1/2.mdx @@ -39,8 +39,6 @@ LLMలు వీటి ద్వారా వర్గీకరించబడ LLMల ఉద్భవం, ప్రత్యేక NLP పనుల కోసం ప్రత్యేక మోడల్స్‌ను నిర్మించడంనుంచి, విస్తృత శ్రేణా భాషా పనులను పరిష్కరించడానికి ప్రాంప్ట్ చేయబడిన లేదా ఫైన్-ట్యూన్ చేయబడిన ఒక పెద్ద మోడల్‌ను ఉపయోగించడం వరకు మార్పు తీసుకువచ్చింది. ఇది సాంకేతిక భాషా ప్రాసెసింగ్‌ను మరింత అందుబాటులోకి తెచ్చింది, కానీ సమర్థత, నైతికత మరియు అమలు వంటి కొత్త సవాళ్లను కూడా పరిచయం చేసింది. -## LLMలు మరియు వాటి పరిమితులు[[llms-and-their-limitations]] - LLMలు కూడా ముఖ్యమైన పరిమితులను కలిగి ఉంటాయి: - **హాల్యూసినేషన్స్**: అవి తప్పు సమాచారాన్ని నమ్మకంగా ఉత్పత్తి చేయగలవు From 1bf51f27708123bc638a11d26d4d95e04b463080 Mon Sep 17 00:00:00 2001 From: sergiopaniego Date: Wed, 9 Jul 2025 10:45:22 +0200 Subject: [PATCH 08/43] Updated .bin to .safetensors --- chapters/rum/chapter2/3.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chapters/rum/chapter2/3.mdx b/chapters/rum/chapter2/3.mdx index 27407ca22..e3fd06989 100644 --- a/chapters/rum/chapter2/3.mdx +++ b/chapters/rum/chapter2/3.mdx @@ -162,7 +162,7 @@ Se salvează două fișiere pe disc: ``` ls directory_on_my_computer -config.json pytorch_model.bin +config.json pytorch_model.safetensors ``` {:else} ``` @@ -176,7 +176,7 @@ Dacă aruncați o privire la fișierul *config.json*, veți recunoaște atribute {#if fw === 'pt'} -Fișierul *pytorch_model.bin* este cunoscut sub numele de *state dictionary*; acesta conține toate weight-urile modelului dumneavoastră. Cele două fișiere merg mână în mână; configurația este necesară pentru a cunoaște arhitectura modelului, în timp ce weight-urile modelului sunt parametrii modelului. +Fișierul *pytorch_model.safetensors* este cunoscut sub numele de *state dictionary*; acesta conține toate weight-urile modelului dumneavoastră. Cele două fișiere merg mână în mână; configurația este necesară pentru a cunoaște arhitectura modelului, în timp ce weight-urile modelului sunt parametrii modelului. {:else} From 86511e43cd43e3658a3c292206d3c66a42debbd0 Mon Sep 17 00:00:00 2001 From: Rahul Konda Date: Sat, 12 Jul 2025 09:30:55 +0530 Subject: [PATCH 09/43] added te/chapter1/4-11 --- README.md | 2 +- chapters/te/_toctree.yml | 17 ++ chapters/te/chapter1/10.mdx | 71 +++++++++ chapters/te/chapter1/11.mdx | 20 +++ chapters/te/chapter1/4.mdx | 188 ++++++++++++++++++++++ chapters/te/chapter1/5.mdx | 270 ++++++++++++++++++++++++++++++++ chapters/te/chapter1/6.mdx | 206 ++++++++++++++++++++++++ chapters/te/chapter1/7.mdx | 283 +++++++++++++++++++++++++++++++++ chapters/te/chapter1/8.mdx | 303 ++++++++++++++++++++++++++++++++++++ chapters/te/chapter1/9.mdx | 42 +++++ 10 files changed, 1401 insertions(+), 1 deletion(-) create mode 100644 chapters/te/chapter1/10.mdx create mode 100644 chapters/te/chapter1/11.mdx create mode 100644 chapters/te/chapter1/4.mdx create mode 100644 chapters/te/chapter1/5.mdx create mode 100644 chapters/te/chapter1/6.mdx create mode 100644 chapters/te/chapter1/7.mdx create mode 100644 chapters/te/chapter1/8.mdx create mode 100644 chapters/te/chapter1/9.mdx diff --git a/README.md b/README.md index dbb302dcc..5216eba06 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ This repo contains the content that's used to create the **[Hugging Face course] | [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) +| [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) | diff --git a/chapters/te/_toctree.yml b/chapters/te/_toctree.yml index 0afdb7624..301decc44 100644 --- a/chapters/te/_toctree.yml +++ b/chapters/te/_toctree.yml @@ -10,3 +10,20 @@ title: Natural Language Processing (NLP) మరియు Large Language Models (LLMs) - local: chapter1/3 title: ట్రాన్స్‌ఫార్మర్‌లు, అవి ఏమి చేయగలవు? + - local: chapter1/4 + title: ట్రాన్స్‌ఫార్మర్‌లు ఎలా పని చేస్తాయి? + - local: chapter1/5 + title: 🤗 ట్రాన్స్‌ఫార్మర్‌లు పనులను ఎలా పరిష్కరిస్తాయి + - local: chapter1/6 + title: ట్రాన్స్‌ఫార్మర్ ఆర్కిటెక్చర్‌లు + - local: chapter1/7 + title: క్విజ్ + - local: chapter1/8 + title: LLMలతో పనులు చేయడం + - local: chapter1/9 + title: పక్షపాతం మరియు పరిమితులు + - local: chapter1/10 + title: సారాంశం + - local: chapter1/11 + title: పరీక్ష + quiz: 1 \ No newline at end of file diff --git a/chapters/te/chapter1/10.mdx b/chapters/te/chapter1/10.mdx new file mode 100644 index 000000000..173671679 --- /dev/null +++ b/chapters/te/chapter1/10.mdx @@ -0,0 +1,71 @@ +# సారాంశం[[summary]] + + + +ఈ అధ్యాయంలో, మీరు Transformer నమూనాలు, Large Language Models (LLMs) యొక్క ప్రాథమిక అంశాలకు పరిచయం చేయబడ్డారు, మరియు అవి AI మరియు అంతకు మించి ఎలా విప్లవాత్మకంగా మారుస్తున్నాయో తెలుసుకున్నారు. + +## చర్చించిన ముఖ్యమైన అంశాలు + +### Natural Language Processing మరియు LLMs + +NLP అంటే ఏమిటి మరియు Large Language Models ఈ రంగాన్ని ఎలా మార్చాయో మేము అన్వేషించాము. మీరు నేర్చుకున్నవి: + +- NLP వర్గీకరణ నుండి జనరేషన్ వరకు విస్తృత శ్రేణి పనులను కలిగి ఉంటుంది +- LLMs అనేవి భారీ మొత్తంలో టెక్స్ట్ డేటాపై శిక్షణ పొందిన శక్తివంతమైన నమూనాలు +- ఈ నమూనాలు ఒకే ఆర్కిటెక్చర్‌లో బహుళ పనులను చేయగలవు +- వాటి సామర్థ్యాలు ఉన్నప్పటికీ, LLMs కు భ్రాంతులు మరియు పక్షపాతం వంటి పరిమితులు ఉన్నాయి + +### Transformer సామర్థ్యాలు + +🤗 Transformers నుండి `pipeline()` ఫంక్షన్ వివిధ పనుల కోసం ముందుగా శిక్షణ పొందిన నమూనాలను ఉపయోగించడాన్ని ఎలా సులభతరం చేస్తుందో మీరు చూశారు: + +- టెక్స్ట్ వర్గీకరణ, టోకెన్ వర్గీకరణ, మరియు ప్రశ్న సమాధానం +- టెక్స్ట్ జనరేషన్ మరియు సారాంశం +- అనువాదం మరియు ఇతర సీక్వెన్స్-టు-సీక్వెన్స్ పనులు +- ప్రసంగ గుర్తింపు మరియు చిత్ర వర్గీకరణ + +### Transformer ఆర్కిటెక్చర్ + +Transformer నమూనాలు ఉన్నత స్థాయిలో ఎలా పనిచేస్తాయో మేము చర్చించాము, వీటితో సహా: + +- అటెన్షన్ మెకానిజం యొక్క ప్రాముఖ్యత +- ట్రాన్స్‌ఫర్ లెర్నింగ్ నమూనాలను నిర్దిష్ట పనులకు అనుగుణంగా మార్చడానికి ఎలా వీలు కల్పిస్తుంది +- మూడు ప్రధాన ఆర్కిటెక్చరల్ వేరియంట్‌లు: ఎన్‌కోడర్-మాత్రమే, డీకోడర్-మాత్రమే, మరియు ఎన్‌కోడర్-డీకోడర్ + +### మోడల్ ఆర్కిటెక్చర్‌లు మరియు వాటి అనువర్తనాలు + +ఈ అధ్యాయంలోని ఒక ముఖ్యమైన అంశం ఏమిటంటే, వివిధ పనుల కోసం ఏ ఆర్కిటెక్చర్‌ను ఉపయోగించాలో అర్థం చేసుకోవడం: + +| మోడల్ | ఉదాహరణలు | పనులు | +| ----------------- | ---------------------------- | ----------------------------------------------------------------------------- | +| ఎన్‌కోడర్-మాత్రమే | BERT, DistilBERT, ModernBERT | వాక్య వర్గీకరణ, నేమ్డ్ ఎంటిటీ రికగ్నిషన్, ఎక్స్‌ట్రాక్టివ్ క్వశ్చన్ ఆన్సరింగ్ | +| డీకోడర్-మాత్రమే | GPT, LLaMA, Gemma, SmolLM | టెక్స్ట్ జనరేషన్, సంభాషణ AI, సృజనాత్మక రచన | +| ఎన్‌కోడర్-డీకోడర్ | BART, T5, Marian, mBART | సారాంశం, అనువాదం, జెనరేటివ్ క్వశ్చన్ ఆన్సరింగ్ | + +### ఆధునిక LLM అభివృద్ధిలు + +ఈ రంగంలో ఇటీవలి పరిణామాల గురించి కూడా మీరు తెలుసుకున్నారు: + +- కాలక్రమేణా LLMs పరిమాణంలో మరియు సామర్థ్యంలో ఎలా పెరిగాయి +- స్కేలింగ్ చట్టాల భావన మరియు అవి మోడల్ అభివృద్ధికి ఎలా మార్గనిర్దేశం చేస్తాయి +- పొడవైన సీక్వెన్స్‌లను ప్రాసెస్ చేయడానికి మోడళ్లకు సహాయపడే ప్రత్యేక అటెన్షన్ మెకానిజమ్స్ +- ప్రీట్రైనింగ్ మరియు ఇన్‌స్ట్రక్షన్ ట్యూనింగ్ యొక్క రెండు-దశల శిక్షణ విధానం + +### ఆచరణాత్మక అనువర్తనాలు + +అధ్యాయం అంతటా, ఈ నమూనాలను వాస్తవ-ప్రపంచ సమస్యలకు ఎలా వర్తింపజేయవచ్చో మీరు చూశారు: + +- ముందుగా శిక్షణ పొందిన నమూనాలను కనుగొని ఉపయోగించడానికి Hugging Face Hub ను ఉపయోగించడం +- మీ బ్రౌజర్‌లో నేరుగా నమూనాలను పరీక్షించడానికి Inference API ని ఉపయోగించడం +- నిర్దిష్ట పనులకు ఏ నమూనాలు ఉత్తమంగా సరిపోతాయో అర్థం చేసుకోవడం + +## భవిష్యత్తు ప్రణాళిక + +Transformer నమూనాలు అంటే ఏమిటి మరియు అవి ఉన్నత స్థాయిలో ఎలా పనిచేస్తాయో ఇప్పుడు మీకు దృఢమైన అవగాహన ఉంది కాబట్టి, వాటిని సమర్థవంతంగా ఎలా ఉపయోగించాలో లోతుగా పరిశోధించడానికి మీరు సిద్ధంగా ఉన్నారు. తదుపరి అధ్యాయాలలో, మీరు ఎలా చేయాలో నేర్చుకుంటారు: + +- నమూనాలను లోడ్ చేయడానికి మరియు ఫైన్-ట్యూన్ చేయడానికి Transformers లైబ్రరీని ఉపయోగించడం +- మోడల్ ఇన్‌పుట్ కోసం వివిధ రకాల డేటాను ప్రాసెస్ చేయడం +- మీ నిర్దిష్ట పనులకు ముందుగా శిక్షణ పొందిన నమూనాలను అనుకూలీకరించడం +- ఆచరణాత్మక అనువర్తనాల కోసం నమూనాలను అమలు చేయడం + +ఈ అధ్యాయంలో మీరు నిర్మించుకున్న పునాది, రాబోయే విభాగాలలో మీరు మరింత ఆధునిక అంశాలు మరియు పద్ధతులను అన్వేషించేటప్పుడు మీకు బాగా ఉపయోగపడుతుంది. diff --git a/chapters/te/chapter1/11.mdx b/chapters/te/chapter1/11.mdx new file mode 100644 index 000000000..2f5d7ba12 --- /dev/null +++ b/chapters/te/chapter1/11.mdx @@ -0,0 +1,20 @@ +# పరీక్షా సమయం! + +మీ జ్ఞానాన్ని పరీక్షించుకునే సమయం ఆసన్నమైంది! ఈ అధ్యాయంలో చర్చించిన అంశాలపై మీ అవగాహనను పరీక్షించడానికి మేము మీ కోసం ఒక చిన్న క్విజ్‌ను సిద్ధం చేసాము. + +క్విజ్ తీసుకోవడానికి, మీరు ఈ దశలను అనుసరించాలి: + +1. మీ Hugging Face ఖాతాకు సైన్ ఇన్ చేయండి. +2. క్విజ్‌లోని ప్రశ్నలకు సమాధానం ఇవ్వండి. +3. మీ సమాధానాలను సమర్పించండి. + +## మల్టిపుల్ ఛాయిస్ క్విజ్ + +ఈ క్విజ్‌లో, మీరు ఎంపికల జాబితా నుండి సరైన సమాధానాన్ని ఎంచుకోవాలి. పర్యవేక్షించబడిన ఫైన్‌ట్యూనింగ్ యొక్క ప్రాథమిక అంశాలపై మేము మిమ్మల్ని పరీక్షిస్తాము. + + diff --git a/chapters/te/chapter1/4.mdx b/chapters/te/chapter1/4.mdx new file mode 100644 index 000000000..f4f12f2aa --- /dev/null +++ b/chapters/te/chapter1/4.mdx @@ -0,0 +1,188 @@ +# Transformerలు ఎలా పనిచేస్తాయి?[[how-do-transformers-work]] + + + +ఈ విభాగంలో, మనం Transformer మోడల్స్ యొక్క ఆర్కిటెక్చర్‌ను పరిశీలిద్దాం మరియు అటెన్షన్, ఎన్‌కోడర్-డీకోడర్ ఆర్కిటెక్చర్ వంటి భావనలను లోతుగా చర్చిద్దాం. + + + +🚀 ఇక్కడ మనం విషయాలను మరింత లోతుగా తెలుసుకుంటున్నాం. ఈ విభాగం వివరంగా మరియు సాంకేతికంగా ఉంటుంది, కాబట్టి మీరు వెంటనే అన్నింటినీ అర్థం చేసుకోకపోయినా చింతించకండి. కోర్సులో తరువాత ఈ భావనల వద్దకు మనం తిరిగి వస్తాము. + + + +## Transformerల చరిత్ర గురించి కొంచెం[[a-bit-of-transformer-history]] + +Transformer మోడల్స్ యొక్క (సంక్షిప్త) చరిత్రలో కొన్ని ముఖ్యమైన ఘట్టాలు ఇక్కడ ఉన్నాయి: + +
+A brief chronology of Transformers models. + +
+ +[Transformer ఆర్కిటెక్చర్](https://arxiv.org/abs/1706.03762) జూన్ 2017లో పరిచయం చేయబడింది. అసలు పరిశోధన యొక్క ముఖ్య ఉద్దేశ్యం అనువాద పనులపై ఉండేది. దీని తర్వాత అనేక ప్రభావవంతమైన మోడల్స్ వచ్చాయి, వాటిలో కొన్ని: + +- **జూన్ 2018**: [GPT](https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf), మొదటి ప్రీ-ట్రైన్డ్ Transformer మోడల్. ఇది వివిధ NLP పనులపై ఫైన్-ట్యూనింగ్ కోసం ఉపయోగించబడింది మరియు అత్యుత్తమ ఫలితాలను సాధించింది. + +- **అక్టోబర్ 2018**: [BERT](https://arxiv.org/abs/1810.04805), మరొక పెద్ద ప్రీ-ట్రైన్డ్ మోడల్. ఇది వాక్యాల యొక్క మెరుగైన సారాంశాలను ఉత్పత్తి చేయడానికి రూపొందించబడింది (దీని గురించి తదుపరి అధ్యాయంలో మరింత!) + +- **ఫిబ్రవరి 2019**: [GPT-2](https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf), GPT యొక్క మెరుగైన (మరియు పెద్ద) వెర్షన్, ఇది నైతిక ఆందోళనల కారణంగా వెంటనే బహిరంగంగా విడుదల కాలేదు. + +- **అక్టోబర్ 2019**: [T5](https://huggingface.co/papers/1910.10683), సీక్వెన్స్-టు-సీక్వెన్స్ Transformer ఆర్కిటెక్చర్ యొక్క బహుళ-పని ఆధారిత అమలు. + +- **మే 2020**, [GPT-3](https://huggingface.co/papers/2005.14165), GPT-2 యొక్క మరింత పెద్ద వెర్షన్. ఇది ఫైన్-ట్యూనింగ్ అవసరం లేకుండా వివిధ పనులపై బాగా పనిచేయగలదు (_zero-shot learning_ అని పిలుస్తారు). + +- **జనవరి 2022**: [InstructGPT](https://huggingface.co/papers/2203.02155), సూచనలను మరింత మెరుగ్గా పాటించడానికి శిక్షణ పొందిన GPT-3 యొక్క వెర్షన్. + +- **జనవరి 2023**: [Llama](https://huggingface.co/papers/2302.13971), వివిధ భాషలలో టెక్స్ట్‌ను ఉత్పత్తి చేయగల ఒక పెద్ద భాషా నమూనా. + +- **మార్చి 2023**: [Mistral](https://huggingface.co/papers/2310.06825), 7-బిలియన్-పారామీటర్ల భాషా నమూనా, ఇది అన్ని మూల్యాంకన బెంచ్‌మార్క్‌లలో Llama 2 13B ను అధిగమించింది. వేగవంతమైన ఇన్ఫరెన్స్ కోసం గ్రూప్డ్-క్వరీ అటెన్షన్ మరియు ఏకపక్ష పొడవు గల సీక్వెన్సులను నిర్వహించడానికి స్లైడింగ్ విండో అటెన్షన్‌ను ఉపయోగిస్తుంది. + +- **మే 2024**: [Gemma 2](https://huggingface.co/papers/2408.00118), 2B నుండి 27B పారామీటర్ల వరకు ఉండే తేలికపాటి, అత్యాధునిక ఓపెన్ మోడల్స్ యొక్క కుటుంబం. ఇవి ఇంటర్లీవ్డ్ లోకల్-గ్లోబల్ అటెన్షన్స్ మరియు గ్రూప్-క్వరీ అటెన్షన్‌ను కలిగి ఉంటాయి, మరియు 2-3 రెట్లు పెద్ద మోడల్స్‌తో పోటీపడే పనితీరును అందించడానికి నాలెడ్జ్ డిస్టిలేషన్ ఉపయోగించి చిన్న మోడల్స్‌కు శిక్షణ ఇవ్వబడింది. + +- **నవంబర్ 2024**: [SmolLM2](https://huggingface.co/papers/2502.02737), అత్యాధునిక చిన్న భాషా నమూనా (135 మిలియన్ల నుండి 1.7 బిలియన్ల పారామీటర్లు), ఇది దాని కాంపాక్ట్ సైజు ఉన్నప్పటికీ ఆకట్టుకునే పనితీరును సాధిస్తుంది మరియు మొబైల్ మరియు ఎడ్జ్ పరికరాల కోసం కొత్త అవకాశాలను అన్‌లాక్ చేస్తుంది. + +ఈ జాబితా పూర్తి కాదు మరియు ఇది కేవలం కొన్ని రకాల Transformer నమూనాలను హైలైట్ చేయడానికి మాత్రమే ఉద్దేశించబడింది. విస్తృతంగా, వీటిని మూడు వర్గాలుగా విభజించవచ్చు: + +- GPT-లాంటి (వీటిని _auto-regressive_ Transformer మోడల్స్ అని కూడా అంటారు) +- BERT-లాంటి (వీటిని _auto-encoding_ Transformer మోడల్స్ అని కూడా అంటారు) +- T5-లాంటి (వీటిని _sequence-to-sequence_ Transformer మోడల్స్ అని కూడా అంటారు) + +మనం ఈ కుటుంబాల గురించి తరువాత మరింత లోతుగా చర్చిస్తాము. + +## Transformer లు భాషా నమూనాలు[[transformers-are-language-models]] + +పైన పేర్కొన్న అన్ని Transformer మోడల్స్ (GPT, BERT, T5, మొదలైనవి) _భాషా నమూనాలుగా_ శిక్షణ పొందాయి. అంటే అవి స్వీయ-పర్యవేక్షిత పద్ధతిలో భారీ మొత్తంలో ముడి టెక్స్ట్‌పై శిక్షణ పొందాయి. + +స్వీయ-పర్యవేక్షిత అభ్యాసం (Self-supervised learning) అనేది ఒక రకమైన శిక్షణ, దీనిలో మోడల్ యొక్క ఇన్‌పుట్‌ల నుండి లక్ష్యం స్వయంచాలకంగా లెక్కించబడుతుంది. అంటే డేటాను లేబుల్ చేయడానికి మానవులు అవసరం లేదు! + +ఈ రకమైన మోడల్, శిక్షణ పొందిన భాషపై గణాంక అవగాహనను పెంచుకుంటుంది, కానీ ఇది నిర్దిష్ట ఆచరణాత్మక పనులకు అంతగా ఉపయోగపడదు. ఈ కారణంగా, సాధారణ ప్రీ-ట్రైన్డ్ మోడల్ తరువాత _ట్రాన్స్‌ఫర్ లెర్నింగ్_ లేదా _ఫైన్-ట్యూనింగ్_ అనే ప్రక్రియ ద్వారా వెళుతుంది. ఈ ప్రక్రియలో, మోడల్ ఒక నిర్దిష్ట పనిపై పర్యవేక్షిత పద్ధతిలో — అంటే, మానవ-అన్నొటేటెడ్ లేబుల్స్ ఉపయోగించి — ఫైన్-ట్యూన్ చేయబడుతుంది. + +ఒక పనికి ఉదాహరణ, ఒక వాక్యం లోని _n_ మునుపటి పదాలను చదివిన తరువాత తదుపరి పదాన్ని అంచనా వేయడం. దీనిని _కాజువల్ లాంగ్వేజ్ మోడలింగ్_ అని అంటారు, ఎందుకంటే అవుట్‌పుట్ గతం మరియు ప్రస్తుత ఇన్‌పుట్‌లపై ఆధారపడి ఉంటుంది, కానీ భవిష్యత్తు వాటిపై కాదు. + +
+Example of causal language modeling in which the next word from a sentence is predicted. + +
+ +మరొక ఉదాహరణ _Masked language modelling_, దీనిలో మోడల్ వాక్యంలోని మాస్క్ చేయబడిన పదాన్ని అంచనా వేస్తుంది. + +
+Example of masked language modeling in which a masked word from a sentence is predicted. + +
+ +## Transformerలు పెద్ద నమూనాలు[[transformers-are-big-models]] + +కొన్ని మినహాయింపులు (DistilBERT వంటివి) తప్ప, మెరుగైన పనితీరును సాధించడానికి సాధారణ వ్యూహం, మోడల్స్ యొక్క పరిమాణాలను అలాగే అవి ప్రీ-ట్రైనింగ్ చేయబడిన డేటా మొత్తాన్ని పెంచడం. + +
+Number of parameters of recent Transformers models +
+ +దురదృష్టవశాత్తు, ఒక మోడల్‌ను, ముఖ్యంగా పెద్ద మోడల్‌ను శిక్షణ ఇవ్వడానికి, పెద్ద మొత్తంలో డేటా అవసరం. సమయం మరియు గణన వనరుల పరంగా ఇది చాలా ఖర్చుతో కూడుకున్నది. ఇది పర్యావరణ ప్రభావానికి కూడా దారితీస్తుంది, కింది గ్రాఫ్‌లో చూడవచ్చు. + +
+The carbon footprint of a large language model. + +
+ + + +మరియు ఇది ప్రీ-ట్రైనింగ్ యొక్క పర్యావరణ ప్రభావాన్ని తగ్గించడానికి స్పృహతో ప్రయత్నిస్తున్న ఒక బృందం నేతృత్వంలోని ఒక (చాలా పెద్ద) మోడల్ కోసం ఒక ప్రాజెక్ట్‌ను చూపుతోంది. ఉత్తమ హైపర్‌పారామీటర్‌లను పొందడానికి చాలా ట్రయల్స్ నడపడం యొక్క ఫుట్‌ప్రింట్ ఇంకా ఎక్కువగా ఉంటుంది. + +ఒక పరిశోధన బృందం, ఒక విద్యార్థి సంస్థ, లేదా ఒక సంస్థ ప్రతిసారీ ఒక మోడల్‌ను శిక్షణ ఇవ్వాలనుకుంటే, అది మొదటి నుండి అలా చేస్తే ఎలా ఉంటుందో ఊహించండి. ఇది భారీ, అనవసరమైన ప్రపంచ వ్యయాలకు దారితీస్తుంది! + +అందుకే భాషా నమూనాలను పంచుకోవడం చాలా ముఖ్యం: శిక్షణ పొందిన వెయిట్స్ పంచుకోవడం మరియు ఇప్పటికే శిక్షణ పొందిన వెయిట్స్ పైన నిర్మించడం ద్వారా కమ్యూనిటీ యొక్క మొత్తం గణన వ్యయాన్ని మరియు కార్బన్ ఫుట్‌ప్రింట్‌ను తగ్గిస్తుంది. + +అలాగే, మీరు మీ మోడల్స్ శిక్షణ యొక్క కార్బన్ ఫుట్‌ప్రింట్‌ను అనేక సాధనాల ద్వారా మూల్యాంకనం చేయవచ్చు. ఉదాహరణకు [ML CO2 Impact](https://mlco2.github.io/impact/) లేదా [Code Carbon](https://codecarbon.io/) ఇది 🤗 Transformers లో విలీనం చేయబడింది. దీని గురించి మరింత తెలుసుకోవడానికి, మీరు ఈ [బ్లాగ్ పోస్ట్](https://huggingface.co/blog/carbon-emissions-on-the-hub) చదవచ్చు, ఇది మీ శిక్షణ యొక్క ఫుట్‌ప్రింట్ యొక్క అంచనాతో `emissions.csv` ఫైల్‌ను ఎలా రూపొందించాలో చూపుతుంది, అలాగే ఈ అంశాన్ని పరిష్కరించే 🤗 Transformers యొక్క [డాక్యుమెంటేషన్](https://huggingface.co/docs/hub/model-cards-co2) కూడా చూడవచ్చు. + +## ట్రాన్స్‌ఫర్ లెర్నింగ్[[transfer-learning]] + + + +_Pretraining_ అంటే ఒక మోడల్‌ను మొదటి నుండి శిక్షణ ఇవ్వడం: వెయిట్స్ యాదృచ్ఛికంగా ప్రారంభించబడతాయి మరియు శిక్షణ ఎటువంటి ముందస్తు జ్ఞానం లేకుండా మొదలవుతుంది. + +
+The pretraining of a language model is costly in both time and money. + +
+ +ఈ ప్రీ-ట్రైనింగ్ సాధారణంగా చాలా పెద్ద మొత్తంలో డేటాపై జరుగుతుంది. అందువల్ల, దీనికి చాలా పెద్ద డేటా కార్పస్ అవసరం, మరియు శిక్షణ పూర్తి కావడానికి చాలా వారాలు పట్టవచ్చు. + +_Fine-tuning_ అనేది, ఒక మోడల్ ప్రీ-ట్రైనింగ్ చేయబడిన **తరువాత** జరిగే శిక్షణ. ఫైన్-ట్యూనింగ్ చేయడానికి, మీరు మొదట ఒక ప్రీ-ట్రైన్డ్ భాషా నమూనాను పొందుతారు, ఆపై మీ పనికి సంబంధించిన నిర్దిష్ట డేటాసెట్‌తో అదనపు శిక్షణ ఇస్తారు. ఒక్క నిమిషం -- మీ తుది వినియోగం కోసం మోడల్‌ను మొదటి నుండి (**scratch**) ఎందుకు శిక్షణ ఇవ్వకూడదు? దీనికి కొన్ని కారణాలు ఉన్నాయి: + +- ప్రీ-ట్రైన్డ్ మోడల్ ఇప్పటికే ఫైన్-ట్యూనింగ్ డేటాసెట్‌తో కొన్ని సారూప్యతలను కలిగి ఉన్న డేటాసెట్‌పై శిక్షణ పొందింది. అందువల్ల ఫైన్-ట్యూనింగ్ ప్రక్రియ ప్రీ-ట్రైనింగ్ సమయంలో ప్రారంభ మోడల్ పొందిన జ్ఞానాన్ని ఉపయోగించుకోగలదు (ఉదాహరణకు, NLP సమస్యలతో, ప్రీ-ట్రైన్డ్ మోడల్ మీ పని కోసం మీరు ఉపయోగిస్తున్న భాషపై ఒకరకమైన గణాంక అవగాహనను కలిగి ఉంటుంది). +- ప్రీ-ట్రైన్డ్ మోడల్ ఇప్పటికే చాలా డేటాపై శిక్షణ పొందింది కాబట్టి, ఫైన్-ట్యూనింగ్‌కు మంచి ఫలితాలను పొందడానికి చాలా తక్కువ డేటా అవసరం. +- అదే కారణంతో, మంచి ఫలితాలను పొందడానికి అవసరమైన సమయం మరియు వనరులు చాలా తక్కువ. + +ఉదాహరణకు, ఇంగ్లీష్ భాషపై శిక్షణ పొందిన ఒక ప్రీ-ట్రైన్డ్ మోడల్‌ను ఉపయోగించి, ఆ తర్వాత దాన్ని ఒక arXiv కార్పస్‌పై ఫైన్-ట్యూన్ చేయడం ద్వారా ఒక సైన్స్/పరిశోధన ఆధారిత మోడల్‌ను పొందవచ్చు. ఫైన్-ట్యూనింగ్‌కు పరిమిత మొత్తంలో డేటా మాత్రమే అవసరం: ప్రీ-ట్రైన్డ్ మోడల్ పొందిన జ్ఞానం "బదిలీ" చేయబడుతుంది, అందుకే _ట్రాన్స్‌ఫర్ లెర్నింగ్_ అనే పదం వచ్చింది. + +
+The fine-tuning of a language model is cheaper than pretraining in both time and money. + +
+ +అందువల్ల, ఒక మోడల్‌ను ఫైన్-ట్యూన్ చేయడం తక్కువ సమయం, డేటా, ఆర్థిక, మరియు పర్యావరణ వ్యయాలను కలిగి ఉంటుంది. పూర్తి ప్రీ-ట్రైనింగ్ కంటే శిక్షణ తక్కువ నిర్బంధంగా ఉన్నందున, వివిధ ఫైన్-ట్యూనింగ్ స్కీమ్‌లను పునరావృతం చేయడం కూడా వేగంగా మరియు సులభంగా ఉంటుంది. + +ఈ ప్రక్రియ సున్నా నుండి శిక్షణ ఇవ్వడం కంటే మెరుగైన ఫలితాలను సాధిస్తుంది (మీరు చాలా డేటాను కలిగి ఉంటే తప్ప), అందుకే మీరు ఎల్లప్పుడూ ఒక ప్రీ-ట్రైన్డ్ మోడల్‌ను ఉపయోగించుకోవడానికి ప్రయత్నించాలి -- మీ చేతిలో ఉన్న పనికి వీలైనంత దగ్గరగా ఉన్న దాన్ని — మరియు దానిని ఫైన్-ట్యూన్ చేయాలి. + +## సాధారణ Transformer ఆర్కిటెక్చర్[[general-transformer-architecture]] + +ఈ విభాగంలో, మనం Transformer మోడల్ యొక్క సాధారణ ఆర్కిటెక్చర్‌ను పరిశీలిద్దాం. మీకు కొన్ని భావనలు అర్థం కాకపోయినా చింతించకండి; ప్రతి భాగాన్ని కవర్ చేసే వివరణాత్మక విభాగాలు తరువాత ఉన్నాయి. + + + +ఈ మోడల్ ప్రధానంగా రెండు బ్లాక్‌లతో కూడి ఉంటుంది: + +- **ఎన్‌కోడర్ (ఎడమవైపు)**: ఎన్‌కోడర్ ఒక ఇన్‌పుట్‌ను స్వీకరించి దాని యొక్క ప్రాతినిధ్యాన్ని (దాని ఫీచర్స్) నిర్మిస్తుంది. అంటే ఈ మోడల్ ఇన్‌పుట్ నుండి అవగాహనను పొందడానికి ఆప్టిమైజ్ చేయబడింది. +- **డీకోడర్ (కుడివైపు)**: డీకోడర్, ఎన్‌కోడర్ యొక్క ప్రాతినిధ్యాన్ని (ఫీచర్స్) మరియు ఇతర ఇన్‌పుట్‌లను ఉపయోగించి ఒక లక్ష్య సీక్వెన్స్‌ను ఉత్పత్తి చేస్తుంది. అంటే ఈ మోడల్ అవుట్‌పుట్‌లను ఉత్పత్తి చేయడానికి ఆప్టిమైజ్ చేయబడింది. + +
+Architecture of a Transformers models + +
+ +ఈ భాగాలలో ప్రతి ఒక్కటి పనిని బట్టి స్వతంత్రంగా ఉపయోగించవచ్చు: + +- **ఎన్‌కోడర్-మాత్రమే మోడల్స్**: వాక్య వర్గీకరణ మరియు పేరుగల ఎంటిటీ గుర్తింపు వంటి ఇన్‌పుట్ అవగాహన అవసరమయ్యే పనులకు మంచివి. +- **డీకోడర్-మాత్రమే మోడల్స్**: టెక్స్ట్ జనరేషన్ వంటి ఉత్పాదక పనులకు మంచివి. +- **ఎన్‌కోడర్-డీకోడర్ మోడల్స్** లేదా **సీక్వెన్స్-టు-సీక్వెన్స్ మోడల్స్**: అనువాదం లేదా సారాంశీకరణ వంటి ఇన్‌పుట్ అవసరమయ్యే ఉత్పాదక పనులకు మంచివి. + +మనం ఈ ఆర్కిటెక్చర్లను తరువాత విభాగాలలో స్వతంత్రంగా పరిశీలిస్తాము. + +## అటెన్షన్ లేయర్లు[[attention-layers]] + +Transformer మోడల్స్ యొక్క ఒక ముఖ్య లక్షణం ఏమిటంటే, అవి _అటెన్షన్ లేయర్లు_ అనే ప్రత్యేక లేయర్లతో నిర్మించబడ్డాయి. నిజానికి, Transformer ఆర్కిటెక్చర్‌ను పరిచయం చేసిన పేపర్ శీర్షిక ["Attention Is All You Need"](https://arxiv.org/abs/1706.03762)! మనం కోర్సులో తరువాత అటెన్షన్ లేయర్ల వివరాలను అన్వేషిస్తాము; ప్రస్తుతానికి, మీరు తెలుసుకోవలసినది ఏమిటంటే, ఈ లేయర్, మీరు పంపిన వాక్యంలోని ప్రతి పదం యొక్క ప్రాతినిధ్యంతో వ్యవహరించేటప్పుడు, ఆ వాక్యంలోని కొన్ని నిర్దిష్ట పదాలపై ప్రత్యేక శ్రద్ధ పెట్టమని మోడల్‌కు చెబుతుంది (మరియు ఇతరులను ఎక్కువ లేదా తక్కువ విస్మరించమని). + +దీనిని సందర్భంలో ఉంచాలంటే, ఇంగ్లీష్ నుండి ఫ్రెంచ్‌కు టెక్స్ట్‌ను అనువదించే పనిని పరిగణించండి. "You like this course" అనే ఇన్‌పుట్ ఇచ్చినప్పుడు, ఒక అనువాద మోడల్ "like" అనే పదం యొక్క సరైన అనువాదాన్ని పొందడానికి ప్రక్కనే ఉన్న "You" అనే పదంపై కూడా శ్రద్ధ పెట్టాలి, ఎందుకంటే ఫ్రెంచ్‌లో "like" అనే క్రియ సబ్జెక్ట్‌ను బట్టి విభిన్నంగా సంయోగం చేయబడుతుంది. అయితే, వాక్యంలోని మిగిలిన భాగం ఆ పదం యొక్క అనువాదానికి ఉపయోగపడదు. అదే విధంగా, "this" ను అనువదించేటప్పుడు మోడల్ "course" అనే పదంపై కూడా శ్రద్ధ పెట్టాలి, ఎందుకంటే దానికి సంబంధించిన నామవాచకం పుంలింగమా లేదా స్త్రీలింగమా అనే దానిపై ఆధారపడి "this" విభిన్నంగా అనువదించబడుతుంది. మళ్లీ, వాక్యంలోని ఇతర పదాలు "course" యొక్క అనువాదానికి పట్టింపు లేదు. మరింత సంక్లిష్టమైన వాక్యాలతో (మరియు మరింత సంక్లిష్టమైన వ్యాకరణ నియమాలతో), ప్రతి పదాన్ని సరిగ్గా అనువదించడానికి మోడల్ వాక్యంలో ఇంకా దూరంగా కనిపించే పదాలపై ప్రత్యేక శ్రద్ధ పెట్టాల్సి ఉంటుంది. + +సహజ భాషతో సంబంధం ఉన్న ఏ పనికైనా ఇదే భావన వర్తిస్తుంది: ఒక పదానికి దానంతట అదే ఒక అర్థం ఉంటుంది, కానీ ఆ అర్థం సందర్భం ద్వారా తీవ్రంగా ప్రభావితమవుతుంది, ఇది అధ్యయనం చేయబడుతున్న పదం ముందు లేదా తరువాత ఉన్న ఏ ఇతర పదం (లేదా పదాలు) అయినా కావచ్చు. + +ఇప్పుడు మీకు అటెన్షన్ లేయర్ల గురించి ఒక ఆలోచన వచ్చింది కాబట్టి, Transformer ఆర్కిటెక్చర్‌ను మరింత నిశితంగా పరిశీలిద్దాం. + +## అసలు ఆర్కిటెక్చర్[[the-original-architecture]] + +Transformer ఆర్కిటెక్చర్ వాస్తవానికి అనువాదం కోసం రూపొందించబడింది. శిక్షణ సమయంలో, ఎన్‌కోడర్ ఒక నిర్దిష్ట భాషలో ఇన్‌పుట్‌లను (వాక్యాలను) స్వీకరిస్తుంది, అయితే డీకోడర్ అవే వాక్యాలను కావలసిన లక్ష్య భాషలో స్వీకరిస్తుంది. ఎన్‌కోడర్‌లో, అటెన్షన్ లేయర్లు ఒక వాక్యంలోని అన్ని పదాలను ఉపయోగించగలవు (ఎందుకంటే, మనం ఇప్పుడు చూసినట్లుగా, ఒక నిర్దిష్ట పదం యొక్క అనువాదం వాక్యంలోని దాని తరువాత మరియు ముందు ఉన్న వాటిపై ఆధారపడి ఉండవచ్చు). అయితే, డీకోడర్ వరుసగా పనిచేస్తుంది మరియు అది ఇప్పటికే అనువదించిన వాక్యంలోని పదాలపై మాత్రమే శ్రద్ధ పెట్టగలదు (అందుకే, ప్రస్తుతం ఉత్పత్తి చేయబడుతున్న పదం ముందు ఉన్న పదాలు మాత్రమే). ఉదాహరణకు, మనం అనువదించబడిన లక్ష్యం యొక్క మొదటి మూడు పదాలను అంచనా వేసినప్పుడు, వాటిని డీకోడర్‌కు ఇస్తాము, అది తరువాత నాల్గవ పదాన్ని అంచనా వేయడానికి ఎన్‌కోడర్ యొక్క అన్ని ఇన్‌పుట్‌లను ఉపయోగిస్తుంది. + +శిక్షణ సమయంలో వేగాన్ని పెంచడానికి (మోడల్‌కు లక్ష్య వాక్యాలకు యాక్సెస్ ఉన్నప్పుడు), డీకోడర్‌కు మొత్తం లక్ష్యం ఇవ్వబడుతుంది, కానీ భవిష్యత్తు పదాలను ఉపయోగించడానికి అనుమతించబడదు (స్థానం 2 వద్ద పదాన్ని అంచనా వేయడానికి ప్రయత్నిస్తున్నప్పుడు స్థానం 2 వద్ద పదానికి యాక్సెస్ ఉంటే, సమస్య చాలా కష్టంగా ఉండదు!). ఉదాహరణకు, నాల్గవ పదాన్ని అంచనా వేయడానికి ప్రయత్నిస్తున్నప్పుడు, అటెన్షన్ లేయర్ కేవలం 1 నుండి 3 వరకు ఉన్న స్థానాలలోని పదాలకు మాత్రమే యాక్సెస్ కలిగి ఉంటుంది. + +అసలు Transformer ఆర్కిటెక్చర్ ఇలా ఉండేది, ఎడమవైపు ఎన్‌కోడర్ మరియు కుడివైపు డీకోడర్‌తో: + +
+Architecture of a Transformers models + +
+ +డీకోడర్ బ్లాక్‌లోని మొదటి అటెన్షన్ లేయర్ డీకోడర్‌కు అన్ని (గత) ఇన్‌పుట్‌లపై శ్రద్ధ చూపుతుంది, కానీ రెండవ అటెన్షన్ లేయర్ ఎన్‌కోడర్ యొక్క అవుట్‌పుట్‌ను ఉపయోగిస్తుంది. అందువల్ల ఇది ప్రస్తుత పదాన్ని ఉత్తమంగా అంచనా వేయడానికి మొత్తం ఇన్‌పుట్ వాక్యాన్ని యాక్సెస్ చేయగలదు. విభిన్న భాషలు పదాలను విభిన్న క్రమాలలో ఉంచే వ్యాకరణ నియమాలను కలిగి ఉండవచ్చు కాబట్టి లేదా వాక్యంలో తరువాత అందించిన కొన్ని సందర్భాలు ఒక నిర్దిష్ట పదం యొక్క ఉత్తమ అనువాదాన్ని నిర్ధారించడానికి సహాయకరంగా ఉండవచ్చు కాబట్టి ఇది చాలా ఉపయోగకరంగా ఉంటుంది. + +_attention mask_ ను ఎన్‌కోడర్/డీకోడర్‌లో కూడా ఉపయోగించవచ్చు, మోడల్ కొన్ని ప్రత్యేక పదాలపై శ్రద్ధ పెట్టకుండా నిరోధించడానికి -- ఉదాహరణకు, వాక్యాలను బ్యాచింగ్ చేసేటప్పుడు అన్ని ఇన్‌పుట్‌లను ఒకే పొడవుకు తీసుకురావడానికి ఉపయోగించే ప్రత్యేక ప్యాడింగ్ పదం. + +## ఆర్కిటెక్చర్లు vs. చెక్‌పాయింట్లు[[architecture-vs-checkpoints]] + +ఈ కోర్సులో మనం Transformer మోడల్స్‌లోకి లోతుగా వెళ్తున్నప్పుడు, మీరు _architectures_ మరియు _checkpoints_ అలాగే _models_ అనే ప్రస్తావనలు చూస్తారు. ఈ పదాలకు అన్నింటికీ కొద్దిగా భిన్నమైన అర్థాలు ఉన్నాయి: + +- **_architectures_**: ఇది మోడల్ యొక్క అస్థిపంజరం -- ప్రతి లేయర్ యొక్క నిర్వచనం మరియు మోడల్ లోపల జరిగే ప్రతి ఆపరేషన్. +- **_checkpoints_**: ఇవి ఒక నిర్దిష్ట ఆర్కిటెక్చర్‌లో లోడ్ చేయబడే వెయిట్స్. +- **_models_**: ఇది ఒక గొడుగు పదం, "ఆర్కిటెక్చర్" లేదా "చెక్‌పాయింట్" అంత కచ్చితమైనది కాదు: ఇది రెండు అర్థాలను సూచించవచ్చు. అస్పష్టతను తగ్గించడానికి ఈ కోర్సు ముఖ్యం అయినప్పుడు _ఆర్కిటెక్చర్_ లేదా _చెక్‌పాయింట్_ అని నిర్దిష్టంగా చెబుతుంది. + +ఉదాహరణకు, BERT ఒక ఆర్కిటెక్చర్ అయితే, `bert-base-cased` అనేది BERT యొక్క మొదటి విడుదల కోసం Google బృందం శిక్షణ ఇచ్చిన వెయిట్స్ యొక్క సెట్, ఇది ఒక చెక్‌పాయింట్. అయితే, ఒకరు "BERT మోడల్" మరియు "`bert-base-cased` మోడల్" అని చెప్పవచ్చు. diff --git a/chapters/te/chapter1/5.mdx b/chapters/te/chapter1/5.mdx new file mode 100644 index 000000000..0754c89ea --- /dev/null +++ b/chapters/te/chapter1/5.mdx @@ -0,0 +1,270 @@ +# 🤗 Transformerలు పనులను ఎలా పరిష్కరిస్తాయి + + + +[Transformers, what can they do?](/course/chapter1/3)లో, మీరు సహజ భాషా ప్రాసెసింగ్ (NLP), ప్రసంగం మరియు ఆడియో, కంప్యూటర్ విజన్ పనులు మరియు వాటి కొన్ని ముఖ్యమైన అనువర్తనాల గురించి తెలుసుకున్నారు. ఈ పేజీ మోడల్స్ ఈ పనులను ఎలా పరిష్కరిస్తాయో నిశితంగా పరిశీలిస్తుంది మరియు తెరవెనుక ఏమి జరుగుతుందో వివరిస్తుంది. ఒక నిర్దిష్ట పనిని పరిష్కరించడానికి చాలా మార్గాలు ఉన్నాయి, కొన్ని మోడల్స్ నిర్దిష్ట టెక్నిక్‌లను అమలు చేయవచ్చు లేదా పనిని కొత్త కోణం నుండి కూడా సంప్రదించవచ్చు, కానీ Transformer మోడల్స్ కోసం, సాధారణ ఆలోచన ఒకటే. దాని సౌకర్యవంతమైన ఆర్కిటెక్చర్ కారణంగా, చాలా మోడల్స్ ఒక ఎన్‌కోడర్, ఒక డీకోడర్, లేదా ఒక ఎన్‌కోడర్-డీకోడర్ నిర్మాణం యొక్క వైవిధ్యాలుగా ఉంటాయి. + + + +నిర్దిష్ట ఆర్కిటెక్చరల్ వైవిధ్యాలలోకి ప్రవేశించే ముందు, చాలా పనులు ఒకే విధమైన పద్ధతిని అనుసరిస్తాయని అర్థం చేసుకోవడం సహాయపడుతుంది: ఇన్‌పుట్ డేటా ఒక మోడల్ ద్వారా ప్రాసెస్ చేయబడుతుంది మరియు అవుట్‌పుట్ ఒక నిర్దిష్ట పని కోసం వ్యాఖ్యానించబడుతుంది. తేడాలు డేటాను ఎలా తయారు చేస్తారు, ఏ మోడల్ ఆర్కిటెక్చర్ వైవిధ్యం ఉపయోగించబడుతుంది మరియు అవుట్‌పుట్ ఎలా ప్రాసెస్ చేయబడుతుంది అనే దానిలో ఉంటాయి. + + + +పనులు ఎలా పరిష్కరించబడతాయో వివరించడానికి, ఉపయోగకరమైన అంచనాలను అవుట్‌పుట్ చేయడానికి మోడల్ లోపల ఏమి జరుగుతుందో మేము వివరిస్తాము. మేము ఈ క్రింది మోడల్స్ మరియు వాటి సంబంధిత పనులను కవర్ చేస్తాము: + +- [Wav2Vec2](https://huggingface.co/docs/transformers/model_doc/wav2vec2) ఆడియో వర్గీకరణ మరియు ఆటోమేటిక్ స్పీచ్ రికగ్నిషన్ (ASR) కోసం +- [Vision Transformer (ViT)](https://huggingface.co/docs/transformers/model_doc/vit) మరియు [ConvNeXT](https://huggingface.co/docs/transformers/model_doc/convnext) ఇమేజ్ వర్గీకరణ కోసం +- [DETR](https://huggingface.co/docs/transformers/model_doc/detr) వస్తువు గుర్తింపు కోసం +- [Mask2Former](https://huggingface.co/docs/transformers/model_doc/mask2former) ఇమేజ్ సెగ్మెంటేషన్ కోసం +- [GLPN](https://huggingface.co/docs/transformers/model_doc/glpn) డెప్త్ ఎస్టిమేషన్ కోసం +- [BERT](https://huggingface.co/docs/transformers/model_doc/bert) ఎన్‌కోడర్‌ను ఉపయోగించే టెక్స్ట్ వర్గీకరణ, టోకెన్ వర్గీకరణ మరియు ప్రశ్నలకు సమాధానాలు వంటి NLP పనుల కోసం +- [GPT2](https://huggingface.co/docs/transformers/model_doc/gpt2) డీకోడర్‌ను ఉపయోగించే టెక్స్ట్ జనరేషన్ వంటి NLP పనుల కోసం +- [BART](https://huggingface.co/docs/transformers/model_doc/bart) ఎన్‌కోడర్-డీకోడర్‌ను ఉపయోగించే సారాంశం మరియు అనువాదం వంటి NLP పనుల కోసం + + + +మీరు ముందుకు వెళ్లే ముందు, అసలు Transformer ఆర్కిటెక్చర్ గురించి কিছু ప్రాథమిక పరిజ్ఞానం కలిగి ఉండటం మంచిది. ఎన్‌కోడర్‌లు, డీకోడర్‌లు మరియు అటెన్షన్ ఎలా పనిచేస్తుందో తెలుసుకోవడం వేర్వేరు Transformer మోడల్స్ ఎలా పనిచేస్తాయో అర్థం చేసుకోవడంలో మీకు సహాయపడుతుంది. మరింత సమాచారం కోసం మా [మునుపటి విభాగాన్ని](https://huggingface.co/course/chapter1/4?fw=pt) తప్పకుండా చూడండి! + + + +## భాష కోసం Transformer మోడల్స్ + +భాషా నమూనాలు ఆధునిక NLP యొక్క గుండెకాయ. అవి టెక్స్ట్‌లోని పదాలు లేదా టోకెన్‌ల మధ్య గణాంక నమూనాలు మరియు సంబంధాలను నేర్చుకోవడం ద్వారా మానవ భాషను అర్థం చేసుకోవడానికి మరియు ఉత్పత్తి చేయడానికి రూపొందించబడ్డాయి. + +Transformer మొదట యంత్ర అనువాదం కోసం రూపొందించబడింది, మరియు అప్పటి నుండి, ఇది అన్ని AI పనులను పరిష్కరించడానికి డిఫాల్ట్ ఆర్కిటెక్చర్‌గా మారింది. కొన్ని పనులు Transformer యొక్క ఎన్‌కోడర్ నిర్మాణానికి అనుకూలంగా ఉంటాయి, మరికొన్ని డీకోడర్‌కు బాగా సరిపోతాయి. మరికొన్ని పనులు Transformer యొక్క ఎన్‌కోడర్-డీకోడర్ నిర్మాణాన్ని రెండింటినీ ఉపయోగిస్తాయి. + +### భాషా నమూనాలు ఎలా పనిచేస్తాయి + +భాషా నమూనాలు చుట్టుపక్కల పదాల సందర్భాన్ని బట్టి ఒక పదం యొక్క సంభావ్యతను అంచనా వేయడానికి శిక్షణ పొందడం ద్వారా పనిచేస్తాయి. ఇది వాటికి భాషపై ప్రాథమిక అవగాహనను ఇస్తుంది, ఇది ఇతర పనులకు సాధారణీకరించగలదు. + +ఒక Transformer మోడల్‌కు శిక్షణ ఇవ్వడానికి రెండు ప్రధాన విధానాలు ఉన్నాయి: + +1. **మాస్క్డ్ లాంగ్వేజ్ మోడలింగ్ (MLM)**: BERT వంటి ఎన్‌కోడర్ మోడల్స్ ద్వారా ఉపయోగించబడుతుంది, ఈ విధానం ఇన్‌పుట్‌లో కొన్ని టోకెన్‌లను యాదృచ్ఛికంగా మాస్క్ చేస్తుంది మరియు చుట్టుపక్కల సందర్భం ఆధారంగా అసలు టోకెన్‌లను అంచనా వేయడానికి మోడల్‌కు శిక్షణ ఇస్తుంది. ఇది మోడల్ ద్విదిశాత్మక సందర్భాన్ని (మాస్క్ చేసిన పదం ముందు మరియు తరువాత ఉన్న పదాలను చూడటం) నేర్చుకోవడానికి అనుమతిస్తుంది. + +2. **కాజల్ లాంగ్వేజ్ మోడలింగ్ (CLM)**: GPT వంటి డీకోడర్ మోడల్స్ ద్వారా ఉపయోగించబడుతుంది, ఈ విధానం క్రమంలోని అన్ని మునుపటి టోకెన్‌ల ఆధారంగా తదుపరి టోకెన్‌ను అంచనా వేస్తుంది. మోడల్ తదుపరి టోకెన్‌ను అంచనా వేయడానికి ఎడమ వైపు (మునుపటి టోకెన్‌లు) నుండి మాత్రమే సందర్భాన్ని ఉపయోగించగలదు. + +### భాషా నమూనాల రకాలు + +Transformers లైబ్రరీలో, భాషా నమూనాలు సాధారణంగా మూడు ఆర్కిటెక్చరల్ వర్గాలలోకి వస్తాయి: + +1. **ఎన్‌కోడర్-మాత్రమే మోడల్స్** (BERT వంటివి): ఈ మోడల్స్ రెండు దిశల నుండి సందర్భాన్ని అర్థం చేసుకోవడానికి ఒక ద్విదిశాత్మక విధానాన్ని ఉపయోగిస్తాయి. వర్గీకరణ, పేరున్న ఎంటిటీ గుర్తింపు మరియు ప్రశ్నలకు సమాధానాలు వంటి టెక్స్ట్ యొక్క లోతైన అవగాహన అవసరమయ్యే పనులకు ఇవి ఉత్తమంగా సరిపోతాయి. + +2. **డీకోడర్-మాత్రమే మోడల్స్** (GPT, Llama వంటివి): ఈ మోడల్స్ ఎడమ నుండి కుడికి టెక్స్ట్‌ను ప్రాసెస్ చేస్తాయి మరియు ముఖ్యంగా టెక్స్ట్ జనరేషన్ పనులలో మంచివి. అవి ఒక ప్రాంప్ట్ ఆధారంగా వాక్యాలను పూర్తి చేయగలవు, వ్యాసాలు రాయగలవు లేదా కోడ్‌ను కూడా ఉత్పత్తి చేయగలవు. + +3. **ఎన్‌కోడర్-డీకోడర్ మోడల్స్** (T5, BART వంటివి): ఈ మోడల్స్ రెండు విధానాలను మిళితం చేస్తాయి, ఇన్‌పుట్‌ను అర్థం చేసుకోవడానికి ఒక ఎన్‌కోడర్‌ను మరియు అవుట్‌పుట్‌ను ఉత్పత్తి చేయడానికి ఒక డీకోడర్‌ను ఉపయోగిస్తాయి. అనువాదం, సారాంశం మరియు ప్రశ్నలకు సమాధానాలు వంటి సీక్వెన్స్-టు-సీక్వెన్స్ పనులలో ఇవి రాణిస్తాయి. + ![transformer-models-for-language](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter1/transformers_architecture.png) + +మునుపటి విభాగంలో మనం కవర్ చేసినట్లుగా, భాషా నమూనాలు సాధారణంగా స్వీయ-పర్యవేక్షిత పద్ధతిలో (మానవ ఉల్లేఖనలు లేకుండా) పెద్ద మొత్తంలో టెక్స్ట్ డేటాపై ముందే శిక్షణ పొందుతాయి, ఆపై నిర్దిష్ట పనులపై ఫైన్-ట్యూన్ చేయబడతాయి. ఈ విధానం, ట్రాన్స్‌ఫర్ లెర్నింగ్ అని పిలవబడుతుంది, ఈ మోడల్స్ సాపేక్షంగా తక్కువ మొత్తంలో పని-నిర్దిష్ట డేటాతో అనేక విభిన్న NLP పనులకు అనుగుణంగా ఉండటానికి అనుమతిస్తుంది. + +తరువాతి విభాగాలలో, మేము నిర్దిష్ట మోడల్ ఆర్కిటెక్చర్లను మరియు అవి ప్రసంగం, దృష్టి మరియు టెక్స్ట్ డొమైన్‌లలోని వివిధ పనులకు ఎలా వర్తింపజేయబడతాయో అన్వేషిస్తాము. + + + +ఒక నిర్దిష్ట NLP పనికి ఏ Transformer ఆర్కిటెక్చర్ భాగం (ఎన్‌కోడర్, డీకోడర్, లేదా రెండూ) ఉత్తమంగా సరిపోతుందో అర్థం చేసుకోవడం సరైన మోడల్‌ను ఎంచుకోవడంలో కీలకం. సాధారణంగా, ద్విదిశాత్మక సందర్భం అవసరమయ్యే పనులు ఎన్‌కోడర్‌లను ఉపయోగిస్తాయి, టెక్స్ట్‌ను ఉత్పత్తి చేసే పనులు డీకోడర్‌లను ఉపయోగిస్తాయి మరియు ఒక క్రమాన్ని మరొకదానికి మార్చే పనులు ఎన్‌కోడర్-డీకోడర్‌లను ఉపయోగిస్తాయి. + + + +### టెక్స్ట్ జనరేషన్ + +టెక్స్ట్ జనరేషన్ అనేది ఒక ప్రాంప్ట్ లేదా ఇన్‌పుట్ ఆధారంగా పొందికైన మరియు సందర్భోచితంగా ఉండే టెక్స్ట్‌ను సృష్టించడం. + +[GPT-2](https://huggingface.co/docs/transformers/model_doc/gpt2) అనేది పెద్ద మొత్తంలో టెక్స్ట్‌పై ముందే శిక్షణ పొందిన డీకోడర్-మాత్రమే మోడల్. ఇది ఒక ప్రాంప్ట్ ఇచ్చినప్పుడు నమ్మదగిన (ఎల్లప్పుడూ నిజం కానప్పటికీ!) టెక్స్ట్‌ను ఉత్పత్తి చేయగలదు మరియు స్పష్టంగా శిక్షణ పొందనప్పటికీ ప్రశ్నలకు సమాధానాలు వంటి ఇతర NLP పనులను పూర్తి చేయగలదు. + +
+ +
+1. GPT-2 పదాలను టోకనైజ్ చేయడానికి మరియు టోకెన్ ఎంబెడ్డింగ్‌ను రూపొందించడానికి [byte +pair encoding (BPE)](https://huggingface.co/docs/transformers/tokenizer_summary#bytepair-encoding-bpe) +ను ఉపయోగిస్తుంది. క్రమంలో ప్రతి టోకెన్ యొక్క స్థానాన్ని సూచించడానికి టోకెన్ ఎంబెడ్డింగ్‌లకు +పొజిషనల్ ఎన్‌కోడింగ్‌లు జోడించబడతాయి. ఇన్‌పుట్ ఎంబెడ్డింగ్‌లు చివరి దాచిన స్థితిని +అవుట్‌పుట్ చేయడానికి బహుళ డీకోడర్ బ్లాక్‌ల ద్వారా పంపబడతాయి. ప్రతి డీకోడర్ బ్లాక్ +లోపల, GPT-2 ఒక *masked self-attention* లేయర్‌ను ఉపయోగిస్తుంది, దీని అర్థం GPT-2 భవిష్యత్ +టోకెన్‌లకు అటెన్షన్ ఇవ్వలేదు. ఇది ఎడమ వైపు ఉన్న టోకెన్‌లకు మాత్రమే అటెన్షన్ ఇవ్వడానికి +అనుమతించబడుతుంది. ఇది BERT యొక్క [`mask`] టోకెన్ నుండి భిన్నంగా ఉంటుంది, ఎందుకంటే +masked self-attention లో, భవిష్యత్ టోకెన్‌ల కోసం స్కోర్‌ను `0` కు సెట్ చేయడానికి +ఒక అటెన్షన్ మాస్క్ ఉపయోగించబడుతుంది. + +2. డీకోడర్ నుండి వచ్చే అవుట్‌పుట్‌ను ఒక లాంగ్వేజ్ మోడలింగ్ హెడ్‌కు పంపబడుతుంది, ఇది దాచిన స్థితులను లాజిట్స్‌గా మార్చడానికి ఒక లీనియర్ ట్రాన్స్‌ఫర్మేషన్ చేస్తుంది. లేబుల్ క్రమంలోని తర్వాతి టోకెన్, ఇది లాజిట్స్‌ను కుడివైపు ఒక స్థానం జరపడం ద్వారా సృష్టించబడుతుంది. షిఫ్ట్ చేయబడిన లాజిట్స్ మరియు లేబుల్స్ మధ్య క్రాస్-ఎంట్రోపీ నష్టం లెక్కించబడుతుంది, తద్వారా తదుపరి అత్యంత సంభావ్య టోకెన్‌ను అవుట్‌పుట్ చేయవచ్చు. + +GPT-2 యొక్క ప్రీ-ట్రైనింగ్ లక్ష్యం పూర్తిగా [causal language modeling](https://huggingface.co/docs/transformers/glossary#causal-language-modeling) పై ఆధారపడి ఉంటుంది, ఒక క్రమంలోని తర్వాతి పదాన్ని అంచనా వేయడం. ఇది GPT-2ను ముఖ్యంగా టెక్స్ట్ ఉత్పత్తికి సంబంధించిన పనులలో మంచిదిగా చేస్తుంది. + +టెక్స్ట్ జనరేషన్‌లో మీ నైపుణ్యాన్ని ప్రయత్నించడానికి సిద్ధంగా ఉన్నారా? DistilGPT-2ను ఫైన్‌ట్యూన్ చేయడం మరియు దానిని ఇన్ఫరెన్స్ కోసం ఉపయోగించడం ఎలాగో తెలుసుకోవడానికి మా పూర్తి [causal language modeling guide](https://huggingface.co/docs/transformers/tasks/language_modeling#causal-language-modeling)ను చూడండి! + + + టెక్స్ట్ జనరేషన్ గురించి మరింత సమాచారం కోసం, [text generation + strategies](generation_strategies) గైడ్‌ను చూడండి! + + +### టెక్స్ట్ వర్గీకరణ + +టెక్స్ట్ వర్గీకరణ అనేది టెక్స్ట్ పత్రాలకు ముందుగా నిర్వచించిన వర్గాలను కేటాయించడం, సెంటిమెంట్ విశ్లేషణ, అంశ వర్గీకరణ, లేదా స్పామ్ గుర్తింపు వంటివి. + +[BERT](https://huggingface.co/docs/transformers/model_doc/bert) ఒక ఎన్‌కోడర్-మాత్రమే మోడల్ మరియు ఇది రెండు వైపులా ఉన్న పదాలకు అటెన్షన్ ఇవ్వడం ద్వారా టెక్స్ట్ యొక్క గొప్ప ప్రాతినిధ్యాలను నేర్చుకోవడానికి లోతైన ద్విదిశాత్మకతను సమర్థవంతంగా అమలు చేసిన మొదటి మోడల్. + +1. BERT టెక్స్ట్ యొక్క టోకెన్ ఎంబెడ్డింగ్‌ను రూపొందించడానికి [WordPiece](https://huggingface.co/docs/transformers/tokenizer_summary#wordpiece) టోకనైజేషన్‌ను ఉపయోగిస్తుంది. ఒకే వాక్యం మరియు వాక్యాల జత మధ్య తేడాను చెప్పడానికి, వాటిని వేరు చేయడానికి ఒక ప్రత్యేక `[SEP]` టోకెన్ జోడించబడుతుంది. ప్రతి టెక్స్ట్ క్రమం ప్రారంభంలో ఒక ప్రత్యేక `[CLS]` టోకెన్ జోడించబడుతుంది. `[CLS]` టోకెన్‌తో ఉన్న చివరి అవుట్‌పుట్ వర్గీకరణ పనుల కోసం వర్గీకరణ హెడ్‌కు ఇన్‌పుట్‌గా ఉపయోగించబడుతుంది. BERT ఒక టోకెన్ వాక్యాల జతలోని మొదటి లేదా రెండవ వాక్యానికి చెందినదా అని సూచించడానికి ఒక సెగ్మెంట్ ఎంబెడ్డింగ్‌ను కూడా జోడిస్తుంది. + +2. BERT రెండు లక్ష్యాలతో ముందే శిక్షణ పొందింది: మాస్క్డ్ లాంగ్వేజ్ మోడలింగ్ మరియు నెక్స్ట్-సెంటెన్స్ ప్రిడిక్షన్. మాస్క్డ్ లాంగ్వేజ్ మోడలింగ్‌లో, ఇన్‌పుట్ టోకెన్‌లలో కొంత శాతం యాదృచ్ఛికంగా మాస్క్ చేయబడతాయి, మరియు మోడల్ వీటిని అంచనా వేయాలి. ఇది ద్విదిశాత్మకత సమస్యను పరిష్కరిస్తుంది, ఇక్కడ మోడల్ మోసం చేసి అన్ని పదాలను చూసి తర్వాతి పదాన్ని "అంచనా" వేయగలదు. అంచనా వేయబడిన మాస్క్ టోకెన్‌ల యొక్క చివరి దాచిన స్థితులు మాస్క్ చేయబడిన పదాన్ని అంచనా వేయడానికి ఒక ఫీడ్‌ఫార్వర్డ్ నెట్‌వర్క్‌కు పదజాలంపై సాఫ్ట్‌మాక్స్‌తో పంపబడతాయి. + + రెండవ ప్రీ-ట్రైనింగ్ లక్ష్యం నెక్స్ట్-సెంటెన్స్ ప్రిడిక్షన్. మోడల్ వాక్యం B వాక్యం A ను అనుసరిస్తుందా లేదా అని అంచనా వేయాలి. సగం సార్లు వాక్యం B తర్వాతి వాక్యం, మరియు మిగిలిన సగం సార్లు, వాక్యం B ఒక యాదృచ్ఛిక వాక్యం. అంచనా, అది తర్వాతి వాక్యమా కాదా అనేది, రెండు వర్గాలపై (`IsNext` మరియు `NotNext`) సాఫ్ట్‌మాక్స్‌తో ఉన్న ఒక ఫీడ్‌ఫార్వర్డ్ నెట్‌వర్క్‌కు పంపబడుతుంది. + +3. ఇన్‌పుట్ ఎంబెడ్డింగ్‌లు చివరి దాచిన స్థితులను అవుట్‌పుట్ చేయడానికి బహుళ ఎన్‌కోడర్ లేయర్‌ల ద్వారా పంపబడతాయి. + +టెక్స్ట్ వర్గీకరణ కోసం ముందే శిక్షణ పొందిన మోడల్‌ను ఉపయోగించడానికి, బేస్ BERT మోడల్ పైన ఒక సీక్వెన్స్ వర్గీకరణ హెడ్‌ను జోడించండి. సీక్వెన్స్ వర్గీకరణ హెడ్ అనేది ఒక లీనియర్ లేయర్, ఇది చివరి దాచిన స్థితులను అంగీకరించి మరియు వాటిని లాజిట్స్‌గా మార్చడానికి ఒక లీనియర్ ట్రాన్స్‌ఫర్మేషన్ చేస్తుంది. లాజిట్స్ మరియు టార్గెట్ మధ్య క్రాస్-ఎంట్రోపీ నష్టం లెక్కించబడుతుంది, తద్వారా అత్యంత సంభావ్య లేబుల్‌ను కనుగొనవచ్చు. + +టెక్స్ట్ వర్గీకరణలో మీ నైపుణ్యాన్ని ప్రయత్నించడానికి సిద్ధంగా ఉన్నారా? DistilBERTను ఫైన్‌ట్యూన్ చేయడం మరియు దానిని ఇన్ఫరెన్స్ కోసం ఉపయోగించడం ఎలాగో తెలుసుకోవడానికి మా పూర్తి [text classification guide](https://huggingface.co/docs/transformers/tasks/sequence_classification)ను చూడండి! + +### టోకెన్ వర్గీకరణ + +టోకెన్ వర్గీకరణ అనేది ఒక క్రమంలోని ప్రతి టోకెన్‌కు ఒక లేబుల్‌ను కేటాయించడం, పేరున్న ఎంటిటీ గుర్తింపు లేదా పార్ట్-ఆఫ్-స్పీచ్ ట్యాగింగ్ వంటివి. + +పేరున్న ఎంటిటీ గుర్తింపు (NER) వంటి టోకెన్ వర్గీకరణ పనుల కోసం BERTను ఉపయోగించడానికి, బేస్ BERT మోడల్ పైన ఒక టోకెన్ వర్గీకరణ హెడ్‌ను జోడించండి. టోకెన్ వర్గీకరణ హెడ్ అనేది ఒక లీనియర్ లేయర్, ఇది చివరి దాచిన స్థితులను అంగీకరించి మరియు వాటిని లాజిట్స్‌గా మార్చడానికి ఒక లీనియర్ ట్రాన్స్‌ఫర్మేషన్ చేస్తుంది. లాజిట్స్ మరియు ప్రతి టోకెన్ మధ్య క్రాస్-ఎంట్రోపీ నష్టం లెక్కించబడుతుంది, తద్వారా అత్యంత సంభావ్య లేబుల్‌ను కనుగొనవచ్చు. + +టోకెన్ వర్గీకరణలో మీ నైపుణ్యాన్ని ప్రయత్నించడానికి సిద్ధంగా ఉన్నారా? DistilBERTను ఫైన్‌ట్యూన్ చేయడం మరియు దానిని ఇన్ఫరెన్స్ కోసం ఉపయోగించడం ఎలాగో తెలుసుకోవడానికి మా పూర్తి [token classification guide](https://huggingface.co/docs/transformers/tasks/token_classification)ను చూడండి! + +### ప్రశ్నలకు సమాధానాలు + +ప్రశ్నలకు సమాధానాలు అనేది ఇచ్చిన సందర్భం లేదా పేరాలో ఒక ప్రశ్నకు సమాధానాన్ని కనుగొనడం. + +ప్రశ్నలకు సమాధానాల కోసం BERTను ఉపయోగించడానికి, బేస్ BERT మోడల్ పైన ఒక స్పాన్ వర్గీకరణ హెడ్‌ను జోడించండి. ఈ లీనియర్ లేయర్ చివరి దాచిన స్థితులను అంగీకరించి మరియు సమాధానానికి సంబంధించిన `span` ప్రారంభ మరియు ముగింపు లాజిట్స్‌ను లెక్కించడానికి ఒక లీనియర్ ట్రాన్స్‌ఫర్మేషన్ చేస్తుంది. లాజిట్స్ మరియు లేబుల్ పొజిషన్ మధ్య క్రాస్-ఎంట్రోపీ నష్టం లెక్కించబడుతుంది, తద్వారా సమాధానానికి సంబంధించిన అత్యంత సంభావ్య టెక్స్ట్ స్పాన్‌ను కనుగొనవచ్చు. + +ప్రశ్నలకు సమాధానాలలో మీ నైపుణ్యాన్ని ప్రయత్నించడానికి సిద్ధంగా ఉన్నారా? DistilBERTను ఫైన్‌ట్యూన్ చేయడం మరియు దానిని ఇన్ఫరెన్స్ కోసం ఉపయోగించడం ఎలాగో తెలుసుకోవడానికి మా పూర్తి [question answering guide](https://huggingface.co/docs/transformers/tasks/question_answering)ను చూడండి! + + + +💡 BERT ముందే శిక్షణ పొందిన తర్వాత వివిధ పనుల కోసం ఉపయోగించడం ఎంత సులభమో గమనించండి. మీ దాచిన స్థితులను మీ కావలసిన అవుట్‌పుట్‌గా మార్చడానికి ముందే శిక్షణ పొందిన మోడల్‌కు ఒక నిర్దిష్ట హెడ్‌ను జోడించడం మాత్రమే మీకు అవసరం! + + + +### సారాంశం + +సారాంశం అనేది దాని కీలక సమాచారం మరియు అర్థాన్ని కాపాడుకుంటూ ఒక పొడవైన టెక్స్ట్‌ను చిన్న వెర్షన్‌గా కుదించడం. + +[BART](https://huggingface.co/docs/transformers/model_doc/bart) మరియు [T5](model_doc/t5) వంటి ఎన్‌కోడర్-డీకోడర్ మోడల్స్ ఒక సారాంశం పని యొక్క సీక్వెన్స్-టు-సీక్వెన్స్ నమూనా కోసం రూపొందించబడ్డాయి. మేము ఈ విభాగంలో BART ఎలా పనిచేస్తుందో వివరిస్తాము, ఆపై మీరు చివరిలో T5ను ఫైన్‌ట్యూన్ చేయడానికి ప్రయత్నించవచ్చు. + +
+ +
+ +1. BART యొక్క ఎన్‌కోడర్ ఆర్కిటెక్చర్ BERTకు చాలా సారూప్యంగా ఉంటుంది మరియు టెక్స్ట్ యొక్క టోకెన్ మరియు పొజిషనల్ ఎంబెడ్డింగ్‌ను అంగీకరిస్తుంది. BART ఇన్‌పుట్‌ను పాడు చేసి ఆపై దానిని డీకోడర్‌తో పునర్నిర్మించడం ద్వారా ముందే శిక్షణ పొందింది. నిర్దిష్ట కరప్షన్ వ్యూహాలు ఉన్న ఇతర ఎన్‌కోడర్‌ల వలె కాకుండా, BART ఏ రకమైన కరప్షన్‌ను అయినా వర్తింపజేయగలదు. _text infilling_ కరప్షన్ వ్యూహం ఉత్తమంగా పనిచేస్తుంది. టెక్స్ట్ ఇన్ఫిలింగ్‌లో, అనేక టెక్స్ట్ స్పాన్‌లు ఒక **సింగిల్** [`mask`] టోకెన్‌తో భర్తీ చేయబడతాయి. ఇది ముఖ్యం ఎందుకంటే మోడల్ మాస్క్ చేసిన టోకెన్‌లను అంచనా వేయాలి, మరియు ఇది మోడల్‌కు తప్పిపోయిన టోకెన్‌ల సంఖ్యను అంచనా వేయడం నేర్పుతుంది. ఇన్‌పుట్ ఎంబెడ్డింగ్‌లు మరియు మాస్క్ చేసిన స్పాన్‌లు ఎన్‌కోడర్ ద్వారా పంపబడి చివరి దాచిన స్థితులను అవుట్‌పుట్ చేస్తాయి, కానీ BERT వలె కాకుండా, BART ఒక పదాన్ని అంచనా వేయడానికి చివరిలో ఒక ఫైనల్ ఫీడ్‌ఫార్వర్డ్ నెట్‌వర్క్‌ను జోడించదు. + +2. ఎన్‌కోడర్ యొక్క అవుట్‌పుట్ డీకోడర్‌కు పంపబడుతుంది, ఇది మాస్క్ చేసిన టోకెన్‌లను మరియు ఎన్‌కోడర్ యొక్క అవుట్‌పుట్ నుండి ఏదైనా పాడవని టోకెన్‌లను అంచనా వేయాలి. ఇది డీకోడర్‌కు అసలు టెక్స్ట్‌ను పునరుద్ధరించడానికి అదనపు సందర్భాన్ని ఇస్తుంది. డీకోడర్ నుండి వచ్చే అవుట్‌పుట్‌ను ఒక లాంగ్వేజ్ మోడలింగ్ హెడ్‌కు పంపబడుతుంది, ఇది దాచిన స్థితులను లాజిట్స్‌గా మార్చడానికి ఒక లీనియర్ ట్రాన్స్‌ఫర్మేషన్ చేస్తుంది. లాజిట్స్ మరియు లేబుల్ మధ్య క్రాస్-ఎంట్రోపీ నష్టం లెక్కించబడుతుంది, ఇది కేవలం కుడివైపు షిఫ్ట్ చేయబడిన టోకెన్. + +సారాంశంలో మీ నైపుణ్యాన్ని ప్రయత్నించడానికి సిద్ధంగా ఉన్నారా? T5ను ఫైన్‌ట్యూన్ చేయడం మరియు దానిని ఇన్ఫరెన్స్ కోసం ఉపయోగించడం ఎలాగో తెలుసుకోవడానికి మా పూర్తి [summarization guide](https://huggingface.co/docs/transformers/tasks/summarization)ను చూడండి! + + + +టెక్స్ట్ జనరేషన్ గురించి మరింత సమాచారం కోసం, [text generation strategies](https://huggingface.co/docs/transformers/generation_strategies) గైడ్‌ను చూడండి! + + + +### అనువాదం + +అనువాదం అనేది ఒక భాష నుండి మరొక భాషకు టెక్స్ట్‌ను దాని అర్థాన్ని కాపాడుకుంటూ మార్చడం. అనువాదం కూడా ఒక సీక్వెన్స్-టు-సీక్వెన్స్ పనికి ఉదాహరణ, అంటే మీరు దీన్ని చేయడానికి [BART](https://huggingface.co/docs/transformers/model_doc/bart) లేదా [T5](model_doc/t5) వంటి ఎన్‌కోడర్-డీకోడర్ మోడల్‌ను ఉపయోగించవచ్చు. మేము ఈ విభాగంలో BART ఎలా పనిచేస్తుందో వివరిస్తాము, ఆపై మీరు చివరిలో T5ను ఫైన్‌ట్యూన్ చేయడానికి ప్రయత్నించవచ్చు. + +BART ఒక మూల భాషను లక్ష్య భాషలోకి డీకోడ్ చేయగల ఇన్‌పుట్‌గా మ్యాప్ చేయడానికి ఒక ప్రత్యేక యాదృచ్ఛికంగా ప్రారంభించబడిన ఎన్‌కోడర్‌ను జోడించడం ద్వారా అనువాదానికి అనుగుణంగా ఉంటుంది. ఈ కొత్త ఎన్‌కోడర్ యొక్క ఎంబెడ్డింగ్‌లు అసలు వర్డ్ ఎంబెడ్డింగ్‌లకు బదులుగా ముందే శిక్షణ పొందిన ఎన్‌కోడర్‌కు పంపబడతాయి. మూల ఎన్‌కోడర్ మోడల్ అవుట్‌పుట్ నుండి క్రాస్-ఎంట్రోపీ నష్టంతో మూల ఎన్‌కోడర్, పొజిషనల్ ఎంబెడ్డింగ్‌లు మరియు ఇన్‌పుట్ ఎంబెడ్డింగ్‌లను నవీకరించడం ద్వారా శిక్షణ పొందుతుంది. మోడల్ పారామితులు ఈ మొదటి దశలో ఫ్రీజ్ చేయబడతాయి, మరియు అన్ని మోడల్ పారామితులు రెండవ దశలో కలిసి శిక్షణ పొందుతాయి. +BART తరువాత అనేక విభిన్న భాషలపై ముందే శిక్షణ పొందిన అనువాదం కోసం ఉద్దేశించిన బహుభాషా వెర్షన్, mBART, ను అనుసరించింది. + +అనువాదంలో మీ నైపుణ్యాన్ని ప్రయత్నించడానికి సిద్ధంగా ఉన్నారా? T5ను ఫైన్‌ట్యూన్ చేయడం మరియు దానిని ఇన్ఫరెన్స్ కోసం ఉపయోగించడం ఎలాగో తెలుసుకోవడానికి మా పూర్తి [translation guide](https://huggingface.co/docs/transformers/tasks/translation)ను చూడండి! + + + +ఈ గైడ్ అంతటా మీరు చూసినట్లుగా, అనేక మోడల్స్ వేర్వేరు పనులను పరిష్కరించినప్పటికీ ఇలాంటి నమూనాలను అనుసరిస్తాయి. ఈ సాధారణ నమూనాలను అర్థం చేసుకోవడం కొత్త మోడల్స్ ఎలా పనిచేస్తాయో మరియు మీ నిర్దిష్ట అవసరాలకు అనుగుణంగా ఉన్న మోడల్స్‌ను ఎలా మార్చుకోవాలో త్వరగా గ్రహించడంలో మీకు సహాయపడుతుంది. + + + +## టెక్స్ట్ దాటిన మోడాలిటీలు + +Transformers టెక్స్ట్‌కు పరిమితం కాదు. అవి ప్రసంగం మరియు ఆడియో, చిత్రాలు మరియు వీడియో వంటి ఇతర మోడాలిటీలకు కూడా వర్తింపజేయబడతాయి. వాస్తవానికి, ఈ కోర్సులో మనం టెక్స్ట్‌పై దృష్టి పెడతాము, కానీ మనం ఇతర మోడాలిటీలను క్లుప్తంగా పరిచయం చేయవచ్చు. + +### ప్రసంగం మరియు ఆడియో + +టెక్స్ట్ లేదా చిత్రాలతో పోలిస్తే ప్రత్యేకమైన సవాళ్లను ఎదుర్కొనే ప్రసంగం మరియు ఆడియో డేటాను Transformer మోడల్స్ ఎలా నిర్వహిస్తాయో అన్వేషించడం ద్వారా ప్రారంభిద్దాం. + +[Whisper](https://huggingface.co/docs/transformers/main/en/model_doc/whisper) అనేది 680,000 గంటల లేబుల్ చేయబడిన ఆడియో డేటాపై ముందే శిక్షణ పొందిన ఒక ఎన్‌కోడర్-డీకోడర్ (సీక్వెన్స్-టు-సీక్వెన్స్) ట్రాన్స్‌ఫార్మర్. ఈ మొత్తం ప్రీ-ట్రైనింగ్ డేటా ఇంగ్లీష్ మరియు అనేక ఇతర భాషలలో ఆడియో పనులపై జీరో-షాట్ పనితీరును సాధ్యం చేస్తుంది. డీకోడర్ Whisperకు దాని నేర్చుకున్న ప్రసంగ ప్రాతినిధ్యాలను టెక్స్ట్ వంటి ఉపయోగకరమైన అవుట్‌పుట్‌లకు, అదనపు ఫైన్-ట్యూనింగ్ లేకుండా మ్యాప్ చేయడానికి అనుమతిస్తుంది. Whisper బాక్స్ నుండి నేరుగా పనిచేస్తుంది. + +
+ +
+ +ఈ రేఖాచిత్రం [Whisper పేపర్](https://huggingface.co/papers/2212.04356) నుండి తీసుకోబడింది. + +ఈ మోడల్‌లో రెండు ప్రధాన భాగాలు ఉన్నాయి: + +1. ఒక **ఎన్‌కోడర్** ఇన్‌పుట్ ఆడియోను ప్రాసెస్ చేస్తుంది. ముడి ఆడియో మొదట ఒక లాగ్-మెల్ స్పెక్ట్రోగ్రామ్‌గా మార్చబడుతుంది. ఈ స్పెక్ట్రోగ్రామ్ ఆపై ఒక Transformer ఎన్‌కోడర్ నెట్‌వర్క్ ద్వారా పంపబడుతుంది. + +2. ఒక **డీకోడర్** ఎన్‌కోడ్ చేయబడిన ఆడియో ప్రాతినిధ్యాన్ని తీసుకుని మరియు అనుగుణమైన టెక్స్ట్ టోకెన్‌లను ఆటోరిగ్రెసివ్‌గా అంచనా వేస్తుంది. ఇది ఒక ప్రామాణిక Transformer డీకోడర్, ఇది మునుపటి టోకెన్‌లు మరియు ఎన్‌కోడర్ అవుట్‌పుట్ ఆధారంగా తదుపరి టెక్స్ట్ టోకెన్‌ను అంచనా వేయడానికి శిక్షణ పొందింది. డీకోడర్ ఇన్‌పుట్ ప్రారంభంలో ప్రత్యేక టోకెన్‌లు ట్రాన్స్‌క్రిప్షన్, అనువాదం, లేదా భాషా గుర్తింపు వంటి నిర్దిష్ట పనుల వైపు మోడల్‌ను నడిపించడానికి ఉపయోగించబడతాయి. + +Whisper వెబ్ నుండి సేకరించిన 680,000 గంటల లేబుల్ చేయబడిన ఆడియో డేటా యొక్క భారీ మరియు విభిన్న డేటాసెట్‌పై ముందే శిక్షణ పొందింది. ఈ భారీ-స్థాయి, బలహీనంగా పర్యవేక్షించబడిన ప్రీ-ట్రైనింగ్ దాని బలమైన జీరో-షాట్ పనితీరుకు అనేక భాషలు మరియు పనులలో కీలకం. + +ఇప్పుడు Whisper ముందే శిక్షణ పొందింది, మీరు దానిని జీరో-షాట్ ఇన్ఫరెన్స్ కోసం నేరుగా ఉపయోగించవచ్చు లేదా ఆటోమేటిక్ స్పీచ్ రికగ్నిషన్ లేదా స్పీచ్ ట్రాన్స్‌లేషన్ వంటి నిర్దిష్ట పనులపై మెరుగైన పనితీరు కోసం మీ డేటాపై ఫైన్‌ట్యూన్ చేయవచ్చు! + + + +Whisperలోని కీలకమైన ఆవిష్కరణ దాని శిక్షణ, ఇది ఇంటర్నెట్ నుండి అపూర్వమైన స్థాయిలో విభిన్న, బలహీనంగా పర్యవేక్షించబడిన ఆడియో డేటాపై జరిగింది. ఇది పని-నిర్దిష్ట ఫైన్‌ట్యూనింగ్ లేకుండా విభిన్న భాషలు, యాసలు మరియు పనులకు అసాధారణంగా బాగా సాధారణీకరించడానికి అనుమతిస్తుంది. + + + +### ఆటోమేటిక్ స్పీచ్ రికగ్నిషన్ + +ఆటోమేటిక్ స్పీచ్ రికగ్నిషన్ కోసం ముందే శిక్షణ పొందిన మోడల్‌ను ఉపయోగించడానికి, మీరు దాని పూర్తి ఎన్‌కోడర్-డీకోడర్ నిర్మాణాన్ని ఉపయోగించుకుంటారు. ఎన్‌కోడర్ ఆడియో ఇన్‌పుట్‌ను ప్రాసెస్ చేస్తుంది, మరియు డీకోడర్ ట్రాన్స్‌క్రిప్ట్‌ను టోకెన్ ద్వారా టోకెన్ ఆటోరిగ్రెసివ్‌గా ఉత్పత్తి చేస్తుంది. ఫైన్-ట్యూనింగ్ చేసేటప్పుడు, ఆడియో ఇన్‌పుట్ ఆధారంగా సరైన టెక్స్ట్ టోకెన్‌లను అంచనా వేయడానికి మోడల్ సాధారణంగా ఒక ప్రామాణిక సీక్వెన్స్-టు-సీక్వెన్స్ నష్టాన్ని (క్రాస్-ఎంట్రోపీ వంటివి) ఉపయోగించి శిక్షణ పొందుతుంది. + +ఇన్ఫరెన్స్ కోసం ఫైన్-ట్యూన్ చేసిన మోడల్‌ను ఉపయోగించడానికి సులభమైన మార్గం `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.'} +``` + +ఆటోమేటిక్ స్పీచ్ రికగ్నిషన్‌లో మీ నైపుణ్యాన్ని ప్రయత్నించడానికి సిద్ధంగా ఉన్నారా? Whisperను ఫైన్‌ట్యూన్ చేయడం మరియు దానిని ఇన్ఫరెన్స్ కోసం ఉపయోగించడం ఎలాగో తెలుసుకోవడానికి మా పూర్తి [automatic speech recognition guide](https://huggingface.co/docs/transformers/tasks/asr)ను చూడండి! + +### కంప్యూటర్ విజన్ + +ఇప్పుడు మనం కంప్యూటర్ విజన్ పనులకు వెళ్దాం, ఇవి చిత్రాలు లేదా వీడియోల నుండి దృశ్య సమాచారాన్ని అర్థం చేసుకోవడం మరియు వ్యాఖ్యానించడంతో వ్యవహరిస్తాయి. + +కంప్యూటర్ విజన్ పనులను సంప్రదించడానికి రెండు మార్గాలు ఉన్నాయి: + +1. ఒక చిత్రాన్ని ప్యాచ్‌ల క్రమంగా విభజించి మరియు వాటిని ఒక Transformerతో సమాంతరంగా ప్రాసెస్ చేయండి. +2. [ConvNeXT](https://huggingface.co/docs/transformers/model_doc/convnext) వంటి ఆధునిక CNNను ఉపయోగించండి, ఇది కన్వల్యూషనల్ లేయర్‌లపై ఆధారపడుతుంది కానీ ఆధునిక నెట్‌వర్క్ డిజైన్‌లను అనుసరిస్తుంది. + + + +మూడవ విధానం Transformersను కన్వల్యూషన్‌లతో మిళితం చేస్తుంది (ఉదాహరణకు, [Convolutional Vision Transformer](https://huggingface.co/docs/transformers/model_doc/cvt) లేదా [LeViT](https://huggingface.co/docs/transformers/model_doc/levit)). మనం వాటిని చర్చించము ఎందుకంటే అవి ఇక్కడ మనం పరిశీలించే రెండు విధానాలను మిళితం చేస్తాయి. + + + +ViT మరియు ConvNeXT సాధారణంగా ఇమేజ్ వర్గీకరణ కోసం ఉపయోగించబడతాయి, కానీ వస్తువు గుర్తింపు, సెగ్మెంటేషన్, మరియు డెప్త్ ఎస్టిమేషన్ వంటి ఇతర దృష్టి పనుల కోసం, మనం వరుసగా DETR, Mask2Former మరియు GLPNలను పరిశీలిస్తాము; ఈ మోడల్స్ ఆ పనులకు బాగా సరిపోతాయి. + +### ఇమేజ్ వర్గీకరణ + +ఇమేజ్ వర్గీకరణ అనేది ప్రాథమిక కంప్యూటర్ విజన్ పనులలో ఒకటి. వివిధ మోడల్ ఆర్కిటెక్చర్లు ఈ సమస్యను ఎలా సంప్రదిస్తాయో చూద్దాం. + +ViT మరియు ConvNeXT రెండూ ఇమేజ్ వర్గీకరణ కోసం ఉపయోగించబడతాయి; ప్రధాన వ్యత్యాసం ఏమిటంటే ViT ఒక అటెన్షన్ మెకానిజంను ఉపయోగిస్తుంది, అయితే ConvNeXT కన్వల్యూషన్‌లను ఉపయోగిస్తుంది. + +[ViT](https://huggingface.co/docs/transformers/model_doc/vit) కన్వల్యూషన్‌లను పూర్తిగా ఒక స్వచ్ఛమైన Transformer ఆర్కిటెక్చర్‌తో భర్తీ చేస్తుంది. మీరు అసలు Transformerతో పరిచయం ఉంటే, మీరు ఇప్పటికే ViTను అర్థం చేసుకోవడానికి చాలా దూరం వచ్చారు. + +
+ +
+ +ViT ప్రవేశపెట్టిన ప్రధాన మార్పు చిత్రాలు ఒక Transformerకు ఎలా ఇవ్వబడతాయి అనే దానిలో ఉంది: + +1. ఒక చిత్రం చదరపు అతివ్యాప్తి లేని ప్యాచ్‌లుగా విభజించబడుతుంది, ప్రతి ఒక్కటి ఒక వెక్టర్ లేదా *ప్యాచ్ ఎంబెడ్డింగ్‌*గా మార్చబడుతుంది. ప్యాచ్ ఎంబెడ్డింగ్‌లు ఒక కన్వల్యూషనల్ 2D లేయర్ నుండి రూపొందించబడతాయి, ఇది సరైన ఇన్‌పుట్ డైమెన్షన్‌లను సృష్టిస్తుంది (ఇది బేస్ Transformer కోసం ప్రతి ప్యాచ్ ఎంబెడ్డింగ్‌కు 768 విలువలు). మీరు ఒక 224x224 పిక్సెల్ చిత్రం కలిగి ఉంటే, మీరు దానిని 196 16x16 ఇమేజ్ ప్యాచ్‌లుగా విభజించవచ్చు. టెక్స్ట్ పదాలుగా టోకనైజ్ చేయబడినట్లే, ఒక చిత్రం ప్యాచ్‌ల క్రమంగా "టోకనైజ్" చేయబడుతుంది. + +2. ఒక _లెర్నబుల్ ఎంబెడ్డింగ్_ - ఒక ప్రత్యేక `[CLS]` టోకెన్ - BERT వలె ప్యాచ్ ఎంబెడ్డింగ్‌ల ప్రారంభంలో జోడించబడుతుంది. `[CLS]` టోకెన్ యొక్క చివరి దాచిన స్థితి జతచేయబడిన వర్గీకరణ హెడ్‌కు ఇన్‌పుట్‌గా ఉపయోగించబడుతుంది; ఇతర అవుట్‌పుట్‌లు విస్మరించబడతాయి. ఈ టోకెన్ మోడల్‌కు చిత్రం యొక్క ప్రాతినిధ్యాన్ని ఎలా ఎన్‌కోడ్ చేయాలో నేర్చుకోవడంలో సహాయపడుతుంది. + +3. ప్యాచ్ మరియు లెర్నబుల్ ఎంబెడ్డింగ్‌లకు జోడించాల్సిన చివరి విషయం _పొజిషన్ ఎంబెడ్డింగ్‌లు_ ఎందుకంటే మోడల్‌కు ఇమేజ్ ప్యాచ్‌లు ఎలా ఆర్డర్ చేయబడ్డాయో తెలియదు. పొజిషన్ ఎంబెడ్డింగ్‌లు కూడా లెర్నబుల్ మరియు ప్యాచ్ ఎంబెడ్డింగ్‌ల వలె అదే పరిమాణాన్ని కలిగి ఉంటాయి. చివరగా, అన్ని ఎంబెడ్డింగ్‌లు Transformer ఎన్‌కోడర్‌కు పంపబడతాయి. + +4. అవుట్‌పుట్, ప్రత్యేకంగా `[CLS]` టోకెన్‌తో ఉన్న అవుట్‌పుట్ మాత్రమే, ఒక మల్టీలేయర్ పెర్సెప్ట్రాన్ హెడ్ (MLP)కు పంపబడుతుంది. ViT యొక్క ప్రీ-ట్రైనింగ్ లక్ష్యం కేవలం వర్గీకరణ. ఇతర వర్గీకరణ హెడ్‌ల వలె, MLP హెడ్ అవుట్‌పుట్‌ను తరగతి లేబుల్స్‌పై లాజిట్స్‌గా మార్చి మరియు అత్యంత సంభావ్య తరగతిని కనుగొనడానికి క్రాస్-ఎంట్రోపీ నష్టాన్ని లెక్కిస్తుంది. + +ఇమేజ్ వర్గీకరణలో మీ నైపుణ్యాన్ని ప్రయత్నించడానికి సిద్ధంగా ఉన్నారా? ViTను ఫైన్-ట్యూన్ చేయడం మరియు దానిని ఇన్ఫరెన్స్ కోసం ఉపయోగించడం ఎలాగో తెలుసుకోవడానికి మా పూర్తి [image classification guide](https://huggingface.co/docs/transformers/tasks/image_classification)ను చూడండి! + + + +ViT మరియు BERT మధ్య సమాంతరాన్ని గమనించండి: రెండూ మొత్తం ప్రాతినిధ్యాన్ని సంగ్రహించడానికి ఒక ప్రత్యేక టోకెన్ ([CLS])ను ఉపయోగిస్తాయి, రెండూ వాటి ఎంబెడ్డింగ్‌లకు స్థాన సమాచారాన్ని జోడిస్తాయి, మరియు రెండూ టోకెన్‌లు/ప్యాచ్‌ల క్రమాన్ని ప్రాసెస్ చేయడానికి ఒక Transformer ఎన్‌కోడర్‌ను ఉపయోగిస్తాయి. + + diff --git a/chapters/te/chapter1/6.mdx b/chapters/te/chapter1/6.mdx new file mode 100644 index 000000000..d9939b20b --- /dev/null +++ b/chapters/te/chapter1/6.mdx @@ -0,0 +1,206 @@ + + +# ట్రాన్స్‌ఫార్మర్ ఆర్కిటెక్చర్లు[[transformer-architectures]] + +మునుపటి విభాగాలలో, మేము సాధారణ Transformer ఆర్కిటెక్చర్‌ను పరిచయం చేసాము మరియు ఈ నమూనాలు వివిధ పనులను ఎలా పరిష్కరించగలవో అన్వేషించాము. ఇప్పుడు, Transformer నమూనాల యొక్క మూడు ప్రధాన నిర్మాణ వైవిధ్యాలను నిశితంగా పరిశీలిద్దాం మరియు ప్రతి ఒక్కటి ఎప్పుడు ఉపయోగించాలో అర్థం చేసుకుందాం. ఆపై, ఆ నిర్మాణాలు వేర్వేరు భాషా పనులకు ఎలా వర్తింపజేయబడతాయో చూశాము. + +ఈ విభాగంలో, మేము Transformer నమూనాల యొక్క మూడు ప్రధాన నిర్మాణ వైవిధ్యాలను లోతుగా పరిశీలించబోతున్నాము మరియు ప్రతి ఒక్కటి ఎప్పుడు ఉపయోగించాలో అర్థం చేసుకుంటాము. + + + +చాలా Transformer నమూనాలు మూడు నిర్మాణాలలో ఒకదాన్ని ఉపయోగిస్తాయని గుర్తుంచుకోండి: ఎన్‌కోడర్-మాత్రమే, డీకోడర్-మాత్రమే లేదా ఎన్‌కోడర్-డీకోడర్ (సీక్వెన్స్-టు-సీక్వెన్స్). ఈ తేడాలను అర్థం చేసుకోవడం మీ నిర్దిష్ట పనికి సరైన నమూనాను ఎంచుకోవడంలో మీకు సహాయపడుతుంది. + + + +## ఎన్‌కోడర్ నమూనాలు[[encoder-models]] + + + +ఎన్‌కోడర్ నమూనాలు Transformer నమూనా యొక్క ఎన్‌కోడర్‌ను మాత్రమే ఉపయోగిస్తాయి. ప్రతి దశలో, శ్రద్ధా పొరలు ప్రారంభ వాక్యంలోని అన్ని పదాలను యాక్సెస్ చేయగలవు. ఈ నమూనాలు తరచుగా "ద్విదిశాత్మక" శ్రద్ధను కలిగి ఉన్నాయని వర్గీకరించబడతాయి మరియు తరచుగా ఆటో-ఎన్‌కోడింగ్ నమూనాలు అని పిలువబడతాయి. + +ఈ నమూనాల యొక్క ప్రీ-ట్రైనింగ్ సాధారణంగా ఇచ్చిన వాక్యాన్ని ఏదో ఒక విధంగా పాడు చేయడం (ఉదాహరణకు, యాదృచ్ఛిక పదాలను మాస్క్ చేయడం ద్వారా) మరియు ప్రారంభ వాక్యాన్ని కనుగొనడం లేదా పునర్నిర్మించడం నమూనా యొక్క పని. + +వాక్య వర్గీకరణ, పేరున్న ఎంటిటీ గుర్తింపు (మరియు సాధారణంగా పద వర్గీకరణ), మరియు సంగ్రాహక ప్రశ్న-సమాధానం వంటి పూర్తి వాక్యం యొక్క అవగాహన అవసరమయ్యే పనులకు ఎన్‌కోడర్ నమూనాలు ఉత్తమంగా సరిపోతాయి. + + + +[How 🤗 Transformers solve tasks](/chapter1/5), లో మనం చూసినట్లుగా, BERT వంటి ఎన్‌కోడర్ నమూనాలు టెక్స్ట్‌ను అర్థం చేసుకోవడంలో రాణిస్తాయి ఎందుకంటే అవి రెండు దిశలలోని మొత్తం సందర్భాన్ని చూడగలవు. ఇది మొత్తం ఇన్‌పుట్ యొక్క గ్రహణశక్తి ముఖ్యమైన పనులకు వాటిని పరిపూర్ణంగా చేస్తుంది. + + + +ఈ నమూనాల కుటుంబం యొక్క ప్రతినిధులు: + +- [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]] + + + +డీకోడర్ నమూనాలు Transformer నమూనా యొక్క డీకోడర్‌ను మాత్రమే ఉపయోగిస్తాయి. ప్రతి దశలో, ఇచ్చిన పదం కోసం శ్రద్ధా పొరలు వాక్యంలో దాని ముందు ఉన్న పదాలను మాత్రమే యాక్సెస్ చేయగలవు. ఈ నమూనాలను తరచుగా ఆటో-రిగ్రెసివ్ నమూనాలు అని పిలుస్తారు. + +డీకోడర్ నమూనాల యొక్క ప్రీ-ట్రైనింగ్ సాధారణంగా వాక్యంలోని తదుపరి పదాన్ని అంచనా వేయడం చుట్టూ తిరుగుతుంది. + +ఈ నమూనాలు టెక్స్ట్ జనరేషన్ వంటి పనులకు ఉత్తమంగా సరిపోతాయి. + + + +GPT వంటి డీకోడర్ నమూనాలు ఒక సమయంలో ఒక టోకెన్‌ను అంచనా వేయడం ద్వారా టెక్స్ట్‌ను ఉత్పత్తి చేయడానికి రూపొందించబడ్డాయి. [How 🤗 Transformers solve tasks](/chapter1/5) లో మనం అన్వేషించినట్లుగా, అవి మునుపటి టోకెన్‌లను మాత్రమే చూడగలవు, ఇది సృజనాత్మక టెక్స్ట్ జనరేషన్‌కు వాటిని అద్భుతంగా చేస్తుంది కానీ ద్విదిశాత్మక అవగాహన అవసరమయ్యే పనులకు అంత ఆదర్శవంతంగా ఉండదు. + + + +ఈ నమూనాల కుటుంబం యొక్క ప్రతినిధులు: + +- [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) + +### ఆధునిక లార్జ్ లాంగ్వేజ్ మోడల్స్ (LLMలు) + +చాలా ఆధునిక Large Language Models (LLMలు) డీకోడర్-మాత్రమే నిర్మాణాన్ని ఉపయోగిస్తాయి. ఈ నమూనాలు గత కొన్ని సంవత్సరాలుగా పరిమాణం మరియు సామర్థ్యాలలో నాటకీయంగా పెరిగాయి, అతిపెద్ద నమూనాలలో కొన్ని వందల బిలియన్ల పారామితులు ఉన్నాయి. + +ఆధునిక LLMలు సాధారణంగా రెండు దశలలో శిక్షణ పొందుతాయి: + +1. **ప్రీ-ట్రైనింగ్**: నమూనా విస్తారమైన టెక్స్ట్ డేటాపై తదుపరి టోకెన్‌ను అంచనా వేయడం నేర్చుకుంటుంది +2. **ఇన్‌స్ట్రక్షన్ ట్యూనింగ్**: నమూనా సూచనలను అనుసరించడానికి మరియు సహాయకరమైన ప్రతిస్పందనలను ఉత్పత్తి చేయడానికి ఫైన్-ట్యూన్ చేయబడుతుంది + +ఈ విధానం అనేక రకాల అంశాలు మరియు పనులలో మానవ-లాంటి టెక్స్ట్‌ను అర్థం చేసుకుని, ఉత్పత్తి చేయగల నమూనాలకు దారితీసింది. + +#### ఆధునిక LLMల యొక్క ముఖ్య సామర్థ్యాలు + +ఆధునిక డీకోడర్-ఆధారిత LLMలు ఆకట్టుకునే సామర్థ్యాలను ప్రదర్శించాయి: + +| సామర్థ్యం | వివరణ | ఉదాహరణ | +| -------------------- | --------------------------------------------------- | -------------------------------------------------------- | +| టెక్స్ట్ జనరేషన్ | పొందికైన మరియు సందర్భోచితమైన టెక్స్ట్‌ను సృష్టించడం | వ్యాసాలు, కథలు లేదా ఈమెయిల్‌లు రాయడం | +| సారాంశీకరణ | పొడవైన పత్రాలను చిన్న వెర్షన్‌లుగా కుదించడం | నివేదికల కార్యనిర్వాహక సారాంశాలను సృష్టించడం | +| అనువాదం | భాషల మధ్య టెక్స్ట్‌ను మార్చడం | ఇంగ్లీష్‌ను స్పానిష్‌లోకి అనువదించడం | +| ప్రశ్న-సమాధానం | వాస్తవ ప్రశ్నలకు సమాధానాలు అందించడం | "ఫ్రాన్స్ రాజధాని ఏది?" | +| కోడ్ జనరేషన్ | కోడ్ స్నిప్పెట్‌లను రాయడం లేదా పూర్తి చేయడం | వివరణ ఆధారంగా ఒక ఫంక్షన్‌ను సృష్టించడం | +| తార్కికం (Reasoning) | సమస్యలను దశలవారీగా పరిష్కరించడం | గణిత సమస్యలు లేదా తార్కిక పజిల్స్‌ను పరిష్కరించడం | +| ఫ్యూ-షాట్ లెర్నింగ్ | ప్రాంప్ట్‌లోని కొన్ని ఉదాహరణల నుండి నేర్చుకోవడం | కేవలం 2-3 ఉదాహరణలు చూసిన తర్వాత టెక్స్ట్‌ను వర్గీకరించడం | + +మీరు బ్రౌజర్‌లో నేరుగా హబ్‌లోని నమూనా రిపో పేజీల ద్వారా డీకోడర్-ఆధారిత LLMలతో ప్రయోగాలు చేయవచ్చు. ఇక్కడ క్లాసిక్ [GPT-2](https://huggingface.co/openai-community/gpt2) (OpenAI యొక్క అత్యుత్తమ ఓపెన్ సోర్స్ నమూనా!) తో ఒక ఉదాహరణ ఉంది: + + + +## సీక్వెన్స్-టు-సీక్వెన్స్ నమూనాలు[[sequence-to-sequence-models]] + + + +ఎన్‌కోడర్-డీకోడర్ నమూనాలు (సీక్వెన్స్-టు-సీక్వెన్స్ నమూనాలు అని కూడా పిలుస్తారు) Transformer నిర్మాణం యొక్క రెండు భాగాలను ఉపయోగిస్తాయి. ప్రతి దశలో, ఎన్‌కోడర్ యొక్క శ్రద్ధా పొరలు ప్రారంభ వాక్యంలోని అన్ని పదాలను యాక్సెస్ చేయగలవు, అయితే డీకోడర్ యొక్క శ్రద్ధా పొరలు ఇన్‌పుట్‌లో ఇచ్చిన పదం ముందు ఉన్న పదాలను మాత్రమే యాక్సెస్ చేయగలవు. + +ఈ నమూనాల యొక్క ప్రీ-ట్రైనింగ్ వివిధ రూపాలను తీసుకోవచ్చు, కానీ ఇది తరచుగా ఇన్‌పుట్ ఏదో ఒక విధంగా పాడు చేయబడిన వాక్యాన్ని పునర్నిర్మించడం (ఉదాహరణకు యాదృచ్ఛిక పదాలను మాస్క్ చేయడం ద్వారా) ఉంటుంది. T5 నమూనా యొక్క ప్రీ-ట్రైనింగ్ యాదృచ్ఛిక టెక్స్ట్ స్పాన్‌లను (ఇవి అనేక పదాలను కలిగి ఉండవచ్చు) ఒకే మాస్క్ ప్రత్యేక టోకెన్‌తో భర్తీ చేయడం, మరియు అప్పుడు ఈ మాస్క్ టోకెన్ భర్తీ చేసే టెక్స్ట్‌ను అంచనా వేయడం పని. + +సీక్వెన్స్-టు-సీక్వెన్స్ నమూనాలు సారాంశీకరణ, అనువాదం, లేదా సృజనాత్మక ప్రశ్న-సమాధానం వంటి ఇచ్చిన ఇన్‌పుట్‌పై ఆధారపడి కొత్త వాక్యాలను ఉత్పత్తి చేయడం చుట్టూ తిరిగే పనులకు ఉత్తమంగా సరిపోతాయి. + + + +[How 🤗 Transformers solve tasks](/chapter1/5),లో మనం చూసినట్లుగా, BART మరియు T5 వంటి ఎన్‌కోడర్-డీకోడర్ నమూనాలు రెండు నిర్మాణాల యొక్క బలాలను మిళితం చేస్తాయి. ఎన్‌కోడర్ ఇన్‌పుట్ యొక్క లోతైన ద్విదిశాత్మక అవగాహనను అందిస్తుంది, అయితే డీకోడర్ తగిన అవుట్‌పుట్ టెక్స్ట్‌ను ఉత్పత్తి చేస్తుంది. ఇది ఒక సీక్వెన్స్‌ను మరొకదానికి మార్చే పనులకు, అనువాదం లేదా సారాంశీకరణ వంటి వాటికి వాటిని పరిపూర్ణంగా చేస్తుంది. + + + +### ఆచరణాత్మక అనువర్తనాలు + +సీక్వెన్స్-టు-సీక్వెన్స్ నమూనాలు అర్థాన్ని కాపాడుకుంటూ ఒక రూపంలోని టెక్స్ట్‌ను మరొక రూపంలోకి మార్చాల్సిన పనులలో రాణిస్తాయి. కొన్ని ఆచరణాత్మక అనువర్తనాలు: + +| అనువర్తనం | వివరణ | ఉదాహరణ నమూనా | +| ------------------------ | ----------------------------------------------- | ------------ | +| యంత్ర అనువాదం | భాషల మధ్య టెక్స్ట్‌ను మార్చడం | Marian, T5 | +| టెక్స్ట్ సారాంశీకరణ | పొడవైన టెక్స్ట్‌ల క్లుప్త సారాంశాలను సృష్టించడం | BART, T5 | +| డేటా-టు-టెక్స్ట్ జనరేషన్ | నిర్మాణాత్మక డేటాను సహజ భాషలోకి మార్చడం | T5 | +| వ్యాకరణ దిద్దుబాటు | టెక్స్ట్‌లోని వ్యాకరణ దోషాలను సరిచేయడం | T5 | + +ఈ నమూనాల కుటుంబం యొక్క ప్రతినిధులు: + + + +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]] + +ఒక నిర్దిష్ట NLP పనిలో పనిచేస్తున్నప్పుడు, మీరు ఏ నిర్మాణాన్ని ఉపయోగించాలో ఎలా నిర్ణయిస్తారు? ఇక్కడ ఒక శీఘ్ర మార్గదర్శి ఉంది: + +| పని | సూచించిన నిర్మాణం | ఉదాహరణలు | +| ------------------------------------ | -------------------------- | ------------- | +| టెక్స్ట్ వర్గీకరణ (భావోద్వేగం, అంశం) | Encoder | BERT, RoBERTa | +| టెక్స్ట్ ఉత్పత్తి (సృజనాత్మక రచన) | Decoder | GPT, LLaMA | +| అనువాదం | Encoder-Decoder | T5, BART | +| సంక్షిప్తీకరణ | Encoder-Decoder | BART, T5 | +| పేరుతో గుర్తింపు | Encoder | BERT, RoBERTa | +| ప్రశ్నలకు సమాధానం (ఎక్స్‌ట్రాక్టివ్) | Encoder | BERT, RoBERTa | +| ప్రశ్నలకు సమాధానం (జనరేటివ్) | Encoder-Decoder or Decoder | T5, GPT | +| సంభాషణ AI | Decoder | GPT, LLaMA | + + + +ఏ నమూనాను ఉపయోగించాలో సందేహంలో ఉన్నప్పుడు, పరిగణించండి: + +1. మీ పనికి ఎలాంటి అవగాహన అవసరం? (ద్విదిశాత్మక లేదా ఏకదిశాత్మక) +2. మీరు కొత్త టెక్స్ట్‌ను ఉత్పత్తి చేస్తున్నారా లేదా ఉన్న టెక్స్ట్‌ను విశ్లేషిస్తున్నారా? +3. మీరు ఒక సీక్వెన్స్‌ను మరొకదానికి మార్చాల్సిన అవసరం ఉందా? + +ఈ ప్రశ్నలకు సమాధానాలు మిమ్మల్ని సరైన నిర్మాణం వైపు నడిపిస్తాయి. + + + +## LLMల పరిణామం + +పెద్ద భాషా నమూనాలు ఇటీవలి సంవత్సరాలలో వేగంగా అభివృద్ధి చెందాయి, ప్రతి తరం సామర్థ్యాలలో గణనీయమైన మెరుగుదలలను తీసుకువచ్చింది. + +## అటెన్షన్ మెకానిజమ్స్[[attention-mechanisms]] + +చాలా ట్రాన్స్‌ఫార్మర్ నమూనాలు పూర్తి శ్రద్ధను ఉపయోగిస్తాయి, అంటే శ్రద్ధా మాత్రిక చతురస్రాకారంలో ఉంటుంది. మీకు పొడవైన టెక్స్ట్‌లు ఉన్నప్పుడు ఇది ఒక పెద్ద గణన అవరోధంగా ఉంటుంది. లాంగ్‌ఫార్మర్ మరియు రిఫార్మర్ అనే నమూనాలు మరింత సమర్థవంతంగా ఉండటానికి ప్రయత్నిస్తాయి మరియు శిక్షణను వేగవంతం చేయడానికి శ్రద్ధా మాత్రిక యొక్క స్పాన్ వెర్షన్‌ను ఉపయోగిస్తాయి. + + + +ప్రామాణిక శ్రద్ధా యంత్రాంగాలు O(n²) యొక్క గణన సంక్లిష్టతను కలిగి ఉంటాయి, ఇక్కడ n సీక్వెన్స్ పొడవు. చాలా పొడవైన సీక్వెన్స్‌లకు ఇది సమస్యాత్మకంగా మారుతుంది. కింద పేర్కొన్న ప్రత్యేక శ్రద్ధా యంత్రాంగాలు ఈ పరిమితిని పరిష్కరించడంలో సహాయపడతాయి. + + + +### LSH అటెన్షన్ + +[Reformer](https://huggingface.co/docs/transformers/model_doc/reformer) LSH అటెన్షన్ ఉపయోగిస్తుంది. సాఫ్ట్‌మాక్స్(QK^t)లో, మాత్రిక QK^t యొక్క అతిపెద్ద అంశాలు మాత్రమే (సాఫ్ట్‌మాక్స్ డైమెన్షన్‌లో) ఉపయోగకరమైన సహకారం అందిస్తాయి. కాబట్టి Q లోని ప్రతి క్వెరీ q కోసం, మనం K లో q కు దగ్గరగా ఉన్న కీలను మాత్రమే పరిగణించవచ్చు. q మరియు k దగ్గరగా ఉన్నాయో లేదో నిర్ధారించడానికి ఒక హాష్ ఫంక్షన్ ఉపయోగించబడుతుంది. ప్రస్తుత టోకెన్‌ను మాస్క్ చేయడానికి శ్రద్ధా మాస్క్ సవరించబడింది (మొదటి స్థానంలో తప్ప), ఎందుకంటే ఇది సమానమైన క్వెరీ మరియు కీని ఇస్తుంది (కాబట్టి ఒకదానికొకటి చాలా పోలి ఉంటుంది). హాష్ కొంచెం యాదృచ్ఛికంగా ఉండగలదు కాబట్టి, ఆచరణలో అనేక హాష్ ఫంక్షన్లు ఉపయోగించబడతాయి (n_rounds పారామితి ద్వారా నిర్ధారించబడతాయి) మరియు తరువాత అవి సగటు చేయబడతాయి. + +### లోకల్ అటెన్షన్ + +[Longformer](https://huggingface.co/docs/transformers/model_doc/longformer) స్థానిక శ్రద్ధను ఉపయోగిస్తుంది: తరచుగా, స్థానిక సందర్భం (ఉదా., ఎడమ మరియు కుడి వైపున ఉన్న రెండు టోకెన్‌లు ఏమిటి?) ఒక నిర్దిష్ట టోకెన్ కోసం చర్య తీసుకోవడానికి సరిపోతుంది. అలాగే, చిన్న విండో ఉన్న శ్రద్ధా పొరలను పేర్చడం ద్వారా, చివరి పొర కేవలం విండోలోని టోకెన్‌ల కంటే ఎక్కువ గ్రహణ క్షేత్రాన్ని కలిగి ఉంటుంది, ఇది మొత్తం వాక్యం యొక్క ప్రాతినిధ్యాన్ని నిర్మించడానికి వీలు కల్పిస్తుంది. + +కొన్ని ముందుగా ఎంచుకున్న ఇన్‌పుట్ టోకెన్‌లకు గ్లోబల్ అటెన్షన్ కూడా ఇవ్వబడుతుంది: ఆ కొన్ని టోకెన్‌ల కోసం, శ్రద్ధా మాత్రిక అన్ని టోకెన్‌లను యాక్సెస్ చేయగలదు మరియు ఈ ప్రక్రియ సుష్టంగా ఉంటుంది: అన్ని ఇతర టోకెన్‌లు ఆ నిర్దిష్ట టోకెన్‌లకు యాక్సెస్ కలిగి ఉంటాయి (వాటి స్థానిక విండోలోని వాటితో పాటు). ఇది పేపర్‌లోని ఫిగర్ 2డిలో చూపబడింది, ఒక నమూనా శ్రద్ధా మాస్క్ కోసం కింద చూడండి: + +
+ +
+ +తక్కువ పారామితులతో ఆ Attention matrix ఉపయోగించడం వలన నమూనా పెద్ద సీక్వెన్స్ పొడవు ఉన్న ఇన్‌పుట్‌లను కలిగి ఉండటానికి వీలు కల్పిస్తుంది. + +### యాక్సియల్ పొజిషనల్ ఎన్‌కోడింగ్స్ + +[Reformer](https://huggingface.co/docs/transformers/model_doc/reformer) యాక్సియల్ పొజిషనల్ ఎన్‌కోడింగ్‌లను ఉపయోగిస్తుంది: సాంప్రదాయ ట్రాన్స్‌ఫార్మర్ నమూనాలలో, పొజిషనల్ ఎన్‌కోడింగ్ E అనేది \(l\) బై \(d\) పరిమాణంలో ఒక మాత్రిక, ఇక్కడ \(l\) సీక్వెన్స్ పొడవు మరియు \(d\) దాగి ఉన్న స్థితి యొక్క డైమెన్షన్. మీకు చాలా పొడవైన టెక్స్ట్‌లు ఉంటే, ఈ మాత్రిక చాలా పెద్దదిగా ఉండవచ్చు మరియు GPUలో చాలా ఎక్కువ స్థలాన్ని తీసుకుంటుంది. దానిని తగ్గించడానికి, యాక్సియల్ పొజిషనల్ ఎన్‌కోడింగ్‌లు ఆ పెద్ద మాత్రిక E ని రెండు చిన్న మాత్రికలు E1 మరియు E2 గా విభజించడం, వాటి డైమెన్షన్లు \(l*{1} \times d*{1}\) మరియు \(l*{2} \times d*{2}\), ఇక్కడ \(l*{1} \times l*{2} = l\) మరియు \(d*{1} + d*{2} = d\) (పొడవుల కోసం గుణకారంతో, ఇది చాలా చిన్నదిగా ముగుస్తుంది). E లో సమయ దశ \(j\) కోసం ఎంబెడ్డింగ్ E1 లో సమయ దశ \(j % l1\) మరియు E2 లో \(j // l1\) కోసం ఎంబెడ్డింగ్‌లను కలపడం ద్వారా పొందబడుతుంది. + +## ముగింపు[[conclusion]] + +ఈ విభాగంలో, మేము మూడు ప్రధాన Transformer నిర్మాణాలను మరియు కొన్ని ప్రత్యేక శ్రద్ధా యంత్రాంగాలను అన్వేషించాము. మీ నిర్దిష్ట NLP పని కోసం సరైన నమూనాను ఎంచుకోవడానికి ఈ నిర్మాణ తేడాలను అర్థం చేసుకోవడం చాలా ముఖ్యం. + +కోర్సులో మనం ముందుకు సాగుతున్నప్పుడు, మీరు ఈ విభిన్న నిర్మాణాలతో ప్రత్యక్ష అనుభవాన్ని పొందుతారు మరియు మీ నిర్దిష్ట అవసరాలకు వాటిని ఎలా ఫైన్-ట్యూన్ చేయాలో నేర్చుకుంటారు. తదుపరి విభాగంలో, మనం ఈ నమూనాలలో ఉన్న కొన్ని పరిమితులు మరియు పక్షపాతాలను పరిశీలిస్తాము, వాటిని అమలు చేస్తున్నప్పుడు మీరు తెలుసుకోవాలి. diff --git a/chapters/te/chapter1/7.mdx b/chapters/te/chapter1/7.mdx new file mode 100644 index 000000000..087f18d7b --- /dev/null +++ b/chapters/te/chapter1/7.mdx @@ -0,0 +1,283 @@ + + +# గ్రేడ్ లేని క్విజ్[[ungraded-quiz]] + + + +ఇప్పటివరకు, ఈ అధ్యాయం చాలా విషయాలను కవర్ చేసింది! మీరు అన్ని వివరాలను గ్రహించలేకపోయినా చింతించకండి, కానీ క్విజ్‌తో ఇప్పటివరకు మీరు నేర్చుకున్న వాటిని సమీక్షించుకోవడం మంచిది. + +ఈ క్విజ్‌కు గ్రేడ్ లేదు, కాబట్టి మీరు దీన్ని మీకు కావలసినన్ని సార్లు ప్రయత్నించవచ్చు. కొన్ని ప్రశ్నలతో మీరు ఇబ్బంది పడితే, చిట్కాలను అనుసరించి, మెటీరియల్‌ను మళ్ళీ చూడండి. సర్టిఫికేషన్ పరీక్షలో ఈ మెటీరియల్‌పై మిమ్మల్ని మళ్లీ క్విజ్ చేయబడుతుంది. + +### 1. హబ్‌ను అన్వేషించండి మరియు `roberta-large-mnli` చెక్‌పాయింట్ కోసం చూడండి. ఇది ఏ పనిని చేస్తుంది? + +ఇప్పటివరకు, ఈ అధ్యాయం చాలా విషయాలను కవర్ చేసింది! మీరు అన్ని వివరాలను గ్రహించలేకపోయినా చింతించకండి, కానీ క్విజ్‌తో ఇప్పటివరకు మీరు నేర్చుకున్న వాటిని సమీక్షించుకోవడం మంచిది. + +ఈ క్విజ్‌కు గ్రేడ్ లేదు, కాబట్టి మీరు దీన్ని మీకు కావలసినన్ని సార్లు ప్రయత్నించవచ్చు. కొన్ని ప్రశ్నలతో మీరు ఇబ్బంది పడితే, చిట్కాలను అనుసరించి, మెటీరియల్‌ను మళ్ళీ చూడండి. సర్టిఫికేషన్ పరీక్షలో ఈ మెటీరియల్‌పై మిమ్మల్ని మళ్లీ క్విజ్ చేయబడుతుంది. + +1. హబ్‌ను అన్వేషించండి మరియు roberta-large-mnli చెక్‌పాయింట్ కోసం చూడండి. ఇది ఏ పనిని చేస్తుంది? + + roberta-large-mnli page లో మళ్ళీ చూడండి.', + }, + { + text: "టెక్స్ట్ వర్గీకరణ", + explain: + "మరింత కచ్చితంగా చెప్పాలంటే, ఇది రెండు వాక్యాలు తార్కికంగా మూడు లేబుల్స్‌లో (వైరుధ్యం, తటస్థం, అనుమితి) కదానికొకటి సంబంధం కలిగి ఉన్నాయో లేదో వర్గీకరిస్తుంది — ఈ పనిని natural language inference అని కూడా పిలుస్తారు.", + correct: true, + }, + { + text: "టెక్స్ట్ జనరేషన్", + explain: + 'roberta-large-mnli page లో మళ్ళీ చూడండి.', + }, + ]} + /> + +### 2. కింది కోడ్ ఏమి తిరిగి ఇస్తుంది?? + +```py +from transformers import pipeline + +ner = pipeline("ner", grouped_entities=True) +ner("My name is Sylvain and I work at Hugging Face in Brooklyn.") +``` + +sentiment-analysis పైప్‌లైన్ అవుతుంది." + }, + { + text: "ఇది ఈ వాక్యాన్ని పూర్తి చేస్తూ ఉత్పత్తి చేయబడిన టెక్స్ట్‌ను తిరిగి ఇస్తుంది.", + explain: "ఇది తప్పు — ఇది text-generation పైప్‌లైన్ అవుతుంది.", + }, + { + text: "ఇది వ్యక్తులు, సంస్థలు లేదా ప్రదేశాలను సూచించే పదాలను తిరిగి ఇస్తుంది.", + explain: "అంతేకాకుండా, grouped_entities=True తో, ఇది \"Hugging Face\" వంటి ఒకే ఎంటిటీకి చెందిన పదాలను సమూహపరుస్తుంది.", + correct: true + } + ]} +/> + +### 3. ఈ కోడ్ నమూనాలో ... స్థానంలో ఏమి ఉండాలి?? + +```py +from transformers import pipeline + +filler = pipeline("fill-mask", model="bert-base-cased") +result = filler("...") +``` + + has been waiting for you.", + explain: + "ఇది తప్పు. bert-base-cased మోడల్ కార్డును తనిఖీ చేసి మీ పొరపాటును గుర్తించడానికి ప్రయత్నించండి.", + }, + { + text: "This [MASK] has been waiting for you.", + explain: "ఈ మోడల్ యొక్క మాస్క్ టోకెన్ [MASK].", + correct: true, + }, + { + text: "This man has been waiting for you.", + explain: + "ఇది తప్పు. ఈ పైప్‌లైన్ మాస్క్ చేయబడిన పదాలను నింపుతుంది, కాబట్టి దీనికి ఎక్కడో ఒక మాస్క్ టోకెన్ అవసరం.", + }, + ]} +/> + +### 4. ఈ కోడ్ ఎందుకు విఫలమవుతుంది?? + +```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: "ఈ పైప్‌లైన్‌కు కేవలం ఒక వాక్యం కాకుండా, అనేక వాక్యాలు అవసరం.", + explain: + "ఇది తప్పు, సరిగ్గా ఉపయోగించినప్పుడు, ఈ పైప్‌లైన్ (ఇతర అన్ని పైప్‌లైన్‌ల వలె) ప్రాసెస్ చేయడానికి వాక్యాల జాబితాను తీసుకోవచ్చు.", + }, + { + text: "🤗 Transformers లైబ్రరీ మామూలుగానే విఫలమైంది.", + explain: "మేము ఈ సమాధానానికి వ్యాఖ్యానించి గౌరవించము!", + }, + { + text: "ఈ పైప్‌లైన్‌కు పొడవైన ఇన్‌పుట్‌లు అవసరం; ఇది చాలా చిన్నది.", + explain: + "ఇది తప్పు. ఈ పైప్‌లైన్ ద్వారా ప్రాసెస్ చేయబడినప్పుడు చాలా పొడవైన టెక్స్ట్ కుదించబడుతుందని గమనించండి.", + }, + ]} +/> + +### 5. ట్రాన్స్‌ఫర్ లెర్నింగ్ అంటే ఏమిటి? + + + +### 6. నిజమా అబద్ధమా? ఒక భాషా నమూనాకు దాని ప్రీట్రైనింగ్ కోసం సాధారణంగా లేబుల్స్ అవసరం లేదు. + +స్వీయ-పర్యవేక్షితం (self-supervised), అంటే లేబుల్స్ ఇన్‌పుట్‌ల నుండి స్వయంచాలకంగా సృష్టించబడతాయి (తదుపరి పదాన్ని అంచనా వేయడం లేదా కొన్ని మాస్క్ చేయబడిన పదాలను పూరించడం వంటివి).", + correct: true, + }, + { + text: "అబద్ధం", + explain: "ఇది సరైన సమాధానం కాదు.", + }, + ]} +/> + +### 7. మోడల్, ఆర్కిటెక్చర్, మరియు వెయిట్స్ అనే పదాలను ఉత్తమంగా వర్ణించే వాక్యాన్ని ఎంచుకోండి. + + + +### 8. ఉత్పత్తి చేయబడిన టెక్స్ట్‌తో ప్రాంప్ట్‌లను పూర్తి చేయడానికి మీరు ఈ రకమైన మోడల్స్‌లో దేనిని ఉపయోగిస్తారు? + + + +### 9. టెక్స్ట్‌లను సంగ్రహించడానికి మీరు ఆ రకమైన మోడల్స్‌లో దేనిని ఉపయోగిస్తారు? + + + +### 10. కొన్ని లేబుల్స్ ప్రకారం టెక్స్ట్ ఇన్‌పుట్‌లను వర్గీకరించడానికి మీరు ఈ రకమైన మోడల్స్‌లో దేనిని ఉపయోగిస్తారు? + + + +### 11. ఒక మోడల్‌లో గమనించిన పక్షపాతానికి సాధ్యమయ్యే మూలం ఏమిటి? + + diff --git a/chapters/te/chapter1/8.mdx b/chapters/te/chapter1/8.mdx new file mode 100644 index 000000000..12dda0e10 --- /dev/null +++ b/chapters/te/chapter1/8.mdx @@ -0,0 +1,303 @@ +# LLMలతో టెక్స్ట్ జనరేషన్ ఇన్ఫరెన్స్ పై లోతైన పరిశీలన [[inference-with-llms]] + + + + + +ఇప్పటివరకు, మనం టెక్స్ట్ వర్గీకరణ లేదా సారాంశీకరణ వంటి వివిధ రకాల పనులకు సంబంధించి ట్రాన్స్‌ఫార్మర్ ఆర్కిటెక్చర్‌ను అన్వేషించాము. అయితే, Large Language Models (LLMలు) ఎక్కువగా టెక్స్ట్ జనరేషన్ కోసం ఉపయోగించబడతాయి మరియు ఈ అధ్యాయంలో మనం దీనినే అన్వేషిస్తాము. + +ఈ పేజీలో, మనం LLM ఇన్ఫరెన్స్ వెనుక ఉన్న ముఖ్యమైన భావనలను అన్వేషిస్తాము. ఈ మోడల్స్ టెక్స్ట్‌ను ఎలా ఉత్పత్తి చేస్తాయి మరియు ఇన్ఫరెన్స్ ప్రక్రియలో కీలకమైన అంశాలు ఏమిటో సమగ్ర అవగాహనను అందిస్తాము. + +## ప్రాథమికాలను అర్థం చేసుకోవడం + +ప్రాథమిక అంశాలతో ప్రారంభిద్దాం. ఇన్ఫరెన్స్ అనేది, శిక్షణ పొందిన LLMను ఉపయోగించి, ఇచ్చిన ఇన్‌పుట్ ప్రాంప్ట్ నుండి మానవ-సహజమైన టెక్స్ట్‌ను ఉత్పత్తి చేసే ప్రక్రియ. భాషా నమూనాలు తమ శిక్షణ నుండి పొందిన జ్ఞానాన్ని ఉపయోగించి, ఒకేసారి ఒక్కో పదాన్ని స్పందనలుగా రూపొందిస్తాయి. మోడల్, బిలియన్ల పారామితుల నుండి నేర్చుకున్న సంభావ్యతలను (probabilities) ఉపయోగించి, ఒక క్రమంలో తదుపరి టోకెన్‌ను అంచనా వేసి, ఉత్పత్తి చేస్తుంది. ఈ వరుస ఉత్పత్తి ప్రక్రియే LLMలను పొందికగా మరియు సందర్భోచితంగా ఉండే టెక్స్ట్‌ను రూపొందించడానికి అనుమతిస్తుంది. + +## అటెన్షన్ పాత్ర + +అటెన్షన్ మెకానిజం, LLMలకు సందర్భాన్ని అర్థం చేసుకుని, పొందికైన ప్రతిస్పందనలను ఉత్పత్తి చేసే సామర్థ్యాన్ని ఇస్తుంది. తదుపరి పదాన్ని అంచనా వేసేటప్పుడు, ఒక వాక్యంలోని ప్రతి పదానికి సమాన ప్రాధాన్యత ఉండదు - ఉదాహరణకు, "The capital of France is ..." అనే వాక్యంలో, "France" మరియు "capital" అనే పదాలు తదుపరి పదం "Paris" అని నిర్ధారించడానికి చాలా ముఖ్యమైనవి. సంబంధిత సమాచారంపై దృష్టి పెట్టే ఈ సామర్థ్యాన్ని మనం అటెన్షన్ అని పిలుస్తాము. + +Visual Gif of Attention + +తదుపరి టోకెన్‌ను అంచనా వేయడానికి అత్యంత సంబంధిత పదాలను గుర్తించే ఈ ప్రక్రియ అద్భుతంగా ప్రభావవంతమైనదని నిరూపించబడింది. BERT మరియు GPT-2 కాలం నుండి LLMలకు శిక్షణ ఇచ్చే ప్రాథమిక సూత్రం — తదుపరి టోకెన్‌ను అంచనా వేయడం — సాధారణంగా స్థిరంగా ఉన్నప్పటికీ, న్యూరల్ నెట్‌వర్క్‌లను స్కేల్ చేయడంలో మరియు అటెన్షన్ మెకానిజంను తక్కువ ఖర్చుతో, సుదీర్ఘమైన సీక్వెన్స్‌ల కోసం పనిచేసేలా చేయడంలో గణనీయమైన పురోగతి సాధించబడింది. + + + +సంక్షిప్తంగా, LLMలు పొందికగా మరియు సందర్భానుసారంగా ఉండే టెక్స్ట్‌ను ఉత్పత్తి చేయగలగడానికి అటెన్షన్ మెకానిజం కీలకం. ఇది ఆధునిక LLMలను పాత తరం భాషా నమూనాల నుండి వేరుగా నిలుపుతుంది. + + + +### కాంటెక్స్ట్ లెంగ్త్ మరియు అటెన్షన్ స్పాన్ + +ఇప్పుడు మనం అటెన్షన్ గురించి అర్థం చేసుకున్నాం కాబట్టి, ఒక LLM వాస్తవానికి ఎంత కాంటెక్స్ట్‌ను నిర్వహించగలదో అన్వేషిద్దాం. ఇది మనల్ని కాంటెక్స్ట్ లెంగ్త్, లేదా మోడల్ యొక్క 'అటెన్షన్ స్పాన్' వద్దకు తీసుకువస్తుంది. + +కాంటెక్స్ట్ లెంగ్త్ అనేది LLM ఒకేసారి ప్రాసెస్ చేయగల గరిష్ట సంఖ్య టోకెన్‌లను (పదాలు లేదా పదాల భాగాలు) సూచిస్తుంది. దీనిని మోడల్ యొక్క వర్కింగ్ మెమరీ పరిమాణంగా భావించండి. + +ఈ సామర్థ్యాలు అనేక ఆచరణాత్మక కారకాల ద్వారా పరిమితం చేయబడ్డాయి: + +- మోడల్ యొక్క ఆర్కిటెక్చర్ మరియు పరిమాణం +- అందుబాటులో ఉన్న కంప్యూటేషనల్ వనరులు +- ఇన్‌పుట్ మరియు కావలసిన అవుట్‌పుట్ యొక్క సంక్లిష్టత + +ఒక ఆదర్శ ప్రపంచంలో, మనం మోడల్‌కు అపరిమితమైన కాంటెక్స్ట్‌ను అందించవచ్చు, కానీ హార్డ్‌వేర్ పరిమితులు మరియు గణన ఖర్చులు దీనిని అసాధ్యం చేస్తాయి. అందుకే సామర్థ్యాన్ని మరియు సమర్థతను సమతుల్యం చేయడానికి వివిధ మోడల్స్ వివిధ కాంటెక్స్ట్ లెంగ్త్‌లతో రూపొందించబడ్డాయి. + + + +కాంటెక్స్ట్ లెంగ్త్ అనేది, స్పందనను ఉత్పత్తి చేసేటప్పుడు మోడల్ ఒకేసారి పరిగణించగల గరిష్ట టోకెన్‌ల సంఖ్య. + + + +### ప్రాంప్టింగ్ కళ + +మనం LLMలకు సమాచారాన్ని అందించినప్పుడు, LLM యొక్క జనరేషన్‌ను కావలసిన అవుట్‌పుట్ వైపు నడిపించే విధంగా మన ఇన్‌పుట్‌ను రూపొందిస్తాము. దీనిని ప్రాంప్టింగ్ అని అంటారు. + +LLMలు సమాచారాన్ని ఎలా ప్రాసెస్ చేస్తాయో అర్థం చేసుకోవడం, మెరుగైన ప్రాంప్ట్‌లను రూపొందించడంలో మనకు సహాయపడుతుంది. మోడల్ యొక్క ప్రాథమిక విధి ప్రతి ఇన్‌పుట్ టోకెన్ యొక్క ప్రాముఖ్యతను విశ్లేషించడం ద్వారా తదుపరి టోకెన్‌ను అంచనా వేయడం కాబట్టి, మీ ఇన్‌పుట్ సీక్వెన్స్ యొక్క పదజాలం చాలా కీలకమైనది. + + + +ప్రాంప్ట్‌ను జాగ్రత్తగా రూపొందించడం వల్ల LLM జనరేషన్‌ను కావలసిన అవుట్‌పుట్ వైపు నడిపించడం సులభం అవుతుంది. + + + +## రెండు-దశల ఇన్ఫరెన్స్ ప్రక్రియ + +ఇప్పుడు మనం ప్రాథమిక భాగాలను అర్థం చేసుకున్నాం కాబట్టి, LLMలు వాస్తవానికి టెక్స్ట్‌ను ఎలా ఉత్పత్తి చేస్తాయో లోతుగా చూద్దాం. ఈ ప్రక్రియను రెండు ప్రధాన దశలుగా విభజించవచ్చు: ప్రీఫిల్ (prefill) మరియు డీకోడ్ (decode). ఈ దశలు ఒక అసెంబ్లీ లైన్ లాగా కలిసి పనిచేస్తాయి, పొందికైన టెక్స్ట్‌ను ఉత్పత్తి చేయడంలో ప్రతి ఒక్కటి కీలక పాత్ర పోషిస్తుంది. + +### ప్రీఫిల్ దశ + +ప్రీఫిల్ దశ వంటలో తయారీ దశ లాంటిది - ఇక్కడ అన్ని ప్రారంభ పదార్థాలు ప్రాసెస్ చేయబడి సిద్ధంగా ఉంటాయి. ఈ దశలో మూడు కీలక దశలు ఉంటాయి: + +1. **టోకనైజేషన్**: ఇన్‌పుట్ టెక్స్ట్‌ను టోకెన్‌లుగా మార్చడం (వీటిని మోడల్ అర్థం చేసుకునే ప్రాథమిక బిల్డింగ్ బ్లాక్‌లుగా భావించండి) +2. **ఎంబెడ్డింగ్ మార్పిడి**: ఈ టోకెన్‌లను వాటి అర్థాన్ని సంగ్రహించే సంఖ్యా ప్రాతినిధ్యాలుగా మార్చడం +3. **ప్రారంభ ప్రాసెసింగ్**: కాంటెక్స్ట్ యొక్క గొప్ప అవగాహనను సృష్టించడానికి ఈ ఎంబెడ్డింగ్‌లను మోడల్ యొక్క న్యూరల్ నెట్‌వర్క్‌ల ద్వారా అమలు చేయడం + +ఈ దశ కంప్యూటేషనల్‌గా చాలా తీవ్రమైనది ఎందుకంటే ఇది అన్ని ఇన్‌పుట్ టోకెన్‌లను ఒకేసారి ప్రాసెస్ చేయాలి. ఒక ప్రతిస్పందన రాయడం ప్రారంభించే ముందు ఒక పూర్తి పేరా చదివి అర్థం చేసుకున్నట్లుగా దీనిని భావించండి. + +కింది ఇంటరాక్టివ్ ప్లేగ్రౌండ్‌లో మీరు వివిధ టోకనైజర్‌లతో ప్రయోగాలు చేయవచ్చు: + + + +### డీకోడ్ దశ + +ప్రీఫిల్ దశ ఇన్‌పుట్‌ను ప్రాసెస్ చేసిన తర్వాత, మనం డీకోడ్ దశకు వెళ్తాము - ఇక్కడే అసలు టెక్స్ట్ జనరేషన్ జరుగుతుంది. మోడల్ ఒక ఆటోరిగ్రెసివ్ ప్రక్రియలో (ఇక్కడ ప్రతి కొత్త టోకెన్ మునుపటి అన్ని టోకెన్లపై ఆధారపడి ఉంటుంది) ఒకేసారి ఒక్కో టోకెన్‌ను ఉత్పత్తి చేస్తుంది. + +డీకోడ్ దశలో ప్రతి కొత్త టోకెన్ కోసం జరిగే అనేక కీలక దశలు ఉంటాయి: + +1. **అటెన్షన్ కంప్యూటేషన్**: కాంటెక్స్ట్‌ను అర్థం చేసుకోవడానికి మునుపటి అన్ని టోకెన్‌లను తిరిగి చూడటం +2. **సంభావ్యత గణన**: సాధ్యమయ్యే ప్రతి తదుపరి టోకెన్ యొక్క సంభావ్యతను నిర్ణయించడం +3. **టోకెన్ ఎంపిక**: ఈ సంభావ్యతల ఆధారంగా తదుపరి టోకెన్‌ను ఎంచుకోవడం +4. **కొనసాగింపు తనిఖీ**: జనరేషన్‌ను కొనసాగించాలా లేదా ఆపాలా అని నిర్ణయించడం + +ఈ దశ మెమరీ-ఇంటెన్సివ్ ఎందుకంటే మోడల్ గతంలో ఉత్పత్తి చేయబడిన అన్ని టోకెన్‌లను మరియు వాటి సంబంధాలను గుర్తుంచుకోవాలి. + +## శాంప్లింగ్ వ్యూహాలు + +ఇప్పుడు మనం మోడల్ టెక్స్ట్‌ను ఎలా ఉత్పత్తి చేస్తుందో అర్థం చేసుకున్నాం కాబట్టి, ఈ జనరేషన్ ప్రక్రియను మనం నియంత్రించగల వివిధ మార్గాలను అన్వేషిద్దాం. ఒక రచయిత మరింత సృజనాత్మకంగా లేదా మరింత కచ్చితంగా ఉండటానికి మధ్య ఎంచుకున్నట్లే, మోడల్ తన టోకెన్ ఎంపికలను ఎలా చేయాలో మనం సర్దుబాటు చేయవచ్చు. + +ఈ స్పేస్‌లో SmolLM2 తో మీరు ప్రాథమిక డీకోడింగ్ ప్రక్రియతో స్వయంగా ఇంటరాక్ట్ అవ్వవచ్చు (గుర్తుంచుకోండి, ఇది ఈ మోడల్‌కు **EOS** అయిన `<|im_end|>` టోకెన్‌ను చేరుకునే వరకు డీకోడ్ చేస్తుంది): + + + +### టోకెన్ ఎంపికను అర్థం చేసుకోవడం: సంభావ్యతల నుండి టోకెన్ ఎంపికల వరకు + +మోడల్ తదుపరి టోకెన్‌ను ఎంచుకోవలసి వచ్చినప్పుడు, అది దాని పదజాలంలోని ప్రతి పదానికి ముడి సంభావ్యతలతో (logits అని పిలుస్తారు) ప్రారంభమవుతుంది. కానీ ఈ సంభావ్యతలను మనం అసలు ఎంపికలుగా ఎలా మారుస్తాం? ప్రక్రియను విభజించి చూద్దాం: + +![image](https://huggingface.co/reasoning-course/images/resolve/main/inference/1.png) + +1. **రా లాజిట్స్ (Raw Logits)**: సాధ్యమైన ప్రతి తదుపరి పదం గురించి మోడల్ యొక్క ప్రారంభ అంతర్ దృష్టిగా వీటిని భావించండి +2. **టెంపరేచర్ కంట్రోల్**: ఒక క్రియేటివిటీ డయల్ లాంటిది - అధిక సెట్టింగ్‌లు `(>1.0)` ఎంపికలను మరింత యాదృచ్ఛికంగా మరియు సృజనాత్మకంగా చేస్తాయి, తక్కువ సెట్టింగ్‌లు `(<1.0)` వాటిని మరింత కేంద్రీకృతంగా మరియు నిర్ధారితంగా చేస్తాయి +3. **టాప్-పి (న్యూక్లియస్) శాంప్లింగ్**: సాధ్యమయ్యే అన్ని పదాలను పరిగణలోకి తీసుకోకుండా, మనం ఎంచుకున్న సంభావ్యత థ్రెషోల్డ్‌కు (ఉదా., టాప్ 90%) సరిపోయే అత్యంత సంభావ్య పదాలను మాత్రమే చూస్తాము +4. **టాప్-కె ఫిల్టరింగ్**: ఒక ప్రత్యామ్నాయ విధానం, ఇక్కడ మనం k అత్యంత సంభావ్య తదుపరి పదాలను మాత్రమే పరిగణలోకి తీసుకుంటాము + +### పునరావృత్తిని నిర్వహించడం: అవుట్‌పుట్‌ను తాజాగా ఉంచడం + +LLMలతో ఒక సాధారణ సవాలు ఏమిటంటే, అవి తమను తాము పునరావృతం చేసుకునే ధోరణి - ఒకే పాయింట్లకు పదేపదే తిరిగివచ్చే స్పీకర్ లాగా. దీనిని పరిష్కరించడానికి, మేము రెండు రకాల పెనాల్టీలను ఉపయోగిస్తాము: + +1. **ప్రెజెన్స్ పెనాల్టీ (Presence Penalty)**: ఇదివరకు కనిపించిన ఏ టోకెన్‌కైనా, అది ఎంత తరచుగా కనిపించినా వర్తించే ఒక స్థిరమైన పెనాల్టీ. ఇది మోడల్ అదే పదాలను తిరిగి ఉపయోగించకుండా నిరోధించడానికి సహాయపడుతుంది. +2. **ఫ్రీక్వెన్సీ పెనాల్టీ (Frequency Penalty)**: ఒక టోకెన్ ఎంత తరచుగా ఉపయోగించబడిందనే దానిపై ఆధారపడి పెరిగే స్కేలింగ్ పెనాల్టీ. ఒక పదం ఎంత ఎక్కువగా కనిపిస్తే, అది మళ్లీ ఎంపికయ్యే అవకాశం అంత తక్కువ. + +![image](https://huggingface.co/reasoning-course/images/resolve/main/inference/2.png) + +ఇతర శాంప్లింగ్ వ్యూహాలు వర్తించే ముందు, ఈ పెనాల్టీలు టోకెన్ ఎంపిక ప్రక్రియలో ప్రారంభంలోనే వర్తింపజేయబడతాయి, ముడి సంభావ్యతలను సర్దుబాటు చేస్తాయి. కొత్త పదజాలాన్ని అన్వేషించడానికి మోడల్‌ను ప్రోత్సహించే సున్నితమైన ప్రోత్సాహకాలుగా వీటిని భావించండి. + +### జనరేషన్ పొడవును నియంత్రించడం: సరిహద్దులను సెట్ చేయడం + +ఒక మంచి కథకు సరైన వేగం మరియు పొడవు అవసరమైనట్లే, మన LLM ఎంత టెక్స్ట్ ఉత్పత్తి చేస్తుందో నియంత్రించడానికి మనకు మార్గాలు అవసరం. ఆచరణాత్మక అనువర్తనాలకు ఇది చాలా ముఖ్యం - మనం ట్వీట్-పొడవు ప్రతిస్పందనను ఉత్పత్తి చేస్తున్నా లేదా పూర్తి బ్లాగ్ పోస్ట్‌ను ఉత్పత్తి చేస్తున్నా. + +మనం జనరేషన్ పొడవును అనేక విధాలుగా నియంత్రించవచ్చు: + +1. **టోకెన్ పరిమితులు**: కనీస మరియు గరిష్ట టోకెన్ల సంఖ్యను సెట్ చేయడం +2. **స్టాప్ సీక్వెన్సులు**: జనరేషన్ ముగింపును సూచించే నిర్దిష్ట నమూనాలను నిర్వచించడం +3. **ఎండ్-ఆఫ్-సీక్వెన్స్ డిటెక్షన్**: మోడల్ తన ప్రతిస్పందనను సహజంగా ముగించనివ్వడం + +ఉదాహరణకు, మనం ఒకే పేరాగ్రాఫ్‌ను రూపొందించాలనుకుంటే, గరిష్టంగా 100 టోకెన్‌లను సెట్ చేసి "\n\n" ను స్టాప్ సీక్వెన్స్‌గా ఉపయోగించవచ్చు. ఇది మన అవుట్‌పుట్ దాని ప్రయోజనం కోసం కేంద్రీకృతమై మరియు తగిన పరిమాణంలో ఉండేలా చేస్తుంది. + +![image](https://huggingface.co/reasoning-course/images/resolve/main/inference/3.png) + +### బీమ్ సెర్చ్: మెరుగైన పొందిక కోసం ముందుకు చూడటం + +ఇప్పటివరకు మనం చర్చించిన వ్యూహాలు ఒక సమయంలో ఒక్కో టోకెన్‌కు మాత్రమే నిర్ణయాలు తీసుకుంటాయి, కానీ బీమ్ సెర్చ్ మరింత సమగ్రమైన విధానాన్ని తీసుకుంటుంది. ప్రతి దశలో ఒకే ఎంపికకు కట్టుబడి ఉండటానికి బదులుగా, ఇది ఒకేసారి అనేక సాధ్యమైన మార్గాలను అన్వేషిస్తుంది - చదరంగం ఆటగాడు అనేక ఎత్తుగడలను ముందుకు ఆలోచించినట్లుగా. + +![image](https://huggingface.co/reasoning-course/images/resolve/main/inference/4.png) + +ఇది ఎలా పనిచేస్తుందో ఇక్కడ ఉంది: + +1. ప్రతీ దశలో, అనేక అభ్యర్థి సీక్వెన్సులను (సాధారణంగా 5-10) నిర్వహించండి +2. ప్రతి అభ్యర్థికి, తదుపరి టోకెన్ కోసం సంభావ్యతలను గణించండి +3. సీక్వెన్సులు మరియు తదుపరి టోకెన్‌ల యొక్క అత్యంత ఆశాజనకమైన కలయికలను మాత్రమే ఉంచండి +4. కావలసిన పొడవు లేదా స్టాప్ కండిషన్ చేరే వరకు ఈ ప్రక్రియను కొనసాగించండి +5. అత్యధిక మొత్తం సంభావ్యత ఉన్న సీక్వెన్స్‌ను ఎంచుకోండి + +మీరు బీమ్ సెర్చ్‌ను దృశ్యమానంగా ఇక్కడ అన్వేషించవచ్చు: + + + +ఈ విధానం తరచుగా మరింత పొందికైన మరియు వ్యాకరణపరంగా సరైన టెక్స్ట్‌ను ఉత్పత్తి చేస్తుంది, కానీ ఇది సరళమైన పద్ధతుల కంటే ఎక్కువ కంప్యూటేషనల్ వనరులను తీసుకుంటుంది. + +## ఆచరణాత్మక సవాళ్లు మరియు ఆప్టిమైజేషన్ + +LLM ఇన్ఫరెన్స్ అన్వేషణను ముగించే ముందు, ఈ మోడల్స్‌ను అమలు చేసేటప్పుడు మీరు ఎదుర్కొనే ఆచరణాత్మక సవాళ్లను, మరియు వాటి పనితీరును ఎలా కొలవాలి మరియు ఆప్టిమైజ్ చేయాలో చూద్దాం. + +### కీలక పనితీరు కొలమానాలు + +LLMలతో పనిచేసేటప్పుడు, నాలుగు కీలకమైన కొలమానాలు మీ అమలు నిర్ణయాలను తీర్చిదిద్దుతాయి: + +1. **టైమ్ టు ఫస్ట్ టోకెన్ (TTFT)**: మొదటి ప్రతిస్పందనను ఎంత త్వరగా పొందగలరు? ఇది వినియోగదారు అనుభవం కోసం చాలా ముఖ్యం మరియు దీనిపై ప్రధానంగా ప్రీఫిల్ దశ ప్రభావం చూపుతుంది. +2. **టైమ్ పర్ అవుట్‌పుట్ టోకెన్ (TPOT)**: తర్వాతి టోకెన్‌లను ఎంత వేగంగా ఉత్పత్తి చేయగలరు? ఇది మొత్తం జనరేషన్ వేగాన్ని నిర్ధారిస్తుంది. +3. **త్రూపుట్ (Throughput)**: ఒకేసారి ఎన్ని అభ్యర్థనలను మీరు నిర్వహించగలరు? ఇది స్కేలింగ్ మరియు ఖర్చు సమర్థతపై ప్రభావం చూపుతుంది. +4. **VRAM వినియోగం**: మీకు ఎంత GPU మెమరీ అవసరం? వాస్తవ ప్రపంచ అప్లికేషన్‌లలో ఇది తరచుగా ప్రధాన పరిమితిగా మారుతుంది. + +### కాంటెక్స్ట్ లెంగ్త్ సవాలు + +LLM ఇన్ఫరెన్స్‌లో అత్యంత ముఖ్యమైన సవాళ్లలో ఒకటి కాంటెక్స్ట్ లెంగ్త్‌ను సమర్థవంతంగా నిర్వహించడం. పొడవైన కాంటెక్స్ట్‌లు ఎక్కువ సమాచారాన్ని అందిస్తాయి కానీ గణనీయమైన ఖర్చులతో వస్తాయి: + +- **మెమరీ వినియోగం**: కాంటెక్స్ట్ లెంగ్త్‌తో వర్గానుపాతంలో (quadratically) పెరుగుతుంది +- **ప్రాసెసింగ్ వేగం**: పొడవైన కాంటెక్స్ట్‌లతో సరళంగా (linearly) తగ్గుతుంది +- **వనరుల కేటాయింపు**: VRAM వినియోగాన్ని జాగ్రత్తగా సమతుల్యం చేయడం అవసరం + +[Qwen2.5-1M](https://huggingface.co/Qwen/Qwen2.5-14B-Instruct-1M) వంటి ఇటీవలి మోడల్స్ 1M టోకెన్ కాంటెక్స్ట్ విండోలను అందిస్తాయి, కానీ ఇది గణనీయంగా నెమ్మదిగా ఉండే ఇన్ఫరెన్స్ సమయాల ఖర్చుతో వస్తుంది. మీ నిర్దిష్ట వినియోగ సందర్భానికి సరైన సమతుల్యాన్ని కనుగొనడం కీలకం. + +
+
+
+
+ Input Text (Raw) +
+
+
+ Tokenized Input +
+
+
+
+ Context Window +
+ (e.g., 4K tokens) +
+
+
+
+
+
+
+
+
+
+
+ Memory Usage +
∝ Length² +
+
+
+
+ Processing Time +
∝ Length +
+
+
+
+
+ +### KV కాష్ ఆప్టిమైజేషన్ + +ఈ సవాళ్లను ఎదుర్కోవడానికి, అత్యంత శక్తివంతమైన ఆప్టిమైజేషన్‌లలో ఒకటి KV (కీ-వాల్యూ) కాషింగ్. ఈ టెక్నిక్ మధ్యంతర గణనలను నిల్వ చేయడం మరియు తిరిగి ఉపయోగించడం ద్వారా ఇన్ఫరెన్స్ వేగాన్ని గణనీయంగా మెరుగుపరుస్తుంది. ఈ ఆప్టిమైజేషన్: + +- పునరావృత గణనలను తగ్గిస్తుంది +- జనరేషన్ వేగాన్ని మెరుగుపరుస్తుంది +- సుదీర్ఘ-సందర్భ (long-context) జనరేషన్‌ను ఆచరణాత్మకంగా చేస్తుంది + +దీని ప్రతికూలత అదనపు మెమరీ వినియోగం, కానీ పనితీరు ప్రయోజనాలు సాధారణంగా ఈ ఖర్చును అధిగమిస్తాయి. + +## ముగింపు + +ఈ శక్తివంతమైన మోడల్స్‌ను సమర్థవంతంగా అమలు చేయడానికి మరియు ఆప్టిమైజ్ చేయడానికి LLM ఇన్ఫరెన్స్‌ను అర్థం చేసుకోవడం చాలా ముఖ్యం. మేము కవర్ చేసిన ముఖ్య అంశాలు: + +- అటెన్షన్ మరియు కాంటెక్స్ట్ యొక్క ప్రాథమిక పాత్ర +- రెండు-దశల ఇన్ఫరెన్స్ ప్రక్రియ +- జనరేషన్‌ను నియంత్రించడానికి వివిధ శాంప్లింగ్ వ్యూహాలు +- ఆచరణాత్మక సవాళ్లు మరియు ఆప్టిమైజేషన్లు + +ఈ భావనలపై పట్టు సాధించడం ద్వారా, LLMలను సమర్థవంతంగా మరియు ప్రభావవంతంగా ఉపయోగించుకునే అప్లికేషన్‌లను రూపొందించడానికి మీరు మరింత మెరుగ్గా సిద్ధమవుతారు. + +LLM ఇన్ఫరెన్స్ రంగం వేగంగా అభివృద్ధి చెందుతోందని, కొత్త టెక్నిక్‌లు మరియు ఆప్టిమైజేషన్‌లు క్రమం తప్పకుండా వస్తున్నాయని గుర్తుంచుకోండి. ఆసక్తిగా ఉండండి మరియు మీ నిర్దిష్ట వినియోగ సందర్భాలకు ఏది ఉత్తమంగా పనిచేస్తుందో కనుగొనడానికి వివిధ విధానాలతో ప్రయోగాలు చేస్తూ ఉండండి. diff --git a/chapters/te/chapter1/9.mdx b/chapters/te/chapter1/9.mdx new file mode 100644 index 000000000..4543b436d --- /dev/null +++ b/chapters/te/chapter1/9.mdx @@ -0,0 +1,42 @@ +# పక్షపాతం మరియు పరిమితులు[[bias-and-limitations]] + + + +మీ ఉద్దేశ్యం ఒక ప్రీట్రైన్డ్ మోడల్ లేదా ఫైన్-ట్యూన్డ్ వెర్షన్‌ను ఉత్పత్తిలో ఉపయోగించాలనుకుంటే, దయచేసి ఈ మోడల్స్ శక్తివంతమైన సాధనాలు అయినప్పటికీ, వాటికి పరిమితులు ఉన్నాయని గుర్తుంచుకోండి. వీటిలో అతిపెద్దది ఏమిటంటే, పెద్ద మొత్తంలో డేటాపై ప్రీట్రైనింగ్‌ను ప్రారంభించడానికి, పరిశోధకులు తరచుగా వారు కనుగొనగలిగిన అన్ని కంటెంట్‌ను స్క్రాప్ చేస్తారు, ఇంటర్నెట్‌లో అందుబాటులో ఉన్న వాటిలో ఉత్తమమైనవి మరియు చెత్తైనవి రెండింటినీ తీసుకుంటారు. + +త్వరగా వివరించడానికి, BERT మోడల్‌తో `fill-mask` పైప్‌లైన్ ఉదాహరణకు తిరిగి వెళ్దాం: + +```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'] +``` + +ఈ రెండు వాక్యాలలో తప్పిపోయిన పదాన్ని పూరించమని అడిగినప్పుడు, మోడల్ ఒకే ఒక లింగ-రహిత సమాధానం (waiter/waitress) మాత్రమే ఇస్తుంది. మిగిలినవి సాధారణంగా ఒక నిర్దిష్ట లింగంతో ముడిపడి ఉన్న వృత్తులు -- మరియు అవును, "స్త్రీ" మరియు "పని"తో మోడల్ అనుబంధించే టాప్ 5 అవకాశాలలో prostitute చేరింది. BERT ఇంటర్నెట్ నుండి డేటాను స్క్రాప్ చేయడం ద్వారా నిర్మించబడని అరుదైన Transformer మోడల్స్‌లో ఒకటి అయినప్పటికీ ఇది జరుగుతుంది, బదులుగా తటస్థ డేటాను ఉపయోగించి (ఇది [English Wikipedia](https://huggingface.co/datasets/wikipedia) మరియు [BookCorpus](https://huggingface.co/datasets/bookcorpus) డేటాసెట్‌లపై శిక్షణ పొందింది). + +మీరు ఈ సాధనాలను ఉపయోగించినప్పుడు, మీరు ఉపయోగిస్తున్న అసలు మోడల్ చాలా సులభంగా సెక్సిస్ట్, జాతి వివక్షతో కూడిన లేదా హోమోఫోబిక్ కంటెంట్‌ను రూపొందించగలదని మీరు గుర్తుంచుకోవాలి. మీ డేటాపై మోడల్‌ను ఫైన్-ట్యూన్ చేయడం ఈ అంతర్గత పక్షపాతాన్ని తొలగించదు. From 01c1e126bd45249030239da247400c7d50644376 Mon Sep 17 00:00:00 2001 From: Youngdong Date: Thu, 17 Jul 2025 19:06:20 +0900 Subject: [PATCH 10/43] docs: ko: chapter3-3.mdx --- chapters/ko/_toctree.yml | 5 + chapters/ko/chapter3/3.mdx | 393 +++++++++++++++++++++++++++++++++++++ 2 files changed, 398 insertions(+) create mode 100644 chapters/ko/chapter3/3.mdx diff --git a/chapters/ko/_toctree.yml b/chapters/ko/_toctree.yml index 7a523be1c..02c1df004 100644 --- a/chapters/ko/_toctree.yml +++ b/chapters/ko/_toctree.yml @@ -47,6 +47,11 @@ title: 단원 마무리 퀴즈 quiz: 2 +- title: 3. 🤗 사전훈련된 모델 미세조정 + sections: + - local: chapter3/3 + title: Trainer API를 사용한 모델 미세조정 + - title: 5. 🤗 Datasets 라이브러리 sections: - local: chapter5/1 diff --git a/chapters/ko/chapter3/3.mdx b/chapters/ko/chapter3/3.mdx new file mode 100644 index 000000000..12705fca7 --- /dev/null +++ b/chapters/ko/chapter3/3.mdx @@ -0,0 +1,393 @@ + + +# Fine-tuning a model with the Trainer API[[fine-tuning-a-model-with-the-trainer-api]] + + + + + +🤗 Transformers provides a `Trainer` class to help you fine-tune any of the pretrained models it provides on your dataset with modern best practices. Once you've done all the data preprocessing work in the last section, you have just a few steps left to define the `Trainer`. The hardest part is likely to be preparing the environment to run `Trainer.train()`, as it will run very slowly on a CPU. If you don't have a GPU set up, you can get access to free GPUs or TPUs on [Google Colab](https://colab.research.google.com/). + + + +📚 **Training Resources**: Before diving into training, familiarize yourself with the comprehensive [🤗 Transformers training guide](https://huggingface.co/docs/transformers/main/en/training) and explore practical examples in the [fine-tuning cookbook](https://huggingface.co/learn/cookbook/en/fine_tuning_code_llm_on_single_gpu). + + + +The code examples below assume you have already executed the examples in the previous section. Here is a short summary recapping what you need: + +```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[[training]] + +The first step before we can define our `Trainer` is to define a `TrainingArguments` class that will contain all the hyperparameters the `Trainer` will use for training and evaluation. The only argument you have to provide is a directory where the trained model will be saved, as well as the checkpoints along the way. For all the rest, you can leave the defaults, which should work pretty well for a basic fine-tuning. + +```py +from transformers import TrainingArguments + +training_args = TrainingArguments("test-trainer") +``` + +If you want to automatically upload your model to the Hub during training, pass along `push_to_hub=True` in the `TrainingArguments`. We will learn more about this in [Chapter 4](/course/chapter4/3) + + + +🚀 **Advanced Configuration**: For detailed information on all available training arguments and optimization strategies, check out the [TrainingArguments documentation](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments) and the [training configuration cookbook](https://huggingface.co/learn/cookbook/en/fine_tuning_code_llm_on_single_gpu). + + + +The second step is to define our model. As in the [previous chapter](/course/chapter2), we will use the `AutoModelForSequenceClassification` class, with two labels: + +```py +from transformers import AutoModelForSequenceClassification + +model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) +``` + +You will notice that unlike in [Chapter 2](/course/chapter2), you get a warning after instantiating this pretrained model. This is because BERT has not been pretrained on classifying pairs of sentences, so the head of the pretrained model has been discarded and a new head suitable for sequence classification has been added instead. The warnings indicate that some weights were not used (the ones corresponding to the dropped pretraining head) and that some others were randomly initialized (the ones for the new head). It concludes by encouraging you to train the model, which is exactly what we are going to do now. + +Once we have our model, we can define a `Trainer` by passing it all the objects constructed up to now — the `model`, the `training_args`, the training and validation datasets, our `data_collator`, and our `processing_class`. The `processing_class` parameter is a newer addition that tells the Trainer which tokenizer to use for processing: + +```py +from transformers import Trainer + +trainer = Trainer( + model, + training_args, + train_dataset=tokenized_datasets["train"], + eval_dataset=tokenized_datasets["validation"], + data_collator=data_collator, + processing_class=tokenizer, +) +``` + +When you pass a tokenizer as the `processing_class`, the default `data_collator` used by the `Trainer` will be a `DataCollatorWithPadding`. You can skip the `data_collator=data_collator` line in this case, but we included it here to show you this important part of the processing pipeline. + + + +📖 **Learn More**: For comprehensive details on the Trainer class and its parameters, visit the [Trainer API documentation](https://huggingface.co/docs/transformers/main/en/main_classes/trainer) and explore advanced usage patterns in the [training cookbook recipes](https://huggingface.co/learn/cookbook/en/fine_tuning_code_llm_on_single_gpu). + + + +To fine-tune the model on our dataset, we just have to call the `train()` method of our `Trainer`: + +```py +trainer.train() +``` + +This will start the fine-tuning (which should take a couple of minutes on a GPU) and report the training loss every 500 steps. It won't, however, tell you how well (or badly) your model is performing. This is because: + +1. We didn't tell the `Trainer` to evaluate during training by setting `eval_strategy` in `TrainingArguments` to either `"steps"` (evaluate every `eval_steps`) or `"epoch"` (evaluate at the end of each epoch). +2. We didn't provide the `Trainer` with a `compute_metrics()` function to calculate a metric during said evaluation (otherwise the evaluation would just have printed the loss, which is not a very intuitive number). + + +### Evaluation[[evaluation]] + +Let's see how we can build a useful `compute_metrics()` function and use it the next time we train. The function must take an `EvalPrediction` object (which is a named tuple with a `predictions` field and a `label_ids` field) and will return a dictionary mapping strings to floats (the strings being the names of the metrics returned, and the floats their values). To get some predictions from our model, we can use the `Trainer.predict()` command: + +```py +predictions = trainer.predict(tokenized_datasets["validation"]) +print(predictions.predictions.shape, predictions.label_ids.shape) +``` + +```python out +(408, 2) (408,) +``` + +The output of the `predict()` method is another named tuple with three fields: `predictions`, `label_ids`, and `metrics`. The `metrics` field will just contain the loss on the dataset passed, as well as some time metrics (how long it took to predict, in total and on average). Once we complete our `compute_metrics()` function and pass it to the `Trainer`, that field will also contain the metrics returned by `compute_metrics()`. + +As you can see, `predictions` is a two-dimensional array with shape 408 x 2 (408 being the number of elements in the dataset we used). Those are the logits for each element of the dataset we passed to `predict()` (as you saw in the [previous chapter](/course/chapter2), all Transformer models return logits). To transform them into predictions that we can compare to our labels, we need to take the index with the maximum value on the second axis: + +```py +import numpy as np + +preds = np.argmax(predictions.predictions, axis=-1) +``` + +We can now compare those `preds` to the labels. To build our `compute_metric()` function, we will rely on the metrics from the 🤗 [Evaluate](https://github.com/huggingface/evaluate/) library. We can load the metrics associated with the MRPC dataset as easily as we loaded the dataset, this time with the `evaluate.load()` function. The object returned has a `compute()` method we can use to do the metric calculation: + +```py +import evaluate + +metric = evaluate.load("glue", "mrpc") +metric.compute(predictions=preds, references=predictions.label_ids) +``` + +```python out +{'accuracy': 0.8578431372549019, 'f1': 0.8996539792387542} +``` + + + +Learn about different evaluation metrics and strategies in the [🤗 Evaluate documentation](https://huggingface.co/docs/evaluate/). + + + +The exact results you get may vary, as the random initialization of the model head might change the metrics it achieved. Here, we can see our model has an accuracy of 85.78% on the validation set and an F1 score of 89.97. Those are the two metrics used to evaluate results on the MRPC dataset for the GLUE benchmark. The table in the [BERT paper](https://arxiv.org/pdf/1810.04805.pdf) reported an F1 score of 88.9 for the base model. That was the `uncased` model while we are currently using the `cased` model, which explains the better result. + +Wrapping everything together, we get our `compute_metrics()` function: + +```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) +``` + +And to see it used in action to report metrics at the end of each epoch, here is how we define a new `Trainer` with this `compute_metrics()` function: + +```py +training_args = TrainingArguments("test-trainer", eval_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, + processing_class=tokenizer, + compute_metrics=compute_metrics, +) +``` + +Note that we create a new `TrainingArguments` with its `eval_strategy` set to `"epoch"` and a new model — otherwise, we would just be continuing the training of the model we have already trained. To launch a new training run, we execute: + +```py +trainer.train() +``` + +This time, it will report the validation loss and metrics at the end of each epoch on top of the training loss. Again, the exact accuracy/F1 score you reach might be a bit different from what we found, because of the random head initialization of the model, but it should be in the same ballpark. + +### Advanced Training Features[[advanced-training-features]] + +The `Trainer` comes with many built-in features that make modern deep learning best practices accessible: + +**Mixed Precision Training**: Use `fp16=True` in your training arguments for faster training and reduced memory usage: + +```py +training_args = TrainingArguments( + "test-trainer", + eval_strategy="epoch", + fp16=True, # Enable mixed precision +) +``` + +**Gradient Accumulation**: For effective larger batch sizes when GPU memory is limited: + +```py +training_args = TrainingArguments( + "test-trainer", + eval_strategy="epoch", + per_device_train_batch_size=4, + gradient_accumulation_steps=4, # Effective batch size = 4 * 4 = 16 +) +``` + +**Learning Rate Scheduling**: The Trainer uses linear decay by default, but you can customize this: + +```py +training_args = TrainingArguments( + "test-trainer", + eval_strategy="epoch", + learning_rate=2e-5, + lr_scheduler_type="cosine", # Try different schedulers +) +``` + + + +🎯 **Performance Optimization**: For more advanced training techniques including distributed training, memory optimization, and hardware-specific optimizations, explore the [🤗 Transformers performance guide](https://huggingface.co/docs/transformers/main/en/performance). + + + +The `Trainer` will work out of the box on multiple GPUs or TPUs and provides lots of options for distributed training. We will go over everything it supports in Chapter 10. + +This concludes the introduction to fine-tuning using the `Trainer` API. An example of doing this for most common NLP tasks will be given in [Chapter 7](/course/chapter7), but for now let's look at how to do the same thing with a pure PyTorch training loop. + + + +📝 **More Examples**: Check out the comprehensive collection of [🤗 Transformers notebooks](https://huggingface.co/docs/transformers/main/en/notebooks). + + + +## Section Quiz[[section-quiz]] + +Test your understanding of the Trainer API and fine-tuning concepts: + +### 1. What is the purpose of the processing_class parameter in the Trainer? + + + +### 2. Which TrainingArguments parameter controls how often evaluation occurs during training? + + + +### 3. What does fp16=True in TrainingArguments enable? + + + +### 4. What is the role of the compute_metrics function in the Trainer? + + + +### 5. What happens when you don't provide an eval_dataset to the Trainer? + + + +### 6. What is gradient accumulation and how do you enable it? + + + + + +💡 **Key Takeaways:** +- The `Trainer` API provides a high-level interface that handles most training complexity +- Use `processing_class` to specify your tokenizer for proper data handling +- `TrainingArguments` controls all aspects of training: learning rate, batch size, evaluation strategy, and optimizations +- `compute_metrics` enables custom evaluation metrics beyond just training loss +- Modern features like mixed precision (`fp16=True`) and gradient accumulation can significantly improve training efficiency + + + From 708e3ad93a981a3a21bace5ada0aba914eb064ff Mon Sep 17 00:00:00 2001 From: Youngdong Date: Thu, 17 Jul 2025 20:04:29 +0900 Subject: [PATCH 11/43] feat: nmt draft --- chapters/ko/chapter3/3.mdx | 196 ++++++++++++++++++------------------- 1 file changed, 98 insertions(+), 98 deletions(-) diff --git a/chapters/ko/chapter3/3.mdx b/chapters/ko/chapter3/3.mdx index 12705fca7..0e397ce8e 100644 --- a/chapters/ko/chapter3/3.mdx +++ b/chapters/ko/chapter3/3.mdx @@ -1,6 +1,6 @@ -# Fine-tuning a model with the Trainer API[[fine-tuning-a-model-with-the-trainer-api]] +# Trainer API로 모델 미세 조정하기[[fine-tuning-a-model-with-the-trainer-api]] -🤗 Transformers provides a `Trainer` class to help you fine-tune any of the pretrained models it provides on your dataset with modern best practices. Once you've done all the data preprocessing work in the last section, you have just a few steps left to define the `Trainer`. The hardest part is likely to be preparing the environment to run `Trainer.train()`, as it will run very slowly on a CPU. If you don't have a GPU set up, you can get access to free GPUs or TPUs on [Google Colab](https://colab.research.google.com/). +🤗 Transformers는 `Trainer` 클래스를 제공하여 최신 모범 사례를 사용해 제공하는 사전 학습된 모델을 데이터셋에 미세 조정할 수 있도록 도와줍니다. 이전 섹션에서 모든 데이터 전처리 작업을 완료했다면, `Trainer`를 정의하는 데 몇 단계만 남았습니다. 가장 어려운 부분은 `Trainer.train()`을 실행할 환경을 준비하는 것일 수 있습니다. CPU에서는 매우 느리게 실행되기 때문입니다. GPU가 설정되어 있지 않다면, [Google Colab](https://colab.research.google.com/)에서 무료 GPU 또는 TPU에 액세스할 수 있습니다. -📚 **Training Resources**: Before diving into training, familiarize yourself with the comprehensive [🤗 Transformers training guide](https://huggingface.co/docs/transformers/main/en/training) and explore practical examples in the [fine-tuning cookbook](https://huggingface.co/learn/cookbook/en/fine_tuning_code_llm_on_single_gpu). +📚 **훈련 리소스**: 훈련을 시작하기 전에 포괄적인 [🤗 Transformers 훈련 가이드](https://huggingface.co/docs/transformers/main/en/training)를 숙지하고 [미세 조정 쿡북](https://huggingface.co/learn/cookbook/en/fine_tuning_code_llm_on_single_gpu)의 실용적인 예제를 살펴보세요. -The code examples below assume you have already executed the examples in the previous section. Here is a short summary recapping what you need: +아래 코드 예제는 이미 이전 섹션의 예제를 실행했다고 가정합니다. 필요한 것을 요약한 간단한 요약은 다음과 같습니다: ```py from datasets import load_dataset @@ -38,9 +38,9 @@ tokenized_datasets = raw_datasets.map(tokenize_function, batched=True) data_collator = DataCollatorWithPadding(tokenizer=tokenizer) ``` -### Training[[training]] +### 훈련[[training]] -The first step before we can define our `Trainer` is to define a `TrainingArguments` class that will contain all the hyperparameters the `Trainer` will use for training and evaluation. The only argument you have to provide is a directory where the trained model will be saved, as well as the checkpoints along the way. For all the rest, you can leave the defaults, which should work pretty well for a basic fine-tuning. +`Trainer`를 정의하기 전 첫 번째 단계는 `Trainer`가 훈련 및 평가에 사용할 모든 하이퍼파라미터를 포함하는 `TrainingArguments` 클래스를 정의하는 것입니다. 제공해야 하는 유일한 인수는 훈련된 모델이 저장될 디렉터리와 그 과정에서 생성되는 체크포인트입니다. 나머지는 기본값으로 둘 수 있으며, 이는 기본 미세 조정에서 꽤 잘 작동합니다. ```py from transformers import TrainingArguments @@ -48,15 +48,15 @@ from transformers import TrainingArguments training_args = TrainingArguments("test-trainer") ``` -If you want to automatically upload your model to the Hub during training, pass along `push_to_hub=True` in the `TrainingArguments`. We will learn more about this in [Chapter 4](/course/chapter4/3) +훈련 중에 모델을 Hub에 자동으로 업로드하려면 `TrainingArguments`에서 `push_to_hub=True`를 전달하세요. 이에 대해서는 [Chapter 4](/course/chapter4/3)에서 자세히 알아보겠습니다. -🚀 **Advanced Configuration**: For detailed information on all available training arguments and optimization strategies, check out the [TrainingArguments documentation](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments) and the [training configuration cookbook](https://huggingface.co/learn/cookbook/en/fine_tuning_code_llm_on_single_gpu). +🚀 **고급 구성**: 사용 가능한 모든 훈련 인수와 최적화 전략에 대한 자세한 정보는 [TrainingArguments 문서](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments)와 [훈련 구성 쿡북](https://huggingface.co/learn/cookbook/en/fine_tuning_code_llm_on_single_gpu)을 확인하세요. -The second step is to define our model. As in the [previous chapter](/course/chapter2), we will use the `AutoModelForSequenceClassification` class, with two labels: +두 번째 단계는 모델을 정의하는 것입니다. [이전 챕터](/course/chapter2)에서와 같이 두 개의 라벨과 함께 `AutoModelForSequenceClassification` 클래스를 사용하겠습니다: ```py from transformers import AutoModelForSequenceClassification @@ -64,9 +64,9 @@ from transformers import AutoModelForSequenceClassification model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) ``` -You will notice that unlike in [Chapter 2](/course/chapter2), you get a warning after instantiating this pretrained model. This is because BERT has not been pretrained on classifying pairs of sentences, so the head of the pretrained model has been discarded and a new head suitable for sequence classification has been added instead. The warnings indicate that some weights were not used (the ones corresponding to the dropped pretraining head) and that some others were randomly initialized (the ones for the new head). It concludes by encouraging you to train the model, which is exactly what we are going to do now. +[Chapter 2](/course/chapter2)와 달리 이 사전 학습된 모델을 인스턴스화한 후 경고가 나타나는 것을 확인할 수 있습니다. 이는 BERT가 문장 쌍 분류에 대해 사전 학습되지 않았기 때문에 사전 학습된 모델의 헤드가 제거되고 시퀀스 분류에 적합한 새로운 헤드가 대신 추가되었기 때문입니다. 경고는 일부 가중치가 사용되지 않았으며 (제거된 사전 학습 헤드에 해당하는 가중치) 일부 다른 가중치가 무작위로 초기화되었음을 나타냅니다 (새로운 헤드의 가중치). 모델을 훈련하도록 권장하며 이는 정확히 우리가 지금 하려는 것입니다. -Once we have our model, we can define a `Trainer` by passing it all the objects constructed up to now — the `model`, the `training_args`, the training and validation datasets, our `data_collator`, and our `processing_class`. The `processing_class` parameter is a newer addition that tells the Trainer which tokenizer to use for processing: +모델이 있으면 지금까지 구성한 모든 객체(`model`, `training_args`, 훈련 및 검증 데이터셋, `data_collator`, `processing_class`)를 전달하여 `Trainer`를 정의할 수 있습니다. `processing_class` 매개변수는 처리에 사용할 토크나이저를 Trainer에 알려주는 새로운 추가 사항입니다: ```py from transformers import Trainer @@ -81,29 +81,29 @@ trainer = Trainer( ) ``` -When you pass a tokenizer as the `processing_class`, the default `data_collator` used by the `Trainer` will be a `DataCollatorWithPadding`. You can skip the `data_collator=data_collator` line in this case, but we included it here to show you this important part of the processing pipeline. +토크나이저를 `processing_class`로 전달하면 `Trainer`에서 사용하는 기본 `data_collator`가 `DataCollatorWithPadding`이 됩니다. 이 경우 `data_collator=data_collator` 줄을 생략할 수 있지만, 처리 파이프라인의 이 중요한 부분을 보여주기 위해 여기에 포함했습니다. -📖 **Learn More**: For comprehensive details on the Trainer class and its parameters, visit the [Trainer API documentation](https://huggingface.co/docs/transformers/main/en/main_classes/trainer) and explore advanced usage patterns in the [training cookbook recipes](https://huggingface.co/learn/cookbook/en/fine_tuning_code_llm_on_single_gpu). +📖 **더 자세히 알아보기**: Trainer 클래스와 그 매개변수에 대한 포괄적인 세부 정보는 [Trainer API 문서](https://huggingface.co/docs/transformers/main/en/main_classes/trainer)를 방문하고 [훈련 쿡북 레시피](https://huggingface.co/learn/cookbook/en/fine_tuning_code_llm_on_single_gpu)에서 고급 사용 패턴을 살펴보세요. -To fine-tune the model on our dataset, we just have to call the `train()` method of our `Trainer`: +데이터셋에서 모델을 파인튜닝하려면 `Trainer`의 `train()` 메서드를 호출하기만 하면 됩니다: ```py trainer.train() ``` -This will start the fine-tuning (which should take a couple of minutes on a GPU) and report the training loss every 500 steps. It won't, however, tell you how well (or badly) your model is performing. This is because: +이렇게 하면 파인튜닝이 시작되고 (GPU에서 몇 분 정도 걸림) 500 스텝마다 훈련 손실을 보고합니다. 하지만 모델이 얼마나 잘 (또는 나쁘게) 수행되고 있는지는 알려주지 않습니다. 그 이유는 다음과 같습니다: -1. We didn't tell the `Trainer` to evaluate during training by setting `eval_strategy` in `TrainingArguments` to either `"steps"` (evaluate every `eval_steps`) or `"epoch"` (evaluate at the end of each epoch). -2. We didn't provide the `Trainer` with a `compute_metrics()` function to calculate a metric during said evaluation (otherwise the evaluation would just have printed the loss, which is not a very intuitive number). +1. `TrainingArguments`에서 `eval_strategy`를 `"steps"` (매 `eval_steps`마다 평가) 또는 `"epoch"` (각 에포크 종료 시 평가)로 설정하여 훈련 중에 평가하도록 `Trainer`에 알리지 않았습니다. +2. 해당 평가 중에 메트릭을 계산하기 위한 `compute_metrics()` 함수를 `Trainer`에 제공하지 않았습니다 (그렇지 않으면 평가에서 손실만 출력되는데, 이는 직관적이지 않은 숫자입니다). -### Evaluation[[evaluation]] +### 평가[[evaluation]] -Let's see how we can build a useful `compute_metrics()` function and use it the next time we train. The function must take an `EvalPrediction` object (which is a named tuple with a `predictions` field and a `label_ids` field) and will return a dictionary mapping strings to floats (the strings being the names of the metrics returned, and the floats their values). To get some predictions from our model, we can use the `Trainer.predict()` command: +유용한 `compute_metrics()` 함수를 빌드하고 다음 번 훈련에서 사용하는 방법을 살펴보겠습니다. 이 함수는 `EvalPrediction` 객체(`predictions` 필드와 `label_ids` 필드가 있는 명명된 튜플)를 받아야 하며 문자열을 플로트에 매핑하는 딕셔너리를 반환합니다 (문자열은 반환되는 메트릭의 이름이고 플로트는 그 값입니다). 모델에서 일부 예측을 얻으려면 `Trainer.predict()` 명령을 사용할 수 있습니다: ```py predictions = trainer.predict(tokenized_datasets["validation"]) @@ -114,9 +114,9 @@ print(predictions.predictions.shape, predictions.label_ids.shape) (408, 2) (408,) ``` -The output of the `predict()` method is another named tuple with three fields: `predictions`, `label_ids`, and `metrics`. The `metrics` field will just contain the loss on the dataset passed, as well as some time metrics (how long it took to predict, in total and on average). Once we complete our `compute_metrics()` function and pass it to the `Trainer`, that field will also contain the metrics returned by `compute_metrics()`. +`predict()` 메서드의 출력은 `predictions`, `label_ids`, `metrics` 세 개의 필드가 있는 또 다른 명명된 튜플입니다. `metrics` 필드는 전달된 데이터셋의 손실과 일부 시간 메트릭 (예측하는 데 걸린 시간, 총 시간 및 평균 시간)만 포함합니다. `compute_metrics()` 함수를 완료하고 `Trainer`에 전달하면 해당 필드에는 `compute_metrics()`에서 반환된 메트릭도 포함됩니다. -As you can see, `predictions` is a two-dimensional array with shape 408 x 2 (408 being the number of elements in the dataset we used). Those are the logits for each element of the dataset we passed to `predict()` (as you saw in the [previous chapter](/course/chapter2), all Transformer models return logits). To transform them into predictions that we can compare to our labels, we need to take the index with the maximum value on the second axis: +보시다시피 `predictions`는 408 x 2 모양의 2차원 배열입니다 (408은 사용한 데이터셋의 요소 수). 이는 `predict()`에 전달한 데이터셋의 각 요소에 대한 로짓입니다 ([이전 챕터](/course/chapter2)에서 보았듯이 모든 Transformer 모델은 로짓을 반환합니다). 라벨과 비교할 수 있는 예측으로 변환하려면 두 번째 축에서 최대값의 인덱스를 가져와야 합니다: ```py import numpy as np @@ -124,7 +124,7 @@ import numpy as np preds = np.argmax(predictions.predictions, axis=-1) ``` -We can now compare those `preds` to the labels. To build our `compute_metric()` function, we will rely on the metrics from the 🤗 [Evaluate](https://github.com/huggingface/evaluate/) library. We can load the metrics associated with the MRPC dataset as easily as we loaded the dataset, this time with the `evaluate.load()` function. The object returned has a `compute()` method we can use to do the metric calculation: +이제 이 `preds`를 라벨과 비교할 수 있습니다. `compute_metric()` 함수를 빌드하기 위해 🤗 [Evaluate](https://github.com/huggingface/evaluate/) 라이브러리의 메트릭을 활용하겠습니다. 데이터셋을 로드한 것처럼 쉽게 MRPC 데이터셋과 연관된 메트릭을 로드할 수 있습니다. 이번에는 `evaluate.load()` 함수를 사용합니다. 반환된 객체에는 메트릭 계산에 사용할 수 있는 `compute()` 메서드가 있습니다: ```py import evaluate @@ -139,13 +139,13 @@ metric.compute(predictions=preds, references=predictions.label_ids) -Learn about different evaluation metrics and strategies in the [🤗 Evaluate documentation](https://huggingface.co/docs/evaluate/). +다양한 평가 메트릭과 전략에 대해 [🤗 Evaluate 문서](https://huggingface.co/docs/evaluate/)에서 알아보세요. -The exact results you get may vary, as the random initialization of the model head might change the metrics it achieved. Here, we can see our model has an accuracy of 85.78% on the validation set and an F1 score of 89.97. Those are the two metrics used to evaluate results on the MRPC dataset for the GLUE benchmark. The table in the [BERT paper](https://arxiv.org/pdf/1810.04805.pdf) reported an F1 score of 88.9 for the base model. That was the `uncased` model while we are currently using the `cased` model, which explains the better result. +모델 헤드의 무작위 초기화가 달성한 메트릭을 변경할 수 있으므로 정확한 결과는 달라질 수 있습니다. 여기서 모델이 검증 세트에서 85.78%의 정확도와 89.97의 F1 점수를 가지고 있음을 확인할 수 있습니다. 이는 GLUE 벤치마크의 MRPC 데이터셋에서 결과를 평가하는 데 사용되는 두 가지 메트릭입니다. [BERT 논문](https://arxiv.org/pdf/1810.04805.pdf)의 표에는 기본 모델에 대해 88.9의 F1 점수가 보고되었습니다. 그것은 `uncased` 모델이었지만 현재 `cased` 모델을 사용하고 있어 더 나은 결과를 설명합니다. -Wrapping everything together, we get our `compute_metrics()` function: +모든 것을 함께 래핑하면 `compute_metrics()` 함수를 얻습니다: ```py def compute_metrics(eval_preds): @@ -155,7 +155,7 @@ def compute_metrics(eval_preds): return metric.compute(predictions=predictions, references=labels) ``` -And to see it used in action to report metrics at the end of each epoch, here is how we define a new `Trainer` with this `compute_metrics()` function: +그리고 각 에포크 종료 시 메트릭을 보고하는 데 사용되는 것을 보려면 이 `compute_metrics()` 함수로 새로운 `Trainer`를 정의하는 방법은 다음과 같습니다: ```py training_args = TrainingArguments("test-trainer", eval_strategy="epoch") @@ -172,222 +172,222 @@ trainer = Trainer( ) ``` -Note that we create a new `TrainingArguments` with its `eval_strategy` set to `"epoch"` and a new model — otherwise, we would just be continuing the training of the model we have already trained. To launch a new training run, we execute: +`eval_strategy`가 `"epoch"`로 설정된 새로운 `TrainingArguments`와 새로운 모델을 만든다는 점에 주목하세요. 그렇지 않으면 이미 훈련한 모델의 훈련을 계속하는 것입니다. 새로운 훈련 실행을 시작하려면 다음을 실행합니다: ```py trainer.train() ``` -This time, it will report the validation loss and metrics at the end of each epoch on top of the training loss. Again, the exact accuracy/F1 score you reach might be a bit different from what we found, because of the random head initialization of the model, but it should be in the same ballpark. +이번에는 훈련 손실 외에 각 에포크 종료 시 검증 손실과 메트릭을 보고합니다. 다시 말하지만, 모델의 무작위 헤드 초기화로 인해 달성하는 정확한 정확도/F1 점수는 우리가 발견한 것과 약간 다를 수 있지만 같은 수준이어야 합니다. -### Advanced Training Features[[advanced-training-features]] +### 고급 훈련 기능[[advanced-training-features]] -The `Trainer` comes with many built-in features that make modern deep learning best practices accessible: +`Trainer`는 최신 딥러닝 모범 사례를 접근 가능하게 만드는 많은 내장 기능을 제공합니다: -**Mixed Precision Training**: Use `fp16=True` in your training arguments for faster training and reduced memory usage: +**혼합 정밀도 훈련**: 더 빠른 훈련과 메모리 사용량 감소를 위해 훈련 인수에서 `fp16=True`를 사용하세요: ```py training_args = TrainingArguments( "test-trainer", eval_strategy="epoch", - fp16=True, # Enable mixed precision + fp16=True, # 혼합 정밀도 활성화 ) ``` -**Gradient Accumulation**: For effective larger batch sizes when GPU memory is limited: +**그래디언트 누적**: GPU 메모리가 제한될 때 효과적인 더 큰 배치 크기를 위해: ```py training_args = TrainingArguments( "test-trainer", eval_strategy="epoch", per_device_train_batch_size=4, - gradient_accumulation_steps=4, # Effective batch size = 4 * 4 = 16 + gradient_accumulation_steps=4, # 효과적인 배치 크기 = 4 * 4 = 16 ) ``` -**Learning Rate Scheduling**: The Trainer uses linear decay by default, but you can customize this: +**학습률 스케줄링**: Trainer는 기본적으로 선형 감소를 사용하지만 이를 사용자 정의할 수 있습니다: ```py training_args = TrainingArguments( "test-trainer", eval_strategy="epoch", learning_rate=2e-5, - lr_scheduler_type="cosine", # Try different schedulers + lr_scheduler_type="cosine", # 다른 스케줄러 시도 ) ``` -🎯 **Performance Optimization**: For more advanced training techniques including distributed training, memory optimization, and hardware-specific optimizations, explore the [🤗 Transformers performance guide](https://huggingface.co/docs/transformers/main/en/performance). +🎯 **성능 최적화**: 분산 훈련, 메모리 최적화, 하드웨어별 최적화를 포함한 고급 훈련 기술에 대해서는 [🤗 Transformers 성능 가이드](https://huggingface.co/docs/transformers/main/en/performance)를 살펴보세요. -The `Trainer` will work out of the box on multiple GPUs or TPUs and provides lots of options for distributed training. We will go over everything it supports in Chapter 10. +`Trainer`는 여러 GPU 또는 TPU에서 즉시 작동하며 분산 훈련을 위한 많은 옵션을 제공합니다. 지원하는 모든 것에 대해서는 Chapter 10에서 다루겠습니다. -This concludes the introduction to fine-tuning using the `Trainer` API. An example of doing this for most common NLP tasks will be given in [Chapter 7](/course/chapter7), but for now let's look at how to do the same thing with a pure PyTorch training loop. +이것으로 `Trainer` API를 사용한 파인튜닝에 대한 소개를 마칩니다. 가장 일반적인 NLP 작업에 대해 이를 수행하는 예제는 [Chapter 7](/course/chapter7)에서 제공되지만, 지금은 순수 PyTorch 훈련 루프로 동일한 작업을 수행하는 방법을 살펴보겠습니다. -📝 **More Examples**: Check out the comprehensive collection of [🤗 Transformers notebooks](https://huggingface.co/docs/transformers/main/en/notebooks). +📝 **더 많은 예제**: [🤗 Transformers 노트북](https://huggingface.co/docs/transformers/main/en/notebooks)의 포괄적인 컬렉션을 확인하세요. -## Section Quiz[[section-quiz]] +## 섹션 퀴즈[[section-quiz]] -Test your understanding of the Trainer API and fine-tuning concepts: +Trainer API와 파인튜닝 개념에 대한 이해를 테스트해보세요: -### 1. What is the purpose of the processing_class parameter in the Trainer? +### 1. processing_class 매개변수의 목적은 무엇인가요? -### 2. Which TrainingArguments parameter controls how often evaluation occurs during training? +### 2. 훈련 중 평가가 얼마나 자주 발생하는지 제어하는 TrainingArguments 매개변수는 무엇인가요? -### 3. What does fp16=True in TrainingArguments enable? +### 3. TrainingArguments에서 fp16=True는 무엇을 활성화하나요? -### 4. What is the role of the compute_metrics function in the Trainer? +### 4. Trainer에서 compute_metrics 함수의 역할은 무엇인가요? -### 5. What happens when you don't provide an eval_dataset to the Trainer? +### 5. Trainer에 eval_dataset을 제공하지 않으면 어떻게 되나요? -### 6. What is gradient accumulation and how do you enable it? +### 6. 그래디언트 누적이란 무엇이며 어떻게 활성화하나요? -💡 **Key Takeaways:** -- The `Trainer` API provides a high-level interface that handles most training complexity -- Use `processing_class` to specify your tokenizer for proper data handling -- `TrainingArguments` controls all aspects of training: learning rate, batch size, evaluation strategy, and optimizations -- `compute_metrics` enables custom evaluation metrics beyond just training loss -- Modern features like mixed precision (`fp16=True`) and gradient accumulation can significantly improve training efficiency +💡 **핵심 요점:** +- `Trainer` API는 대부분의 훈련 복잡성을 처리하는 고수준 인터페이스를 제공합니다 +- 적절한 데이터 처리를 위해 `processing_class`를 사용하여 토크나이저를 지정하세요 +- `TrainingArguments`는 학습률, 배치 크기, 평가 전략, 최적화 등 훈련의 모든 측면을 제어합니다 +- `compute_metrics`는 단순한 훈련 손실 외에 사용자 정의 평가 메트릭을 활성화합니다 +- 혼합 정밀도(`fp16=True`)와 그래디언트 누적과 같은 최신 기능은 훈련 효율성을 크게 향상시킬 수 있습니다 From ee3f18f3762b488a2ca9afe26bb2a1beac528f68 Mon Sep 17 00:00:00 2001 From: Chaewon Song Date: Sat, 19 Jul 2025 15:39:48 +0900 Subject: [PATCH 12/43] docs: ko: processing_the_data.md --- chapters/ko/_toctree.yml | 5 + chapters/ko/chapter3/2.mdx | 446 +++++++++++++++++++++++++++++++++++++ 2 files changed, 451 insertions(+) create mode 100644 chapters/ko/chapter3/2.mdx diff --git a/chapters/ko/_toctree.yml b/chapters/ko/_toctree.yml index 7a523be1c..29659df4f 100644 --- a/chapters/ko/_toctree.yml +++ b/chapters/ko/_toctree.yml @@ -47,6 +47,11 @@ title: 단원 마무리 퀴즈 quiz: 2 +- title: 3. 사전훈련된 모델 미세 조정 + sections: + - local: chapter3/2 + title: 데이터 처리 + - title: 5. 🤗 Datasets 라이브러리 sections: - local: chapter5/1 diff --git a/chapters/ko/chapter3/2.mdx b/chapters/ko/chapter3/2.mdx new file mode 100644 index 000000000..bc1b00179 --- /dev/null +++ b/chapters/ko/chapter3/2.mdx @@ -0,0 +1,446 @@ +# Processing the data[[processing-the-data]] + + + +Continuing with the example from the [previous chapter](/course/chapter2), here is how we would train a sequence classifier on one batch: + +```python +import torch +from torch.optim import AdamW +from transformers import AutoTokenizer, AutoModelForSequenceClassification + +# Same as before +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.", + "This course is amazing!", +] +batch = tokenizer(sequences, padding=True, truncation=True, return_tensors="pt") + +# This is new +batch["labels"] = torch.tensor([1, 1]) + +optimizer = AdamW(model.parameters()) +loss = model(**batch).loss +loss.backward() +optimizer.step() +``` + +Of course, just training the model on two sentences is not going to yield very good results. To get better results, you will need to prepare a bigger dataset. + +In this section we will use as an example the MRPC (Microsoft Research Paraphrase Corpus) dataset, introduced in a [paper](https://www.aclweb.org/anthology/I05-5002.pdf) by William B. Dolan and Chris Brockett. The dataset consists of 5,801 pairs of sentences, with a label indicating if they are paraphrases or not (i.e., if both sentences mean the same thing). We've selected it for this chapter because it's a small dataset, so it's easy to experiment with training on it. + +### Loading a dataset from the Hub[[loading-a-dataset-from-the-hub]] + + + +The Hub doesn't just contain models; it also has multiple datasets in lots of different languages. You can browse the datasets [here](https://huggingface.co/datasets), and we recommend you try to load and process a new dataset once you have gone through this section (see the general documentation [here](https://huggingface.co/docs/datasets/loading)). But for now, let's focus on the MRPC dataset! This is one of the 10 datasets composing the [GLUE benchmark](https://gluebenchmark.com/), which is an academic benchmark that is used to measure the performance of ML models across 10 different text classification tasks. + +The 🤗 Datasets library provides a very simple command to download and cache a dataset on the Hub. We can download the MRPC dataset like this: + + + +💡 **Additional Resources**: For more dataset loading techniques and examples, check out the [🤗 Datasets documentation](https://huggingface.co/docs/datasets/). + + + +```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 + }) +}) +``` + +As you can see, we get a `DatasetDict` object which contains the training set, the validation set, and the test set. Each of those contains several columns (`sentence1`, `sentence2`, `label`, and `idx`) and a variable number of rows, which are the number of elements in each set (so, there are 3,668 pairs of sentences in the training set, 408 in the validation set, and 1,725 in the test set). + + + +This command downloads and caches the dataset, by default in *~/.cache/huggingface/datasets*. Recall from Chapter 2 that you can customize your cache folder by setting the `HF_HOME` environment variable. + + + +We can access each pair of sentences in our `raw_datasets` object by indexing, like with a dictionary: + +```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 .'} +``` + +We can see the labels are already integers, so we won't have to do any preprocessing there. To know which integer corresponds to which label, we can inspect the `features` of our `raw_train_dataset`. This will tell us the type of each column: + +```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)} +``` + +Behind the scenes, `label` is of type `ClassLabel`, and the mapping of integers to label name is stored in the *names* folder. `0` corresponds to `not_equivalent`, and `1` corresponds to `equivalent`. + + + +✏️ **Try it out!** Look at element 15 of the training set and element 87 of the validation set. What are their labels? + + + +### Preprocessing a dataset[[preprocessing-a-dataset]] + + + +To preprocess the dataset, we need to convert the text to numbers the model can make sense of. As you saw in the [previous chapter](/course/chapter2), this is done with a tokenizer. We can feed the tokenizer one sentence or a list of sentences, so we can directly tokenize all the first sentences and all the second sentences of each pair like this: + +```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"]) +``` + + + +💡 **Deep Dive**: For more advanced tokenization techniques and understanding how different tokenizers work, explore the [🤗 Tokenizers documentation](https://huggingface.co/docs/transformers/main/en/tokenizer_summary) and the [tokenization guide in the cookbook](https://huggingface.co/learn/cookbook/en/advanced_rag#tokenization-strategies). + + + +However, we can't just pass two sequences to the model and get a prediction of whether the two sentences are paraphrases or not. We need to handle the two sequences as a pair, and apply the appropriate preprocessing. Fortunately, the tokenizer can also take a pair of sequences and prepare it the way our BERT model expects: + +```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] +} +``` + +We discussed the `input_ids` and `attention_mask` keys in [Chapter 2](/course/chapter2), but we put off talking about `token_type_ids`. In this example, this is what tells the model which part of the input is the first sentence and which is the second sentence. + + + +✏️ **Try it out!** Take element 15 of the training set and tokenize the two sentences separately and as a pair. What's the difference between the two results? + + + +If we decode the IDs inside `input_ids` back to words: + +```py +tokenizer.convert_ids_to_tokens(inputs["input_ids"]) +``` + +we will get: + +```python out +['[CLS]', 'this', 'is', 'the', 'first', 'sentence', '.', '[SEP]', 'this', 'is', 'the', 'second', 'one', '.', '[SEP]'] +``` + +So we see the model expects the inputs to be of the form `[CLS] sentence1 [SEP] sentence2 [SEP]` when there are two sentences. Aligning this with the `token_type_ids` gives us: + +```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] +``` + +As you can see, the parts of the input corresponding to `[CLS] sentence1 [SEP]` all have a token type ID of `0`, while the other parts, corresponding to `sentence2 [SEP]`, all have a token type ID of `1`. + +Note that if you select a different checkpoint, you won't necessarily have the `token_type_ids` in your tokenized inputs (for instance, they're not returned if you use a DistilBERT model). They are only returned when the model will know what to do with them, because it has seen them during its pretraining. + +Here, BERT is pretrained with token type IDs, and on top of the masked language modeling objective we talked about in [Chapter 1](/course/chapter1), it has an additional objective called _next sentence prediction_. The goal with this task is to model the relationship between pairs of sentences. + +With next sentence prediction, the model is provided pairs of sentences (with randomly masked tokens) and asked to predict whether the second sentence follows the first. To make the task non-trivial, half of the time the sentences follow each other in the original document they were extracted from, and the other half of the time the two sentences come from two different documents. + +In general, you don't need to worry about whether or not there are `token_type_ids` in your tokenized inputs: as long as you use the same checkpoint for the tokenizer and the model, everything will be fine as the tokenizer knows what to provide to its model. + +Now that we have seen how our tokenizer can deal with one pair of sentences, we can use it to tokenize our whole dataset: like in the [previous chapter](/course/chapter2), we can feed the tokenizer a list of pairs of sentences by giving it the list of first sentences, then the list of second sentences. This is also compatible with the padding and truncation options we saw in [Chapter 2](/course/chapter2). So, one way to preprocess the training dataset is: + +```py +tokenized_dataset = tokenizer( + raw_datasets["train"]["sentence1"], + raw_datasets["train"]["sentence2"], + padding=True, + truncation=True, +) +``` + +This works well, but it has the disadvantage of returning a dictionary (with our keys, `input_ids`, `attention_mask`, and `token_type_ids`, and values that are lists of lists). It will also only work if you have enough RAM to store your whole dataset during the tokenization (whereas the datasets from the 🤗 Datasets library are [Apache Arrow](https://arrow.apache.org/) files stored on the disk, so you only keep the samples you ask for loaded in memory). + +To keep the data as a dataset, we will use the [`Dataset.map()`](https://huggingface.co/docs/datasets/package_reference/main_classes#datasets.Dataset.map) method. This also allows us some extra flexibility, if we need more preprocessing done than just tokenization. The `map()` method works by applying a function on each element of the dataset, so let's define a function that tokenizes our inputs: + +```py +def tokenize_function(example): + return tokenizer(example["sentence1"], example["sentence2"], truncation=True) +``` + +This function takes a dictionary (like the items of our dataset) and returns a new dictionary with the keys `input_ids`, `attention_mask`, and `token_type_ids`. Note that it also works if the `example` dictionary contains several samples (each key as a list of sentences) since the `tokenizer` works on lists of pairs of sentences, as seen before. This will allow us to use the option `batched=True` in our call to `map()`, which will greatly speed up the tokenization. The `tokenizer` is backed by a tokenizer written in Rust from the [🤗 Tokenizers](https://github.com/huggingface/tokenizers) library. This tokenizer can be very fast, but only if we give it lots of inputs at once. + +Note that we've left the `padding` argument out in our tokenization function for now. This is because padding all the samples to the maximum length is not efficient: it's better to pad the samples when we're building a batch, as then we only need to pad to the maximum length in that batch, and not the maximum length in the entire dataset. This can save a lot of time and processing power when the inputs have very variable lengths! + + + +📚 **Performance Tips**: Learn more about efficient data processing techniques in the [🤗 Datasets performance guide](https://huggingface.co/docs/datasets/about_arrow). + + + +Here is how we apply the tokenization function on all our datasets at once. We're using `batched=True` in our call to `map` so the function is applied to multiple elements of our dataset at once, and not on each element separately. This allows for faster preprocessing. + +```py +tokenized_datasets = raw_datasets.map(tokenize_function, batched=True) +tokenized_datasets +``` + +The way the 🤗 Datasets library applies this processing is by adding new fields to the datasets, one for each key in the dictionary returned by the preprocessing function: + +```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 + }) +}) +``` + +You can even use multiprocessing when applying your preprocessing function with `map()` by passing along a `num_proc` argument. We didn't do this here because the 🤗 Tokenizers library already uses multiple threads to tokenize our samples faster, but if you are not using a fast tokenizer backed by this library, this could speed up your preprocessing. + +Our `tokenize_function` returns a dictionary with the keys `input_ids`, `attention_mask`, and `token_type_ids`, so those three fields are added to all splits of our dataset. Note that we could also have changed existing fields if our preprocessing function returned a new value for an existing key in the dataset to which we applied `map()`. + +The last thing we will need to do is pad all the examples to the length of the longest element when we batch elements together — a technique we refer to as *dynamic padding*. + +##### Dynamic padding[[dynamic-padding]] + + + +The function that is responsible for putting together samples inside a batch is called a *collate function*. It's an argument you can pass when you build a `DataLoader`, the default being a function that will just convert your samples to PyTorch tensors and concatenate them (recursively if your elements are lists, tuples, or dictionaries). This won't be possible in our case since the inputs we have won't all be of the same size. We have deliberately postponed the padding, to only apply it as necessary on each batch and avoid having over-long inputs with a lot of padding. This will speed up training by quite a bit, but note that if you're training on a TPU it can cause problems — TPUs prefer fixed shapes, even when that requires extra padding. + + + +🚀 **Optimization Guide**: For more details on optimizing training performance, including padding strategies and TPU considerations, see the [🤗 Transformers performance documentation](https://huggingface.co/docs/transformers/main/en/performance). + + + +To do this in practice, we have to define a collate function that will apply the correct amount of padding to the items of the dataset we want to batch together. Fortunately, the 🤗 Transformers library provides us with such a function via `DataCollatorWithPadding`. It takes a tokenizer when you instantiate it (to know which padding token to use, and whether the model expects padding to be on the left or on the right of the inputs) and will do everything you need: + +```py +from transformers import DataCollatorWithPadding + +data_collator = DataCollatorWithPadding(tokenizer=tokenizer) +``` + +To test this new toy, let's grab a few samples from our training set that we would like to batch together. Here, we remove the columns `idx`, `sentence1`, and `sentence2` as they won't be needed and contain strings (and we can't create tensors with strings) and have a look at the lengths of each entry in the batch: + +```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] +``` + +No surprise, we get samples of varying length, from 32 to 67. Dynamic padding means the samples in this batch should all be padded to a length of 67, the maximum length inside the batch. Without dynamic padding, all of the samples would have to be padded to the maximum length in the whole dataset, or the maximum length the model can accept. Let's double-check that our `data_collator` is dynamically padding the batch properly: + +```py +batch = data_collator(samples) +{k: v.shape for k, v in batch.items()} +``` + +```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])} +``` + +Looking good! Now that we've gone from raw text to batches our model can deal with, we're ready to fine-tune it! + + + +✏️ **Try it out!** Replicate the preprocessing on the GLUE SST-2 dataset. It's a little bit different since it's composed of single sentences instead of pairs, but the rest of what we did should look the same. For a harder challenge, try to write a preprocessing function that works on any of the GLUE tasks. + +📖 **Additional Practice**: Check out these hands-on examples from the [🤗 Transformers examples](https://huggingface.co/docs/transformers/main/en/notebooks). + + + +Perfect! Now that we have preprocessed our data with the latest best practices from the 🤗 Datasets library, we're ready to move on to training our model using the modern Trainer API. The next section will show you how to fine-tune your model effectively using the latest features and optimizations available in the Hugging Face ecosystem. + +## Section Quiz[[section-quiz]] + +Test your understanding of data processing concepts: + +### 1. What is the main advantage of using `Dataset.map()` with `batched=True`? + + + +### 2. Why do we use dynamic padding instead of padding all sequences to the maximum length in the dataset? + + + +### 3. What does the `token_type_ids` field represent in BERT tokenization? + + + +### 4. When loading a dataset with `load_dataset('glue', 'mrpc')`, what does the second argument specify? + + + +### 5. What is the purpose of removing columns like 'sentence1' and 'sentence2' before training? + + + + + +💡 **Key Takeaways:** +- Use `batched=True` with `Dataset.map()` for significantly faster preprocessing +- Dynamic padding with `DataCollatorWithPadding` is more efficient than fixed-length padding +- Always preprocess your data to match what your model expects (numerical tensors, correct column names) +- The 🤗 Datasets library provides powerful tools for efficient data processing at scale + + From fcb2e2b38b70769e5568f99e84d3585fe6b3fd87 Mon Sep 17 00:00:00 2001 From: Chaewon Song Date: Sat, 19 Jul 2025 15:54:10 +0900 Subject: [PATCH 13/43] feat: nmt draft --- chapters/ko/chapter3/2.mdx | 208 ++++++++++++++++++------------------- 1 file changed, 104 insertions(+), 104 deletions(-) diff --git a/chapters/ko/chapter3/2.mdx b/chapters/ko/chapter3/2.mdx index bc1b00179..cef0967dc 100644 --- a/chapters/ko/chapter3/2.mdx +++ b/chapters/ko/chapter3/2.mdx @@ -1,4 +1,4 @@ -# Processing the data[[processing-the-data]] +# 데이터 처리[[processing-the-data]] -Continuing with the example from the [previous chapter](/course/chapter2), here is how we would train a sequence classifier on one batch: +[이전 챕터](/course/chapter2)의 예제를 이어서, 한 배치에서 시퀀스 분류기를 훈련하는 방법은 다음과 같습니다: ```python import torch from torch.optim import AdamW from transformers import AutoTokenizer, AutoModelForSequenceClassification -# Same as before +# 이전과 동일 checkpoint = "bert-base-uncased" tokenizer = AutoTokenizer.from_pretrained(checkpoint) model = AutoModelForSequenceClassification.from_pretrained(checkpoint) @@ -24,7 +24,7 @@ sequences = [ ] batch = tokenizer(sequences, padding=True, truncation=True, return_tensors="pt") -# This is new +# 여기가 새로운 부분 batch["labels"] = torch.tensor([1, 1]) optimizer = AdamW(model.parameters()) @@ -33,21 +33,21 @@ loss.backward() optimizer.step() ``` -Of course, just training the model on two sentences is not going to yield very good results. To get better results, you will need to prepare a bigger dataset. +물론 두 문장만으로 모델을 훈련하는 것으로는 매우 좋은 결과를 얻을 수 없습니다. 더 나은 결과를 얻으려면 더 큰 데이터 세트를 준비해야 합니다. -In this section we will use as an example the MRPC (Microsoft Research Paraphrase Corpus) dataset, introduced in a [paper](https://www.aclweb.org/anthology/I05-5002.pdf) by William B. Dolan and Chris Brockett. The dataset consists of 5,801 pairs of sentences, with a label indicating if they are paraphrases or not (i.e., if both sentences mean the same thing). We've selected it for this chapter because it's a small dataset, so it's easy to experiment with training on it. +이 섹션에서는 William B. Dolan과 Chris Brockett의 [논문](https://www.aclweb.org/anthology/I05-5002.pdf)에서 소개된 MRPC(Microsoft Research Paraphrase Corpus) 데이터 세트를 예제로 사용하겠습니다. 이 데이터 세트는 5,801개의 문장 쌍으로 구성되어 있으며, 각 쌍이 패러프레이즈인지 아닌지를 나타내는 레이블이 있습니다(즉, 두 문장이 같은 의미인지). 이 챕터에서 이 데이터 세트를 선택한 이유는 작은 데이터 세트이므로 훈련 실험을 하기에 쉽기 때문입니다. -### Loading a dataset from the Hub[[loading-a-dataset-from-the-hub]] +### Hub에서 데이터 세트 가져오기[[loading-a-dataset-from-the-hub]] -The Hub doesn't just contain models; it also has multiple datasets in lots of different languages. You can browse the datasets [here](https://huggingface.co/datasets), and we recommend you try to load and process a new dataset once you have gone through this section (see the general documentation [here](https://huggingface.co/docs/datasets/loading)). But for now, let's focus on the MRPC dataset! This is one of the 10 datasets composing the [GLUE benchmark](https://gluebenchmark.com/), which is an academic benchmark that is used to measure the performance of ML models across 10 different text classification tasks. +Hub에는 모델뿐만 아니라 다양한 언어로 된 여러 데이터 세트도 있습니다. [여기](https://huggingface.co/datasets)에서 데이터 세트를 찾아볼 수 있으며, 이 섹션을 완료한 후에는 새로운 데이터 세트를 로드하고 처리해보는 것을 권장합니다([여기](https://huggingface.co/docs/datasets/loading)에서 일반적인 문서를 참조하세요). 하지만 지금은 MRPC 데이터 세트에 집중해보겠습니다! 이것은 [GLUE 벤치마크](https://gluebenchmark.com/)를 구성하는 10개 데이터 세트 중 하나로, 10개의 서로 다른 텍스트 분류 작업에 걸쳐 ML 모델의 성능을 측정하는 데 사용되는 학술적 벤치마크입니다. -The 🤗 Datasets library provides a very simple command to download and cache a dataset on the Hub. We can download the MRPC dataset like this: +🤗 Datasets 라이브러리는 Hub에서 데이터 세트를 다운로드하고 캐시하는 매우 간단한 명령을 제공합니다. MRPC 데이터 세트를 다음과 같이 다운로드할 수 있습니다: -💡 **Additional Resources**: For more dataset loading techniques and examples, check out the [🤗 Datasets documentation](https://huggingface.co/docs/datasets/). +💡 **추가 자료**: 더 많은 데이터 세트 로딩 기법과 예제를 보려면 [🤗 Datasets 문서](https://huggingface.co/docs/datasets/)를 확인하세요. @@ -75,15 +75,15 @@ DatasetDict({ }) ``` -As you can see, we get a `DatasetDict` object which contains the training set, the validation set, and the test set. Each of those contains several columns (`sentence1`, `sentence2`, `label`, and `idx`) and a variable number of rows, which are the number of elements in each set (so, there are 3,668 pairs of sentences in the training set, 408 in the validation set, and 1,725 in the test set). +보시다시피, 훈련 세트, 검증 세트, 테스트 세트가 포함된 `DatasetDict` 객체를 얻습니다. 각각은 여러 열(`sentence1`, `sentence2`, `label`, `idx`)과 가변적인 행 수를 포함하며, 이는 각 세트의 요소 수입니다(따라서 훈련 세트에는 3,668개의 문장 쌍이, 검증 세트에는 408개가, 테스트 세트에는 1,725개가 있습니다). -This command downloads and caches the dataset, by default in *~/.cache/huggingface/datasets*. Recall from Chapter 2 that you can customize your cache folder by setting the `HF_HOME` environment variable. +이 명령은 기본적으로 *~/.cache/huggingface/datasets*에 데이터 세트를 다운로드하고 캐시합니다. 2장에서 언급했듯이 `HF_HOME` 환경 변수를 설정하여 캐시 폴더를 맞춤 설정할 수 있습니다. -We can access each pair of sentences in our `raw_datasets` object by indexing, like with a dictionary: +딕셔너리처럼 인덱싱하여 `raw_datasets` 객체의 각 문장 쌍에 접근할 수 있습니다: ```py raw_train_dataset = raw_datasets["train"] @@ -97,7 +97,7 @@ raw_train_dataset[0] 'sentence2': 'Referring to him as only " the witness " , Amrozi accused his brother of deliberately distorting his evidence .'} ``` -We can see the labels are already integers, so we won't have to do any preprocessing there. To know which integer corresponds to which label, we can inspect the `features` of our `raw_train_dataset`. This will tell us the type of each column: +레이블이 이미 정수로 되어 있으므로 여기서 전처리를 할 필요가 없습니다. 어떤 정수가 어떤 레이블에 해당하는지 알아보려면 `raw_train_dataset`의 `features`를 검사하면 됩니다. 이것은 각 열의 타입을 알려줍니다: ```py raw_train_dataset.features @@ -110,19 +110,19 @@ raw_train_dataset.features 'idx': Value(dtype='int32', id=None)} ``` -Behind the scenes, `label` is of type `ClassLabel`, and the mapping of integers to label name is stored in the *names* folder. `0` corresponds to `not_equivalent`, and `1` corresponds to `equivalent`. +내부적으로 `label`은 `ClassLabel` 타입이며, 정수와 레이블 이름의 매핑이 *names* 폴더에 저장되어 있습니다. `0`은 `not_equivalent`에, `1`은 `equivalent`에 해당합니다. -✏️ **Try it out!** Look at element 15 of the training set and element 87 of the validation set. What are their labels? +✏️ **직접 해보기!** 훈련 세트의 15번째 요소와 검증 세트의 87번째 요소를 살펴보세요. 그들의 레이블은 무엇인가요? -### Preprocessing a dataset[[preprocessing-a-dataset]] +### 데이터 세트 전처리[[preprocessing-a-dataset]] -To preprocess the dataset, we need to convert the text to numbers the model can make sense of. As you saw in the [previous chapter](/course/chapter2), this is done with a tokenizer. We can feed the tokenizer one sentence or a list of sentences, so we can directly tokenize all the first sentences and all the second sentences of each pair like this: +데이터 세트를 전처리하려면 텍스트를 모델이 이해할 수 있는 숫자로 변환해야 합니다. [이전 챕터](/course/chapter2)에서 보았듯이, 이는 토크나이저로 수행됩니다. 토크나이저에 한 문장이나 문장 목록을 입력할 수 있으므로, 다음과 같이 각 쌍의 모든 첫 번째 문장과 모든 두 번째 문장을 직접 토큰화할 수 있습니다: ```py from transformers import AutoTokenizer @@ -135,11 +135,11 @@ tokenized_sentences_2 = tokenizer(raw_datasets["train"]["sentence2"]) -💡 **Deep Dive**: For more advanced tokenization techniques and understanding how different tokenizers work, explore the [🤗 Tokenizers documentation](https://huggingface.co/docs/transformers/main/en/tokenizer_summary) and the [tokenization guide in the cookbook](https://huggingface.co/learn/cookbook/en/advanced_rag#tokenization-strategies). +💡 **심화 학습**: 더 고급 토큰화 기법과 다양한 토크나이저가 작동하는 방식을 이해하려면 [🤗 Tokenizers 문서](https://huggingface.co/docs/transformers/main/en/tokenizer_summary)와 [쿡북의 토큰화 가이드](https://huggingface.co/learn/cookbook/en/advanced_rag#tokenization-strategies)를 살펴보세요. -However, we can't just pass two sequences to the model and get a prediction of whether the two sentences are paraphrases or not. We need to handle the two sequences as a pair, and apply the appropriate preprocessing. Fortunately, the tokenizer can also take a pair of sequences and prepare it the way our BERT model expects: +하지만 두 시퀀스를 모델에 전달하기만 해서는 두 문장이 패러프레이즈인지 아닌지 예측할 수 없습니다. 두 시퀀스를 쌍으로 처리하고 적절한 전처리를 적용해야 합니다. 다행히 토크나이저는 한 쌍의 시퀀스를 받아서 BERT 모델이 기대하는 방식으로 준비할 수도 있습니다: ```py inputs = tokenizer("This is the first sentence.", "This is the second one.") @@ -154,44 +154,44 @@ inputs } ``` -We discussed the `input_ids` and `attention_mask` keys in [Chapter 2](/course/chapter2), but we put off talking about `token_type_ids`. In this example, this is what tells the model which part of the input is the first sentence and which is the second sentence. +[2장](/course/chapter2)에서 `input_ids`와 `attention_mask` 키에 대해 논의했지만, `token_type_ids`에 대한 이야기는 미뤄두었습니다. 이 예제에서 이것은 입력의 어느 부분이 첫 번째 문장이고 어느 부분이 두 번째 문장인지 모델에 알려주는 역할을 합니다. -✏️ **Try it out!** Take element 15 of the training set and tokenize the two sentences separately and as a pair. What's the difference between the two results? +✏️ **직접 해보기!** 훈련 세트의 15번째 요소를 가져와서 두 문장을 따로따로 토큰화하고 쌍으로도 토큰화해보세요. 두 결과의 차이점은 무엇인가요? -If we decode the IDs inside `input_ids` back to words: +`input_ids` 안의 ID를 다시 단어로 디코딩하면: ```py tokenizer.convert_ids_to_tokens(inputs["input_ids"]) ``` -we will get: +다음을 얻습니다: ```python out ['[CLS]', 'this', 'is', 'the', 'first', 'sentence', '.', '[SEP]', 'this', 'is', 'the', 'second', 'one', '.', '[SEP]'] ``` -So we see the model expects the inputs to be of the form `[CLS] sentence1 [SEP] sentence2 [SEP]` when there are two sentences. Aligning this with the `token_type_ids` gives us: +따라서 모델은 두 문장이 있을 때 입력이 `[CLS] sentence1 [SEP] sentence2 [SEP]` 형태이기를 기대한다는 것을 알 수 있습니다. 이를 `token_type_ids`와 맞춰보면: ```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] ``` -As you can see, the parts of the input corresponding to `[CLS] sentence1 [SEP]` all have a token type ID of `0`, while the other parts, corresponding to `sentence2 [SEP]`, all have a token type ID of `1`. +보시다시피, `[CLS] sentence1 [SEP]`에 해당하는 입력 부분은 모두 토큰 타입 ID가 `0`이고, `sentence2 [SEP]`에 해당하는 다른 부분들은 모두 토큰 타입 ID가 `1`입니다. -Note that if you select a different checkpoint, you won't necessarily have the `token_type_ids` in your tokenized inputs (for instance, they're not returned if you use a DistilBERT model). They are only returned when the model will know what to do with them, because it has seen them during its pretraining. +다른 체크포인트(checkpoint)를 선택하면 토큰화된 입력에 `token_type_ids`가 반드시 있지는 않다는 점에 주의하세요(예를 들어, DistilBERT 모델을 사용하면 반환되지 않습니다). 모델이 사전 훈련 중에 이를 본 적이 있어서 무엇을 해야 할지 알 때만 반환됩니다. -Here, BERT is pretrained with token type IDs, and on top of the masked language modeling objective we talked about in [Chapter 1](/course/chapter1), it has an additional objective called _next sentence prediction_. The goal with this task is to model the relationship between pairs of sentences. +여기서 BERT는 토큰 타입 ID로 사전 훈련되었으며, [1장](/course/chapter1)에서 이야기한 마스크드 언어 모델링 목표 외에도 _다음 문장 예측_이라는 추가 목표를 가지고 있습니다. 이 작업의 목표는 문장 쌍 간의 관계를 모델링하는 것입니다. -With next sentence prediction, the model is provided pairs of sentences (with randomly masked tokens) and asked to predict whether the second sentence follows the first. To make the task non-trivial, half of the time the sentences follow each other in the original document they were extracted from, and the other half of the time the two sentences come from two different documents. +다음 문장 예측에서는 모델에 문장 쌍(무작위로 마스킹된 토큰과 함께)이 제공되고 두 번째 문장이 첫 번째 문장을 따르는지 예측하도록 요청받습니다. 작업을 쉽지 않게 만들기 위해, 절반의 경우에는 문장들이 추출된 원본 문서에서 서로를 따르고, 나머지 절반의 경우에는 두 문장이 서로 다른 문서에서 나옵니다. -In general, you don't need to worry about whether or not there are `token_type_ids` in your tokenized inputs: as long as you use the same checkpoint for the tokenizer and the model, everything will be fine as the tokenizer knows what to provide to its model. +일반적으로 토큰화된 입력에 `token_type_ids`가 있는지 여부에 대해 걱정할 필요는 없습니다: 토크나이저와 모델에 동일한 체크포인트(checkpoint)를 사용하는 한, 토크나이저가 모델에 제공해야 할 것을 알고 있으므로 모든 것이 잘 될 것입니다. -Now that we have seen how our tokenizer can deal with one pair of sentences, we can use it to tokenize our whole dataset: like in the [previous chapter](/course/chapter2), we can feed the tokenizer a list of pairs of sentences by giving it the list of first sentences, then the list of second sentences. This is also compatible with the padding and truncation options we saw in [Chapter 2](/course/chapter2). So, one way to preprocess the training dataset is: +이제 토크나이저가 한 쌍의 문장을 어떻게 처리할 수 있는지 보았으므로, 이를 사용하여 전체 데이터 세트를 토큰화할 수 있습니다: [이전 챕터](/course/chapter2)에서처럼, 첫 번째 문장 목록과 두 번째 문장 목록을 제공하여 토크나이저에 문장 쌍 목록을 입력할 수 있습니다. 이는 [2장](/course/chapter2)에서 본 패딩과 생략 옵션과도 호환됩니다. 따라서 훈련 데이터 세트를 전처리하는 한 가지 방법은: ```py tokenized_dataset = tokenizer( @@ -202,33 +202,33 @@ tokenized_dataset = tokenizer( ) ``` -This works well, but it has the disadvantage of returning a dictionary (with our keys, `input_ids`, `attention_mask`, and `token_type_ids`, and values that are lists of lists). It will also only work if you have enough RAM to store your whole dataset during the tokenization (whereas the datasets from the 🤗 Datasets library are [Apache Arrow](https://arrow.apache.org/) files stored on the disk, so you only keep the samples you ask for loaded in memory). +이것은 잘 작동하지만, 딕셔너리(키는 `input_ids`, `attention_mask`, `token_type_ids`이고 값은 목록의 목록)를 반환한다는 단점이 있습니다. 또한 토큰화 중에 전체 데이터 세트를 메모리에 저장할 수 있는 충분한 RAM이 있는 경우에만 작동합니다(🤗 Datasets 라이브러리의 데이터 세트는 디스크에 저장된 [Apache Arrow](https://arrow.apache.org/) 파일이므로, 요청한 샘플만 메모리에 로드됩니다). -To keep the data as a dataset, we will use the [`Dataset.map()`](https://huggingface.co/docs/datasets/package_reference/main_classes#datasets.Dataset.map) method. This also allows us some extra flexibility, if we need more preprocessing done than just tokenization. The `map()` method works by applying a function on each element of the dataset, so let's define a function that tokenizes our inputs: +데이터를 데이터 세트로 유지하려면 [`Dataset.map()`](https://huggingface.co/docs/datasets/package_reference/main_classes#datasets.Dataset.map) 메소드를 사용하겠습니다. 이는 토큰화 이상의 전처리가 필요한 경우 추가적인 유연성도 제공합니다. `map()` 메소드는 데이터 세트의 각 요소에 함수를 적용하여 작동하므로, 입력을 토큰화하는 함수를 정의해보겠습니다: ```py def tokenize_function(example): return tokenizer(example["sentence1"], example["sentence2"], truncation=True) ``` -This function takes a dictionary (like the items of our dataset) and returns a new dictionary with the keys `input_ids`, `attention_mask`, and `token_type_ids`. Note that it also works if the `example` dictionary contains several samples (each key as a list of sentences) since the `tokenizer` works on lists of pairs of sentences, as seen before. This will allow us to use the option `batched=True` in our call to `map()`, which will greatly speed up the tokenization. The `tokenizer` is backed by a tokenizer written in Rust from the [🤗 Tokenizers](https://github.com/huggingface/tokenizers) library. This tokenizer can be very fast, but only if we give it lots of inputs at once. +이 함수는 딕셔너리(데이터 세트의 항목과 같은)를 받아서 `input_ids`, `attention_mask`, `token_type_ids` 키가 있는 새 딕셔너리를 반환합니다. `example` 딕셔너리에 여러 샘플이 포함되어 있어도(각 키가 문장 목록으로) 작동한다는 점에 주목하세요. 앞서 본 것처럼 `tokenizer`는 문장 쌍의 목록에서 작동하기 때문입니다. 이를 통해 `map()` 호출에서 `batched=True` 옵션을 사용할 수 있으며, 이는 토큰화를 크게 가속화할 것입니다. `tokenizer`는 [🤗 Tokenizers](https://github.com/huggingface/tokenizers) 라이브러리의 Rust로 작성된 토크나이저로 뒷받침됩니다. 이 토크나이저는 매우 빠를 수 있지만, 한 번에 많은 입력을 제공해야만 그렇습니다. -Note that we've left the `padding` argument out in our tokenization function for now. This is because padding all the samples to the maximum length is not efficient: it's better to pad the samples when we're building a batch, as then we only need to pad to the maximum length in that batch, and not the maximum length in the entire dataset. This can save a lot of time and processing power when the inputs have very variable lengths! +지금은 토큰화 함수에서 `padding` 인수를 빼둔 것에 주목하세요. 모든 샘플을 최대 길이로 패딩하는 것은 효율적이지 않기 때문입니다: 배치를 만들 때 샘플을 패딩하는 것이 더 좋습니다. 그러면 해당 배치의 최대 길이까지만 패딩하면 되고, 전체 데이터 세트의 최대 길이까지 패딩할 필요가 없기 때문입니다. 입력의 길이가 매우 다양할 때 많은 시간과 처리 능력을 절약할 수 있습니다! -📚 **Performance Tips**: Learn more about efficient data processing techniques in the [🤗 Datasets performance guide](https://huggingface.co/docs/datasets/about_arrow). +📚 **성능 팁**: 효율적인 데이터 처리 기법에 대한 자세한 내용은 [🤗 Datasets 성능 가이드](https://huggingface.co/docs/datasets/about_arrow)에서 배울 수 있습니다. -Here is how we apply the tokenization function on all our datasets at once. We're using `batched=True` in our call to `map` so the function is applied to multiple elements of our dataset at once, and not on each element separately. This allows for faster preprocessing. +다음은 모든 데이터 세트에 토큰화 함수를 한 번에 적용하는 방법입니다. `map` 호출에서 `batched=True`를 사용하므로 함수가 데이터 세트의 각 요소에 개별적으로가 아니라 여러 요소에 한 번에 적용됩니다. 이를 통해 더 빠른 전처리가 가능합니다. ```py tokenized_datasets = raw_datasets.map(tokenize_function, batched=True) tokenized_datasets ``` -The way the 🤗 Datasets library applies this processing is by adding new fields to the datasets, one for each key in the dictionary returned by the preprocessing function: +🤗 Datasets 라이브러리가 이 처리를 적용하는 방식은 전처리 함수가 반환하는 딕셔너리의 각 키에 대해 데이터 세트에 새 필드를 추가하는 것입니다: ```python out DatasetDict({ @@ -247,25 +247,25 @@ DatasetDict({ }) ``` -You can even use multiprocessing when applying your preprocessing function with `map()` by passing along a `num_proc` argument. We didn't do this here because the 🤗 Tokenizers library already uses multiple threads to tokenize our samples faster, but if you are not using a fast tokenizer backed by this library, this could speed up your preprocessing. +`num_proc` 인수를 전달하여 `map()`으로 전처리 함수를 적용할 때 멀티프로세싱을 사용할 수도 있습니다. 🤗 Tokenizers 라이브러리가 이미 여러 스레드를 사용하여 샘플을 더 빠르게 토큰화하므로 여기서는 이를 사용하지 않았지만, 이 라이브러리가 뒷받침하는 빠른 토크나이저를 사용하지 않는다면 전처리 속도를 높일 수 있습니다. -Our `tokenize_function` returns a dictionary with the keys `input_ids`, `attention_mask`, and `token_type_ids`, so those three fields are added to all splits of our dataset. Note that we could also have changed existing fields if our preprocessing function returned a new value for an existing key in the dataset to which we applied `map()`. +우리의 `tokenize_function`은 `input_ids`, `attention_mask`, `token_type_ids` 키가 있는 딕셔너리를 반환하므로, 이 세 필드가 데이터 세트의 모든 분할에 추가됩니다. 전처리 함수가 `map()`을 적용한 데이터 세트의 기존 키에 대한 새 값을 반환한다면 기존 필드를 변경할 수도 있었을 것입니다. -The last thing we will need to do is pad all the examples to the length of the longest element when we batch elements together — a technique we refer to as *dynamic padding*. +마지막으로 해야 할 일은 요소들을 배치로 묶을 때 모든 예제를 가장 긴 요소의 길이로 패딩하는 것입니다 — 이 기법을 *동적 패딩*이라고 합니다. -##### Dynamic padding[[dynamic-padding]] +##### 동적 패딩[[dynamic-padding]] -The function that is responsible for putting together samples inside a batch is called a *collate function*. It's an argument you can pass when you build a `DataLoader`, the default being a function that will just convert your samples to PyTorch tensors and concatenate them (recursively if your elements are lists, tuples, or dictionaries). This won't be possible in our case since the inputs we have won't all be of the same size. We have deliberately postponed the padding, to only apply it as necessary on each batch and avoid having over-long inputs with a lot of padding. This will speed up training by quite a bit, but note that if you're training on a TPU it can cause problems — TPUs prefer fixed shapes, even when that requires extra padding. +배치 내에서 샘플들을 함께 배치하는 역할을 하는 함수를 *collate function*이라고 합니다. 이는 `DataLoader`를 구축할 때 전달할 수 있는 인수로, 기본값은 샘플을 PyTorch 텐서로 변환하고 연결하는 함수입니다(요소가 목록, 튜플 또는 딕셔너리인 경우 재귀적으로). 우리의 경우 입력이 모두 같은 크기가 아니므로 이것은 불가능할 것입니다. 우리는 의도적으로 패딩을 연기하여 각 배치에서만 필요에 따라 적용하고 많은 패딩이 있는 지나치게 긴 입력을 피했습니다. 이것은 훈련을 상당히 가속화할 것이지만, TPU에서 훈련하는 경우 문제를 일으킬 수 있다는 점에 주의하세요 — TPU는 추가 패딩이 필요하더라도 고정된 모양을 선호합니다. -🚀 **Optimization Guide**: For more details on optimizing training performance, including padding strategies and TPU considerations, see the [🤗 Transformers performance documentation](https://huggingface.co/docs/transformers/main/en/performance). +🚀 **최적화 가이드**: 패딩 전략과 TPU 고려사항을 포함한 훈련 성능 최적화에 대한 자세한 내용은 [🤗 Transformers 성능 문서](https://huggingface.co/docs/transformers/main/en/performance)를 참조하세요. -To do this in practice, we have to define a collate function that will apply the correct amount of padding to the items of the dataset we want to batch together. Fortunately, the 🤗 Transformers library provides us with such a function via `DataCollatorWithPadding`. It takes a tokenizer when you instantiate it (to know which padding token to use, and whether the model expects padding to be on the left or on the right of the inputs) and will do everything you need: +실제로 이를 수행하려면 함께 배치하려는 데이터 세트 항목에 적절한 양의 패딩을 적용할 collate function을 정의해야 합니다. 다행히 🤗 Transformers 라이브러리는 `DataCollatorWithPadding`을 통해 이러한 함수를 제공합니다. 인스턴스화할 때 토크나이저를 받아서(어떤 패딩 토큰을 사용할지, 모델이 입력의 왼쪽 또는 오른쪽에 패딩을 기대하는지 알기 위해) 필요한 모든 것을 수행합니다: ```py from transformers import DataCollatorWithPadding @@ -273,7 +273,7 @@ from transformers import DataCollatorWithPadding data_collator = DataCollatorWithPadding(tokenizer=tokenizer) ``` -To test this new toy, let's grab a few samples from our training set that we would like to batch together. Here, we remove the columns `idx`, `sentence1`, and `sentence2` as they won't be needed and contain strings (and we can't create tensors with strings) and have a look at the lengths of each entry in the batch: +이 새로운 장난감을 테스트하기 위해, 함께 배치하고 싶은 훈련 세트에서 몇 개의 샘플을 가져와보겠습니다. 여기서는 `idx`, `sentence1`, `sentence2` 열을 제거합니다. 이들은 필요하지 않고 문자열을 포함하고 있으며(문자열로는 텐서를 만들 수 없음), 배치의 각 항목 길이를 살펴보겠습니다: ```py samples = tokenized_datasets["train"][:8] @@ -285,7 +285,7 @@ samples = {k: v for k, v in samples.items() if k not in ["idx", "sentence1", "se [50, 59, 47, 67, 59, 50, 62, 32] ``` -No surprise, we get samples of varying length, from 32 to 67. Dynamic padding means the samples in this batch should all be padded to a length of 67, the maximum length inside the batch. Without dynamic padding, all of the samples would have to be padded to the maximum length in the whole dataset, or the maximum length the model can accept. Let's double-check that our `data_collator` is dynamically padding the batch properly: +당연히 32부터 67까지 다양한 길이의 샘플을 얻습니다. 동적 패딩은 이 배치의 샘플들이 모두 배치 내 최대 길이인 67로 패딩되어야 함을 의미합니다. 동적 패딩이 없다면, 모든 샘플이 전체 데이터 세트의 최대 길이나 모델이 받을 수 있는 최대 길이로 패딩되어야 할 것입니다. `data_collator`가 배치를 동적으로 올바르게 패딩하는지 다시 확인해보겠습니다: ```py batch = data_collator(samples) @@ -299,148 +299,148 @@ batch = data_collator(samples) 'labels': torch.Size([8])} ``` -Looking good! Now that we've gone from raw text to batches our model can deal with, we're ready to fine-tune it! +좋아 보입니다! 이제 원시 텍스트에서 모델이 처리할 수 있는 배치까지 만들었으므로, 미세 조정할 준비가 되었습니다! -✏️ **Try it out!** Replicate the preprocessing on the GLUE SST-2 dataset. It's a little bit different since it's composed of single sentences instead of pairs, but the rest of what we did should look the same. For a harder challenge, try to write a preprocessing function that works on any of the GLUE tasks. +✏️ **직접 해보기!** GLUE SST-2 데이터 세트에서 전처리를 복제해보세요. 쌍이 아닌 단일 문장으로 구성되어 있어 약간 다르지만, 나머지는 동일하게 보일 것입니다. 더 어려운 도전을 위해서는 GLUE 작업 중 어떤 것에서도 작동하는 전처리 함수를 작성해보세요. -📖 **Additional Practice**: Check out these hands-on examples from the [🤗 Transformers examples](https://huggingface.co/docs/transformers/main/en/notebooks). +📖 **추가 연습**: [🤗 Transformers 예제](https://huggingface.co/docs/transformers/main/en/notebooks)에서 이러한 실습 예제들을 확인해보세요. -Perfect! Now that we have preprocessed our data with the latest best practices from the 🤗 Datasets library, we're ready to move on to training our model using the modern Trainer API. The next section will show you how to fine-tune your model effectively using the latest features and optimizations available in the Hugging Face ecosystem. +완벽합니다! 이제 🤗 Datasets 라이브러리의 최신 모범 사례로 데이터를 전처리했으므로, 최신 Trainer API를 사용하여 모델을 훈련할 준비가 되었습니다. 다음 섹션에서는 Hugging Face 생태계에서 사용할 수 있는 최신 기능과 최적화를 사용하여 모델을 효과적으로 미세 조정하는 방법을 보여드리겠습니다. -## Section Quiz[[section-quiz]] +## 섹션 퀴즈[[section-quiz]] -Test your understanding of data processing concepts: +데이터 처리 개념에 대한 이해도를 테스트해보세요: -### 1. What is the main advantage of using `Dataset.map()` with `batched=True`? +### 1. `batched=True`와 함께 `Dataset.map()`을 사용하는 주요 장점은 무엇인가요? -### 2. Why do we use dynamic padding instead of padding all sequences to the maximum length in the dataset? +### 2. 데이터 세트의 최대 길이로 모든 시퀀스를 패딩하는 대신 동적 패딩을 사용하는 이유는 무엇인가요? -### 3. What does the `token_type_ids` field represent in BERT tokenization? +### 3. BERT 토큰화에서 `token_type_ids` 필드는 무엇을 나타내나요? -### 4. When loading a dataset with `load_dataset('glue', 'mrpc')`, what does the second argument specify? +### 4. `load_dataset('glue', 'mrpc')`로 데이터 세트를 로딩할 때 두 번째 인수는 무엇을 지정하나요? -### 5. What is the purpose of removing columns like 'sentence1' and 'sentence2' before training? +### 5. 훈련 전에 'sentence1'과 'sentence2' 같은 열을 제거하는 목적은 무엇인가요? -💡 **Key Takeaways:** -- Use `batched=True` with `Dataset.map()` for significantly faster preprocessing -- Dynamic padding with `DataCollatorWithPadding` is more efficient than fixed-length padding -- Always preprocess your data to match what your model expects (numerical tensors, correct column names) -- The 🤗 Datasets library provides powerful tools for efficient data processing at scale +💡 **핵심 요점:** +- 전처리를 훨씬 빠르게 하려면 `Dataset.map()`에서 `batched=True`를 사용하세요 +- `DataCollatorWithPadding`을 사용한 동적 패딩이 고정 길이 패딩보다 효율적입니다 +- 모델이 예상하는 것(수치적 텐서, 올바른 열 이름)에 맞게 항상 데이터를 전처리하세요 +- 🤗 Datasets 라이브러리는 대규모 효율적인 데이터 처리를 위한 강력한 도구를 제공합니다 - + \ No newline at end of file From 9808a12f003e0ce198e8a369c3fb8b3d638ad146 Mon Sep 17 00:00:00 2001 From: Youngdong Date: Sat, 19 Jul 2025 15:54:14 +0900 Subject: [PATCH 14/43] fix: manual edits --- chapters/ko/chapter3/3.mdx | 76 +++++++++++++++++++------------------- 1 file changed, 38 insertions(+), 38 deletions(-) diff --git a/chapters/ko/chapter3/3.mdx b/chapters/ko/chapter3/3.mdx index 0e397ce8e..ff5625339 100644 --- a/chapters/ko/chapter3/3.mdx +++ b/chapters/ko/chapter3/3.mdx @@ -19,7 +19,7 @@ -아래 코드 예제는 이미 이전 섹션의 예제를 실행했다고 가정합니다. 필요한 것을 요약한 간단한 요약은 다음과 같습니다: +아래 코드 예시들은 이전 섹션의 예시들을 이미 실행했다는 가정하에 작동합니다. 즉, 다음 사항들이 필요합니다: ```py from datasets import load_dataset @@ -40,7 +40,7 @@ data_collator = DataCollatorWithPadding(tokenizer=tokenizer) ### 훈련[[training]] -`Trainer`를 정의하기 전 첫 번째 단계는 `Trainer`가 훈련 및 평가에 사용할 모든 하이퍼파라미터를 포함하는 `TrainingArguments` 클래스를 정의하는 것입니다. 제공해야 하는 유일한 인수는 훈련된 모델이 저장될 디렉터리와 그 과정에서 생성되는 체크포인트입니다. 나머지는 기본값으로 둘 수 있으며, 이는 기본 미세 조정에서 꽤 잘 작동합니다. +`Trainer`를 정의하기 전 첫 번째 단계는 `Trainer`가 훈련 및 평가에 사용할 모든 하이퍼파라미터를 포함하는 `TrainingArguments` 클래스를 정의하는 것입니다. 필수로 제공해야 하는 유일한 인수는 훈련된 모델과 중간 체크포인트가 저장될 디렉토리입니다. 나머지는 기본값으로 둘 수 있으며, 이는 기본적인 미세 조정에도 꽤 잘 작동합니다. ```py from transformers import TrainingArguments @@ -52,7 +52,7 @@ training_args = TrainingArguments("test-trainer") -🚀 **고급 구성**: 사용 가능한 모든 훈련 인수와 최적화 전략에 대한 자세한 정보는 [TrainingArguments 문서](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments)와 [훈련 구성 쿡북](https://huggingface.co/learn/cookbook/en/fine_tuning_code_llm_on_single_gpu)을 확인하세요. +🚀 **고급 설정**: 사용 가능한 모든 훈련 인수와 최적화 전략에 대한 자세한 정보는 [TrainingArguments 문서](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments)와 [훈련 구성 쿡북](https://huggingface.co/learn/cookbook/en/fine_tuning_code_llm_on_single_gpu)을 확인하세요. @@ -64,9 +64,9 @@ from transformers import AutoModelForSequenceClassification model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) ``` -[Chapter 2](/course/chapter2)와 달리 이 사전 학습된 모델을 인스턴스화한 후 경고가 나타나는 것을 확인할 수 있습니다. 이는 BERT가 문장 쌍 분류에 대해 사전 학습되지 않았기 때문에 사전 학습된 모델의 헤드가 제거되고 시퀀스 분류에 적합한 새로운 헤드가 대신 추가되었기 때문입니다. 경고는 일부 가중치가 사용되지 않았으며 (제거된 사전 학습 헤드에 해당하는 가중치) 일부 다른 가중치가 무작위로 초기화되었음을 나타냅니다 (새로운 헤드의 가중치). 모델을 훈련하도록 권장하며 이는 정확히 우리가 지금 하려는 것입니다. +[Chapter 2](/course/chapter2)와 달리 이 사전훈련된 모델을 인스턴스화하면 경고 메시지가 나타나는 것을 확인할 수 있습니다. 이는 BERT가 문장 쌍 분류를 위해 사전 훈련되지 않았기 때문에, 사전 훈련된 모델의 헤드가 제거되고 시퀀스 분류에 적합한 새로운 헤드가 추가되었기 때문입니다. 경고는 일부 가중치(제거된 사전 훈련 헤드에 해당하는 가중치)가 사용되지 않았고, 일부 다른 가중치(새로운 헤드용)가 무작위로 초기화되었다는 것을 나타냅니다. 마지막으로 모델을 훈련하도록 권장하는데, 이것이 바로 우리가 지금 할 일입니다. -모델이 있으면 지금까지 구성한 모든 객체(`model`, `training_args`, 훈련 및 검증 데이터셋, `data_collator`, `processing_class`)를 전달하여 `Trainer`를 정의할 수 있습니다. `processing_class` 매개변수는 처리에 사용할 토크나이저를 Trainer에 알려주는 새로운 추가 사항입니다: +모델이 준비되면, 지금까지 구성한 모든 객체들(`model`, `training_args`, 훈련 및 검증 데이터셋, `data_collator`, `processing_class`)를 전달하여 `Trainer`를 정의할 수 있습니다. `processing_class` 매개변수는 매개변수는 비교적 최근에 추가된 기능으로, `Trainer`에게 어떤 토크나이저를 사용해 데이터를 처리할지 알려줍니다: ```py from transformers import Trainer @@ -81,7 +81,7 @@ trainer = Trainer( ) ``` -토크나이저를 `processing_class`로 전달하면 `Trainer`에서 사용하는 기본 `data_collator`가 `DataCollatorWithPadding`이 됩니다. 이 경우 `data_collator=data_collator` 줄을 생략할 수 있지만, 처리 파이프라인의 이 중요한 부분을 보여주기 위해 여기에 포함했습니다. +`processing_class`로 토크나이저를 전달하면, `Trainer`가 기본적으로 `DataCollatorWithPadding`을 `data_collator`로 사용합니다. 따라서 이 경우에는 `data_collator=data_collator` 줄을 생략할 수 있지만, 처리 파이프라인의 중요한 부분을 보여드리기 위해 여기에 포함했습니다. @@ -89,13 +89,13 @@ trainer = Trainer( -데이터셋에서 모델을 파인튜닝하려면 `Trainer`의 `train()` 메서드를 호출하기만 하면 됩니다: +데이터셋에서 모델을 미세 조정하려면 `Trainer`의 `train()` 메서드를 호출하기만 하면 됩니다: ```py trainer.train() ``` -이렇게 하면 파인튜닝이 시작되고 (GPU에서 몇 분 정도 걸림) 500 스텝마다 훈련 손실을 보고합니다. 하지만 모델이 얼마나 잘 (또는 나쁘게) 수행되고 있는지는 알려주지 않습니다. 그 이유는 다음과 같습니다: +이렇게 하면 미세 조정이 시작됩니다(GPU에서는 몇 분 정도 걸릴 거예요). 500단계마다 훈련 손실이 보고되지만, 모델의 성능이 얼마나 좋은지(또는 나쁜지)는 알려주지 않을 겁니다. 그 이유는 다음과 같습니다: 1. `TrainingArguments`에서 `eval_strategy`를 `"steps"` (매 `eval_steps`마다 평가) 또는 `"epoch"` (각 에포크 종료 시 평가)로 설정하여 훈련 중에 평가하도록 `Trainer`에 알리지 않았습니다. 2. 해당 평가 중에 메트릭을 계산하기 위한 `compute_metrics()` 함수를 `Trainer`에 제공하지 않았습니다 (그렇지 않으면 평가에서 손실만 출력되는데, 이는 직관적이지 않은 숫자입니다). @@ -103,7 +103,7 @@ trainer.train() ### 평가[[evaluation]] -유용한 `compute_metrics()` 함수를 빌드하고 다음 번 훈련에서 사용하는 방법을 살펴보겠습니다. 이 함수는 `EvalPrediction` 객체(`predictions` 필드와 `label_ids` 필드가 있는 명명된 튜플)를 받아야 하며 문자열을 플로트에 매핑하는 딕셔너리를 반환합니다 (문자열은 반환되는 메트릭의 이름이고 플로트는 그 값입니다). 모델에서 일부 예측을 얻으려면 `Trainer.predict()` 명령을 사용할 수 있습니다: +유용한 `compute_metrics()` 함수를 어떻게 만들고 다음 훈련 시 사용할 수 있는지 알아봅시다. 이 함수는 `EvalPrediction` 객체(`predictions` 필드와 `label_ids` 필드가 있는 명명된 튜플)를 인수로 받아야 하며 문자열을 부동 소수점 값에 매핑하는 딕셔너리(문자열은 반환되는 메트릭의 이름이고, 부동 소수점 값은 해당 값)를 반환합니다. 모델에서 예측값을 얻으려면 `Trainer.predict()`를 사용할 수 있습니다: ```py predictions = trainer.predict(tokenized_datasets["validation"]) @@ -114,9 +114,9 @@ print(predictions.predictions.shape, predictions.label_ids.shape) (408, 2) (408,) ``` -`predict()` 메서드의 출력은 `predictions`, `label_ids`, `metrics` 세 개의 필드가 있는 또 다른 명명된 튜플입니다. `metrics` 필드는 전달된 데이터셋의 손실과 일부 시간 메트릭 (예측하는 데 걸린 시간, 총 시간 및 평균 시간)만 포함합니다. `compute_metrics()` 함수를 완료하고 `Trainer`에 전달하면 해당 필드에는 `compute_metrics()`에서 반환된 메트릭도 포함됩니다. +`predict()` 메서드의 출력은 `predictions`, `label_ids`, `metrics` 세 개의 필드가 있는 또 다른 명명된 튜플입니다. `metrics` 필드에는 전달된 데이터셋에 대한 손실 값과 몇 가지 시간 관련 메트릭(예측에 총 소요된 시간 및 평균 시간)만 포함됩니다. 하지만 `compute_metrics()` 함수를 완성하여 `Trainer`에 전달하면, 이 필드에 `compute_metrics()`가 반환하는 지표들도 함께 포함될 거예요. -보시다시피 `predictions`는 408 x 2 모양의 2차원 배열입니다 (408은 사용한 데이터셋의 요소 수). 이는 `predict()`에 전달한 데이터셋의 각 요소에 대한 로짓입니다 ([이전 챕터](/course/chapter2)에서 보았듯이 모든 Transformer 모델은 로짓을 반환합니다). 라벨과 비교할 수 있는 예측으로 변환하려면 두 번째 축에서 최대값의 인덱스를 가져와야 합니다: +보시다시피, `predictions`는 408 x 2 모양의 2차원 배열입니다 (408은 predict()에 전달한 데이터셋의 요소 수입니다). 이 값들은 `predict()`에 전달한 데이터셋의 각 요소에 대한 로짓입니다 ([이전 챕터](/course/chapter2)에서 보았듯이 모든 Transformer 모델은 로짓을 반환합니다). 이 로짓을 우리가 가진 레이블과 비교할 수 있는 예측값으로 변환하려면, 두 번째 축에서 최댓값을 가진 인덱스를 취해야 합니다: ```py import numpy as np @@ -124,7 +124,7 @@ import numpy as np preds = np.argmax(predictions.predictions, axis=-1) ``` -이제 이 `preds`를 라벨과 비교할 수 있습니다. `compute_metric()` 함수를 빌드하기 위해 🤗 [Evaluate](https://github.com/huggingface/evaluate/) 라이브러리의 메트릭을 활용하겠습니다. 데이터셋을 로드한 것처럼 쉽게 MRPC 데이터셋과 연관된 메트릭을 로드할 수 있습니다. 이번에는 `evaluate.load()` 함수를 사용합니다. 반환된 객체에는 메트릭 계산에 사용할 수 있는 `compute()` 메서드가 있습니다: +이제 이 `preds`를 라벨과 비교할 수 있습니다. `compute_metric()` 함수를 빌드하기 위해 🤗 [Evaluate](https://github.com/huggingface/evaluate/) 라이브러리의 메트릭을 활용하겠습니다. MRPC 데이터셋과 관련된 메트릭을 불러오는 건 데이터셋을 불러왔던 것만큼이나 쉽습니다. 이번에는 `evaluate.load()` 함수를 사용하면 됩니다. 이렇게 반환된 객체에는 메트릭 계산을 수행할 수 있는 `compute()` 메서드가 있습니다: ```py import evaluate @@ -139,13 +139,13 @@ metric.compute(predictions=preds, references=predictions.label_ids) -다양한 평가 메트릭과 전략에 대해 [🤗 Evaluate 문서](https://huggingface.co/docs/evaluate/)에서 알아보세요. +다양한 평가 메트릭과 전략에 대해 알아보려면 [🤗 Evaluate 문서](https://huggingface.co/docs/evaluate/)를 참고하세요. -모델 헤드의 무작위 초기화가 달성한 메트릭을 변경할 수 있으므로 정확한 결과는 달라질 수 있습니다. 여기서 모델이 검증 세트에서 85.78%의 정확도와 89.97의 F1 점수를 가지고 있음을 확인할 수 있습니다. 이는 GLUE 벤치마크의 MRPC 데이터셋에서 결과를 평가하는 데 사용되는 두 가지 메트릭입니다. [BERT 논문](https://arxiv.org/pdf/1810.04805.pdf)의 표에는 기본 모델에 대해 88.9의 F1 점수가 보고되었습니다. 그것은 `uncased` 모델이었지만 현재 `cased` 모델을 사용하고 있어 더 나은 결과를 설명합니다. +모델 헤드의 무작위 초기화 때문에 얻게 되는 정확한 결과는 달라질 수 있습니다. 여기서는 우리 모델이 검증 세트에서 85.78%의 정확도와 89.97%의 F1 점수를 달성했음을 볼 수 있습니다. 이 두 가지는 GLUE 벤치마크의 MRPC 데이터셋에서 결과를 평가하는 데 사용되는 메트릭입니다. [BERT 논문](https://arxiv.org/pdf/1810.04805.pdf)의 표에는 기본 모델에 대해 F1 점수가 88.9로 보고되었습니다. 당시에는 `uncased` 모델을 사용했지만, 우리는 현재 `cased` 모델을 사용하고 있기 때문에 더 나은 결과가 나온 것입니다. -모든 것을 함께 래핑하면 `compute_metrics()` 함수를 얻습니다: +이 모든 것을 종합하면, 다음처럼 `compute_metrics()` 함수를 얻을 수 있습니다: ```py def compute_metrics(eval_preds): @@ -155,7 +155,7 @@ def compute_metrics(eval_preds): return metric.compute(predictions=predictions, references=labels) ``` -그리고 각 에포크 종료 시 메트릭을 보고하는 데 사용되는 것을 보려면 이 `compute_metrics()` 함수로 새로운 `Trainer`를 정의하는 방법은 다음과 같습니다: +각 에폭이 끝날 때마다 메트릭를 보고하기 위해 이 `compute_metrics()` 함수가 실제로 어떻게 사용되는지 보려면, 다음과 같이 새 `Trainer`를 정의하면 됩니다: ```py training_args = TrainingArguments("test-trainer", eval_strategy="epoch") @@ -172,17 +172,17 @@ trainer = Trainer( ) ``` -`eval_strategy`가 `"epoch"`로 설정된 새로운 `TrainingArguments`와 새로운 모델을 만든다는 점에 주목하세요. 그렇지 않으면 이미 훈련한 모델의 훈련을 계속하는 것입니다. 새로운 훈련 실행을 시작하려면 다음을 실행합니다: +참고로, 우리는 `eval_strategy`를 `"epoch"`으로 설정한 새로운 `TrainingArguments`와 새로운 모델을 생성합니다. 이렇게 하지 않으면 이미 훈련된 모델의 훈련을 계속하게 될 겁니다. 새로운 훈련을 시작하려면 다음을 실행하세요: ```py trainer.train() ``` -이번에는 훈련 손실 외에 각 에포크 종료 시 검증 손실과 메트릭을 보고합니다. 다시 말하지만, 모델의 무작위 헤드 초기화로 인해 달성하는 정확한 정확도/F1 점수는 우리가 발견한 것과 약간 다를 수 있지만 같은 수준이어야 합니다. +이번에는 훈련 손실 외에도 각 에폭이 끝날 때마다 검증 손실과 메트릭을 보고할 겁니다. 모델 헤드의 무작위 초기화 때문에 여러분이 얻는 정확도/F1 점수는 우리가 얻은 결과와 약간 다를 수 있지만, 비슷한 범위에 있을 거예요. ### 고급 훈련 기능[[advanced-training-features]] -`Trainer`는 최신 딥러닝 모범 사례를 접근 가능하게 만드는 많은 내장 기능을 제공합니다: +`Trainer`는 현대 딥러닝의 모범 사례들을 쉽게 활용할 수 있도록 다양한 내장 기능을 제공합니다: **혼합 정밀도 훈련**: 더 빠른 훈련과 메모리 사용량 감소를 위해 훈련 인수에서 `fp16=True`를 사용하세요: @@ -194,7 +194,7 @@ training_args = TrainingArguments( ) ``` -**그래디언트 누적**: GPU 메모리가 제한될 때 효과적인 더 큰 배치 크기를 위해: +**그레이디언트 누적**: GPU 메모리가 제한될 때 효과적인 더 큰 배치 크기를 위해: ```py training_args = TrainingArguments( @@ -205,7 +205,7 @@ training_args = TrainingArguments( ) ``` -**학습률 스케줄링**: Trainer는 기본적으로 선형 감소를 사용하지만 이를 사용자 정의할 수 있습니다: +**학습률 스케줄링**: Trainer는 기본적으로 선형 감소 방식을 사용하지만, 사용자 맞춤 설정이 가능합니다: ```py training_args = TrainingArguments( @@ -224,19 +224,19 @@ training_args = TrainingArguments( `Trainer`는 여러 GPU 또는 TPU에서 즉시 작동하며 분산 훈련을 위한 많은 옵션을 제공합니다. 지원하는 모든 것에 대해서는 Chapter 10에서 다루겠습니다. -이것으로 `Trainer` API를 사용한 파인튜닝에 대한 소개를 마칩니다. 가장 일반적인 NLP 작업에 대해 이를 수행하는 예제는 [Chapter 7](/course/chapter7)에서 제공되지만, 지금은 순수 PyTorch 훈련 루프로 동일한 작업을 수행하는 방법을 살펴보겠습니다. +이것으로 `Trainer` API를 사용한 미세 조정에 대한 소개를 마칩니다. 대부분의 일반적인 NLP 작업에 대한 예제는 [Chapter 7](/course/chapter7)에서 다룰 예정이며, 지금부터는 순수 PyTorch 훈련 루프를 사용하여 동일한 작업을 수행하는 방법을 살펴보겠습니다. -📝 **더 많은 예제**: [🤗 Transformers 노트북](https://huggingface.co/docs/transformers/main/en/notebooks)의 포괄적인 컬렉션을 확인하세요. +📝 **더 많은 예제**: [🤗 Transformers 노트북](https://huggingface.co/docs/transformers/main/en/notebooks)에 있는 방대한 자료를 확인해 보세요. ## 섹션 퀴즈[[section-quiz]] -Trainer API와 파인튜닝 개념에 대한 이해를 테스트해보세요: +Trainer API와 미세 조정 개념에 대한 이해를 테스트해보세요: -### 1. processing_class 매개변수의 목적은 무엇인가요? +### 1. `Trainer`에서 processing_class 매개변수의 목적은 무엇인가요? -### 6. 그래디언트 누적이란 무엇이며 어떻게 활성화하나요? +### 6. 그레이디언트 누적이란 무엇이며 어떻게 활성화하나요? @@ -383,11 +383,11 @@ Trainer API와 파인튜닝 개념에 대한 이해를 테스트해보세요: 💡 **핵심 요점:** -- `Trainer` API는 대부분의 훈련 복잡성을 처리하는 고수준 인터페이스를 제공합니다 +- `Trainer` API는 대부분의 훈련 복잡성을 처리하는 높은 수준의 인터페이스를 제공합니다 - 적절한 데이터 처리를 위해 `processing_class`를 사용하여 토크나이저를 지정하세요 - `TrainingArguments`는 학습률, 배치 크기, 평가 전략, 최적화 등 훈련의 모든 측면을 제어합니다 -- `compute_metrics`는 단순한 훈련 손실 외에 사용자 정의 평가 메트릭을 활성화합니다 -- 혼합 정밀도(`fp16=True`)와 그래디언트 누적과 같은 최신 기능은 훈련 효율성을 크게 향상시킬 수 있습니다 +- `compute_metrics`를 사용하면 훈련 손실 외에 사용자 정의 평가 메트릭을 활용할 수 있습니다 +- 혼합 정밀도(`fp16=True`)와 그레이디언트 누적과 같은 최신 기능은 훈련 효율성을 크게 향상시킬 수 있습니다 From bc73184cbb11ee69f0513bd32dc61c59b3554ad5 Mon Sep 17 00:00:00 2001 From: Youngdong Date: Sat, 19 Jul 2025 16:08:24 +0900 Subject: [PATCH 15/43] fix: manual edits --- chapters/ko/chapter3/3.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chapters/ko/chapter3/3.mdx b/chapters/ko/chapter3/3.mdx index ff5625339..f51abdb45 100644 --- a/chapters/ko/chapter3/3.mdx +++ b/chapters/ko/chapter3/3.mdx @@ -66,7 +66,7 @@ model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_label [Chapter 2](/course/chapter2)와 달리 이 사전훈련된 모델을 인스턴스화하면 경고 메시지가 나타나는 것을 확인할 수 있습니다. 이는 BERT가 문장 쌍 분류를 위해 사전 훈련되지 않았기 때문에, 사전 훈련된 모델의 헤드가 제거되고 시퀀스 분류에 적합한 새로운 헤드가 추가되었기 때문입니다. 경고는 일부 가중치(제거된 사전 훈련 헤드에 해당하는 가중치)가 사용되지 않았고, 일부 다른 가중치(새로운 헤드용)가 무작위로 초기화되었다는 것을 나타냅니다. 마지막으로 모델을 훈련하도록 권장하는데, 이것이 바로 우리가 지금 할 일입니다. -모델이 준비되면, 지금까지 구성한 모든 객체들(`model`, `training_args`, 훈련 및 검증 데이터셋, `data_collator`, `processing_class`)를 전달하여 `Trainer`를 정의할 수 있습니다. `processing_class` 매개변수는 매개변수는 비교적 최근에 추가된 기능으로, `Trainer`에게 어떤 토크나이저를 사용해 데이터를 처리할지 알려줍니다: +모델이 준비되면, 지금까지 구성한 모든 객체들(`model`, `training_args`, 훈련 및 검증 데이터셋, `data_collator`, `processing_class`)를 전달하여 `Trainer`를 정의할 수 있습니다. `processing_class` 매개변수는 비교적 최근에 추가된 기능으로, `Trainer`에게 어떤 토크나이저를 사용해 데이터를 처리할지 알려줍니다: ```py from transformers import Trainer @@ -155,7 +155,7 @@ def compute_metrics(eval_preds): return metric.compute(predictions=predictions, references=labels) ``` -각 에폭이 끝날 때마다 메트릭를 보고하기 위해 이 `compute_metrics()` 함수가 실제로 어떻게 사용되는지 보려면, 다음과 같이 새 `Trainer`를 정의하면 됩니다: +각 에폭이 끝날 때마다 메트릭을 보고하기 위해 이 `compute_metrics()` 함수가 실제로 어떻게 사용되는지 보려면, 다음과 같이 새 `Trainer`를 정의하면 됩니다: ```py training_args = TrainingArguments("test-trainer", eval_strategy="epoch") From 565a630cfebb4486dc565bc8337075ff227c614c Mon Sep 17 00:00:00 2001 From: Chaewon Song Date: Sat, 19 Jul 2025 17:34:25 +0900 Subject: [PATCH 16/43] fix: manual edits --- chapters/ko/chapter3/2.mdx | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/chapters/ko/chapter3/2.mdx b/chapters/ko/chapter3/2.mdx index cef0967dc..d592833f1 100644 --- a/chapters/ko/chapter3/2.mdx +++ b/chapters/ko/chapter3/2.mdx @@ -7,7 +7,7 @@ {label: "Aws Studio", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/master/course/en/chapter3/section2.ipynb"}, ]} /> -[이전 챕터](/course/chapter2)의 예제를 이어서, 한 배치에서 시퀀스 분류기를 훈련하는 방법은 다음과 같습니다: +[이전 챕터](/course/chapter2)의 예제를 이어서, 한 배치에서 시퀀스 분류기를 훈련하는 방법은 다음과 같습니다. ```python import torch @@ -43,7 +43,7 @@ optimizer.step() Hub에는 모델뿐만 아니라 다양한 언어로 된 여러 데이터 세트도 있습니다. [여기](https://huggingface.co/datasets)에서 데이터 세트를 찾아볼 수 있으며, 이 섹션을 완료한 후에는 새로운 데이터 세트를 로드하고 처리해보는 것을 권장합니다([여기](https://huggingface.co/docs/datasets/loading)에서 일반적인 문서를 참조하세요). 하지만 지금은 MRPC 데이터 세트에 집중해보겠습니다! 이것은 [GLUE 벤치마크](https://gluebenchmark.com/)를 구성하는 10개 데이터 세트 중 하나로, 10개의 서로 다른 텍스트 분류 작업에 걸쳐 ML 모델의 성능을 측정하는 데 사용되는 학술적 벤치마크입니다. -🤗 Datasets 라이브러리는 Hub에서 데이터 세트를 다운로드하고 캐시하는 매우 간단한 명령을 제공합니다. MRPC 데이터 세트를 다음과 같이 다운로드할 수 있습니다: +🤗 Datasets 라이브러리는 Hub에서 데이터 세트를 다운로드하고 캐시하는 매우 간단한 명령을 제공합니다. MRPC 데이터 세트를 다음과 같이 다운로드할 수 있습니다. @@ -83,7 +83,7 @@ DatasetDict({ -딕셔너리처럼 인덱싱하여 `raw_datasets` 객체의 각 문장 쌍에 접근할 수 있습니다: +딕셔너리처럼 인덱싱하여 `raw_datasets` 객체의 각 문장 쌍에 접근할 수 있습니다. ```py raw_train_dataset = raw_datasets["train"] @@ -97,7 +97,7 @@ raw_train_dataset[0] 'sentence2': 'Referring to him as only " the witness " , Amrozi accused his brother of deliberately distorting his evidence .'} ``` -레이블이 이미 정수로 되어 있으므로 여기서 전처리를 할 필요가 없습니다. 어떤 정수가 어떤 레이블에 해당하는지 알아보려면 `raw_train_dataset`의 `features`를 검사하면 됩니다. 이것은 각 열의 타입을 알려줍니다: +레이블이 이미 정수로 되어 있으므로 여기서 전처리를 할 필요가 없습니다. 어떤 정수가 어떤 레이블에 해당하는지 알아보려면 `raw_train_dataset`의 `features`를 검사하면 됩니다. 이것은 각 열의 타입을 알려줍니다. ```py raw_train_dataset.features @@ -122,7 +122,7 @@ raw_train_dataset.features -데이터 세트를 전처리하려면 텍스트를 모델이 이해할 수 있는 숫자로 변환해야 합니다. [이전 챕터](/course/chapter2)에서 보았듯이, 이는 토크나이저로 수행됩니다. 토크나이저에 한 문장이나 문장 목록을 입력할 수 있으므로, 다음과 같이 각 쌍의 모든 첫 번째 문장과 모든 두 번째 문장을 직접 토큰화할 수 있습니다: +데이터 세트를 전처리하려면 텍스트를 모델이 이해할 수 있는 숫자로 변환해야 합니다. [이전 챕터](/course/chapter2)에서 보았듯이, 이는 토크나이저로 수행됩니다. 토크나이저에 한 문장이나 문장 목록을 입력할 수 있으므로, 다음과 같이 각 쌍의 모든 첫 번째 문장과 모든 두 번째 문장을 직접 토큰화할 수 있습니다. ```py from transformers import AutoTokenizer @@ -139,7 +139,7 @@ tokenized_sentences_2 = tokenizer(raw_datasets["train"]["sentence2"]) -하지만 두 시퀀스를 모델에 전달하기만 해서는 두 문장이 패러프레이즈인지 아닌지 예측할 수 없습니다. 두 시퀀스를 쌍으로 처리하고 적절한 전처리를 적용해야 합니다. 다행히 토크나이저는 한 쌍의 시퀀스를 받아서 BERT 모델이 기대하는 방식으로 준비할 수도 있습니다: +하지만 두 시퀀스를 모델에 전달하기만 해서는 두 문장이 패러프레이즈인지 아닌지 예측할 수 없습니다. 두 시퀀스를 쌍으로 처리하고 적절한 전처리를 적용해야 합니다. 다행히 토크나이저는 한 쌍의 시퀀스를 받아서 BERT 모델이 기대하는 방식으로 준비할 수도 있습니다. ```py inputs = tokenizer("This is the first sentence.", "This is the second one.") @@ -162,19 +162,19 @@ inputs -`input_ids` 안의 ID를 다시 단어로 디코딩하면: +`input_ids` 안의 ID를 다시 단어로 디코딩하면 ```py tokenizer.convert_ids_to_tokens(inputs["input_ids"]) ``` -다음을 얻습니다: +다음을 얻습니다. ```python out ['[CLS]', 'this', 'is', 'the', 'first', 'sentence', '.', '[SEP]', 'this', 'is', 'the', 'second', 'one', '.', '[SEP]'] ``` -따라서 모델은 두 문장이 있을 때 입력이 `[CLS] sentence1 [SEP] sentence2 [SEP]` 형태이기를 기대한다는 것을 알 수 있습니다. 이를 `token_type_ids`와 맞춰보면: +따라서 모델은 두 문장이 있을 때 입력이 `[CLS] sentence1 [SEP] sentence2 [SEP]` 형태이기를 기대한다는 것을 알 수 있습니다. 이를 `token_type_ids`와 맞춰보면 ```python out ['[CLS]', 'this', 'is', 'the', 'first', 'sentence', '.', '[SEP]', 'this', 'is', 'the', 'second', 'one', '.', '[SEP]'] @@ -189,9 +189,9 @@ tokenizer.convert_ids_to_tokens(inputs["input_ids"]) 다음 문장 예측에서는 모델에 문장 쌍(무작위로 마스킹된 토큰과 함께)이 제공되고 두 번째 문장이 첫 번째 문장을 따르는지 예측하도록 요청받습니다. 작업을 쉽지 않게 만들기 위해, 절반의 경우에는 문장들이 추출된 원본 문서에서 서로를 따르고, 나머지 절반의 경우에는 두 문장이 서로 다른 문서에서 나옵니다. -일반적으로 토큰화된 입력에 `token_type_ids`가 있는지 여부에 대해 걱정할 필요는 없습니다: 토크나이저와 모델에 동일한 체크포인트(checkpoint)를 사용하는 한, 토크나이저가 모델에 제공해야 할 것을 알고 있으므로 모든 것이 잘 될 것입니다. +일반적으로 토큰화된 입력에 `token_type_ids`가 있는지 여부에 대해 걱정할 필요는 없습니다. 토크나이저와 모델에 동일한 체크포인트(checkpoint)를 사용하는 한, 토크나이저가 모델에 제공해야 할 것을 알고 있으므로 모든 것이 잘 될 것입니다. -이제 토크나이저가 한 쌍의 문장을 어떻게 처리할 수 있는지 보았으므로, 이를 사용하여 전체 데이터 세트를 토큰화할 수 있습니다: [이전 챕터](/course/chapter2)에서처럼, 첫 번째 문장 목록과 두 번째 문장 목록을 제공하여 토크나이저에 문장 쌍 목록을 입력할 수 있습니다. 이는 [2장](/course/chapter2)에서 본 패딩과 생략 옵션과도 호환됩니다. 따라서 훈련 데이터 세트를 전처리하는 한 가지 방법은: +이제 토크나이저가 한 쌍의 문장을 어떻게 처리할 수 있는지 보았으므로, 이를 사용하여 전체 데이터 세트를 토큰화할 수 있습니다: [이전 챕터](/course/chapter2)에서처럼, 첫 번째 문장 목록과 두 번째 문장 목록을 제공하여 토크나이저에 문장 쌍 목록을 입력할 수 있습니다. 이는 [2장](/course/chapter2)에서 본 패딩과 생략 옵션과도 호환됩니다. 따라서 훈련 데이터 세트를 전처리하는 한 가지 방법은 ```py tokenized_dataset = tokenizer( @@ -204,7 +204,7 @@ tokenized_dataset = tokenizer( 이것은 잘 작동하지만, 딕셔너리(키는 `input_ids`, `attention_mask`, `token_type_ids`이고 값은 목록의 목록)를 반환한다는 단점이 있습니다. 또한 토큰화 중에 전체 데이터 세트를 메모리에 저장할 수 있는 충분한 RAM이 있는 경우에만 작동합니다(🤗 Datasets 라이브러리의 데이터 세트는 디스크에 저장된 [Apache Arrow](https://arrow.apache.org/) 파일이므로, 요청한 샘플만 메모리에 로드됩니다). -데이터를 데이터 세트로 유지하려면 [`Dataset.map()`](https://huggingface.co/docs/datasets/package_reference/main_classes#datasets.Dataset.map) 메소드를 사용하겠습니다. 이는 토큰화 이상의 전처리가 필요한 경우 추가적인 유연성도 제공합니다. `map()` 메소드는 데이터 세트의 각 요소에 함수를 적용하여 작동하므로, 입력을 토큰화하는 함수를 정의해보겠습니다: +데이터를 데이터 세트로 유지하려면 [`Dataset.map()`](https://huggingface.co/docs/datasets/package_reference/main_classes#datasets.Dataset.map) 메소드를 사용하겠습니다. 이는 토큰화 이상의 전처리가 필요한 경우 추가적인 유연성도 제공합니다. `map()` 메소드는 데이터 세트의 각 요소에 함수를 적용하여 작동하므로, 입력을 토큰화하는 함수를 정의해보겠습니다. ```py def tokenize_function(example): @@ -213,7 +213,7 @@ def tokenize_function(example): 이 함수는 딕셔너리(데이터 세트의 항목과 같은)를 받아서 `input_ids`, `attention_mask`, `token_type_ids` 키가 있는 새 딕셔너리를 반환합니다. `example` 딕셔너리에 여러 샘플이 포함되어 있어도(각 키가 문장 목록으로) 작동한다는 점에 주목하세요. 앞서 본 것처럼 `tokenizer`는 문장 쌍의 목록에서 작동하기 때문입니다. 이를 통해 `map()` 호출에서 `batched=True` 옵션을 사용할 수 있으며, 이는 토큰화를 크게 가속화할 것입니다. `tokenizer`는 [🤗 Tokenizers](https://github.com/huggingface/tokenizers) 라이브러리의 Rust로 작성된 토크나이저로 뒷받침됩니다. 이 토크나이저는 매우 빠를 수 있지만, 한 번에 많은 입력을 제공해야만 그렇습니다. -지금은 토큰화 함수에서 `padding` 인수를 빼둔 것에 주목하세요. 모든 샘플을 최대 길이로 패딩하는 것은 효율적이지 않기 때문입니다: 배치를 만들 때 샘플을 패딩하는 것이 더 좋습니다. 그러면 해당 배치의 최대 길이까지만 패딩하면 되고, 전체 데이터 세트의 최대 길이까지 패딩할 필요가 없기 때문입니다. 입력의 길이가 매우 다양할 때 많은 시간과 처리 능력을 절약할 수 있습니다! +지금은 토큰화 함수에서 `padding` 인수를 빼둔 것에 주목하세요. 모든 샘플을 최대 길이로 패딩하는 것은 효율적이지 않기 때문입니다. 배치를 만들 때 샘플을 패딩하는 것이 더 좋습니다. 그러면 해당 배치의 최대 길이까지만 패딩하면 되고, 전체 데이터 세트의 최대 길이까지 패딩할 필요가 없기 때문입니다. 입력의 길이가 매우 다양할 때 많은 시간과 처리 능력을 절약할 수 있습니다! @@ -228,7 +228,7 @@ tokenized_datasets = raw_datasets.map(tokenize_function, batched=True) tokenized_datasets ``` -🤗 Datasets 라이브러리가 이 처리를 적용하는 방식은 전처리 함수가 반환하는 딕셔너리의 각 키에 대해 데이터 세트에 새 필드를 추가하는 것입니다: +🤗 Datasets 라이브러리가 이 처리를 적용하는 방식은 전처리 함수가 반환하는 딕셔너리의 각 키에 대해 데이터 세트에 새 필드를 추가하는 것입니다. ```python out DatasetDict({ @@ -265,7 +265,7 @@ DatasetDict({ -실제로 이를 수행하려면 함께 배치하려는 데이터 세트 항목에 적절한 양의 패딩을 적용할 collate function을 정의해야 합니다. 다행히 🤗 Transformers 라이브러리는 `DataCollatorWithPadding`을 통해 이러한 함수를 제공합니다. 인스턴스화할 때 토크나이저를 받아서(어떤 패딩 토큰을 사용할지, 모델이 입력의 왼쪽 또는 오른쪽에 패딩을 기대하는지 알기 위해) 필요한 모든 것을 수행합니다: +실제로 이를 수행하려면 함께 배치하려는 데이터 세트 항목에 적절한 양의 패딩을 적용할 collate function을 정의해야 합니다. 다행히 🤗 Transformers 라이브러리는 `DataCollatorWithPadding`을 통해 이러한 함수를 제공합니다. 인스턴스화할 때 토크나이저를 받아서(어떤 패딩 토큰을 사용할지, 모델이 입력의 왼쪽 또는 오른쪽에 패딩을 기대하는지 알기 위해) 필요한 모든 것을 수행합니다. ```py from transformers import DataCollatorWithPadding @@ -273,7 +273,7 @@ from transformers import DataCollatorWithPadding data_collator = DataCollatorWithPadding(tokenizer=tokenizer) ``` -이 새로운 장난감을 테스트하기 위해, 함께 배치하고 싶은 훈련 세트에서 몇 개의 샘플을 가져와보겠습니다. 여기서는 `idx`, `sentence1`, `sentence2` 열을 제거합니다. 이들은 필요하지 않고 문자열을 포함하고 있으며(문자열로는 텐서를 만들 수 없음), 배치의 각 항목 길이를 살펴보겠습니다: +이 새로운 도구를 테스트하기 위해, 함께 배치하고 싶은 훈련 세트에서 몇 개의 샘플을 가져와보겠습니다. 여기서는 `idx`, `sentence1`, `sentence2` 열을 제거합니다. 이들은 필요하지 않고 문자열을 포함하고 있으며(문자열로는 텐서를 만들 수 없음), 배치의 각 항목 길이를 살펴보겠습니다. ```py samples = tokenized_datasets["train"][:8] @@ -285,7 +285,7 @@ samples = {k: v for k, v in samples.items() if k not in ["idx", "sentence1", "se [50, 59, 47, 67, 59, 50, 62, 32] ``` -당연히 32부터 67까지 다양한 길이의 샘플을 얻습니다. 동적 패딩은 이 배치의 샘플들이 모두 배치 내 최대 길이인 67로 패딩되어야 함을 의미합니다. 동적 패딩이 없다면, 모든 샘플이 전체 데이터 세트의 최대 길이나 모델이 받을 수 있는 최대 길이로 패딩되어야 할 것입니다. `data_collator`가 배치를 동적으로 올바르게 패딩하는지 다시 확인해보겠습니다: +당연히 32부터 67까지 다양한 길이의 샘플을 얻습니다. 동적 패딩은 이 배치의 샘플들이 모두 배치 내 최대 길이인 67로 패딩되어야 함을 의미합니다. 동적 패딩이 없다면, 모든 샘플이 전체 데이터 세트의 최대 길이나 모델이 받을 수 있는 최대 길이로 패딩되어야 할 것입니다. `data_collator`가 배치를 동적으로 올바르게 패딩하는지 다시 확인해보겠습니다. ```py batch = data_collator(samples) @@ -313,7 +313,7 @@ batch = data_collator(samples) ## 섹션 퀴즈[[section-quiz]] -데이터 처리 개념에 대한 이해도를 테스트해보세요: +데이터 처리 개념에 대한 이해도를 테스트해보세요. ### 1. `batched=True`와 함께 `Dataset.map()`을 사용하는 주요 장점은 무엇인가요? @@ -437,7 +437,7 @@ batch = data_collator(samples) -💡 **핵심 요점:** +💡 **핵심 요점** - 전처리를 훨씬 빠르게 하려면 `Dataset.map()`에서 `batched=True`를 사용하세요 - `DataCollatorWithPadding`을 사용한 동적 패딩이 고정 길이 패딩보다 효율적입니다 - 모델이 예상하는 것(수치적 텐서, 올바른 열 이름)에 맞게 항상 데이터를 전처리하세요 From ed055119d0dc7097f307f4ad462b51d148fb6bc0 Mon Sep 17 00:00:00 2001 From: Chaewon Song Date: Sat, 19 Jul 2025 17:41:24 +0900 Subject: [PATCH 17/43] fix: toctree edits --- chapters/ko/_toctree.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/chapters/ko/_toctree.yml b/chapters/ko/_toctree.yml index 29659df4f..f1866f389 100644 --- a/chapters/ko/_toctree.yml +++ b/chapters/ko/_toctree.yml @@ -47,10 +47,12 @@ title: 단원 마무리 퀴즈 quiz: 2 -- title: 3. 사전훈련된 모델 미세 조정 +- title: 3. 🤗 사전훈련된 모델 미세조정 sections: - local: chapter3/2 title: 데이터 처리 + - local: chapter3/3 + title: Trainer API를 사용한 모델 미세조정 - title: 5. 🤗 Datasets 라이브러리 sections: From b76ccece3fdcbc458e442e7f5049cf99dd8ca84a Mon Sep 17 00:00:00 2001 From: Chaewon Song Date: Sat, 19 Jul 2025 17:53:45 +0900 Subject: [PATCH 18/43] fix: toctree edits --- chapters/ko/_toctree.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/chapters/ko/_toctree.yml b/chapters/ko/_toctree.yml index f1866f389..692c38c37 100644 --- a/chapters/ko/_toctree.yml +++ b/chapters/ko/_toctree.yml @@ -51,8 +51,6 @@ sections: - local: chapter3/2 title: 데이터 처리 - - local: chapter3/3 - title: Trainer API를 사용한 모델 미세조정 - title: 5. 🤗 Datasets 라이브러리 sections: From d584efc28859fee3036a06d7343a583a88bab7d6 Mon Sep 17 00:00:00 2001 From: Chaewon Song Date: Tue, 22 Jul 2025 22:44:39 +0900 Subject: [PATCH 19/43] Apply suggestions from code review Co-authored-by: Yijun Lee <119404328+yijun-lee@users.noreply.github.com> Co-authored-by: YONGSANG <71686691+4N3MONE@users.noreply.github.com> --- chapters/ko/chapter3/2.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chapters/ko/chapter3/2.mdx b/chapters/ko/chapter3/2.mdx index d592833f1..ef091fac2 100644 --- a/chapters/ko/chapter3/2.mdx +++ b/chapters/ko/chapter3/2.mdx @@ -417,7 +417,7 @@ batch = data_collator(samples) choices={[ { text: "훈련 중 메모리를 절약하기 위해서입니다.", - explain: "약간의 메모리는 절약하지만, 이것이 주된 이유는 아닙니다." + explain: "약간의 메모리는 절약되지만, 이것이 주된 이유는 아닙니다." }, { text: "모델이 이러한 원시 텍스트 열을 예상하지 않고 오류가 발생할 수 있기 때문입니다.", @@ -440,7 +440,7 @@ batch = data_collator(samples) 💡 **핵심 요점** - 전처리를 훨씬 빠르게 하려면 `Dataset.map()`에서 `batched=True`를 사용하세요 - `DataCollatorWithPadding`을 사용한 동적 패딩이 고정 길이 패딩보다 효율적입니다 -- 모델이 예상하는 것(수치적 텐서, 올바른 열 이름)에 맞게 항상 데이터를 전처리하세요 +- 모델의 추론 결과물(수치적 텐서, 올바른 열 이름)에 맞게 항상 데이터를 전처리하세요 - 🤗 Datasets 라이브러리는 대규모 효율적인 데이터 처리를 위한 강력한 도구를 제공합니다 \ No newline at end of file From 7e74bde1d19fd5e3d7291196d5f989766259f6a9 Mon Sep 17 00:00:00 2001 From: Chaewon Song Date: Tue, 22 Jul 2025 22:47:43 +0900 Subject: [PATCH 20/43] fix: manual edits --- chapters/ko/chapter3/2.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapters/ko/chapter3/2.mdx b/chapters/ko/chapter3/2.mdx index ef091fac2..106801824 100644 --- a/chapters/ko/chapter3/2.mdx +++ b/chapters/ko/chapter3/2.mdx @@ -7,7 +7,7 @@ {label: "Aws Studio", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/master/course/en/chapter3/section2.ipynb"}, ]} /> -[이전 챕터](/course/chapter2)의 예제를 이어서, 한 배치에서 시퀀스 분류기를 훈련하는 방법은 다음과 같습니다. +[이전 챕터](/course/chapter2)의 예제에 이어서, 한 배치에서 시퀀스 분류기를 훈련하는 방법은 다음과 같습니다. ```python import torch From fbed6f705585251aebdc15f1c8a01de3b0c53686 Mon Sep 17 00:00:00 2001 From: thliang01 Date: Thu, 24 Jul 2025 11:33:07 +0800 Subject: [PATCH 21/43] Add contributor to Chinese (traditional) translation in README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5216eba06..3cc68a9ea 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ This repo contains the content that's used to create the **[Hugging Face course] | [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) | +| [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/rum/chapter1/1) (WIP) | [`chapters/rum`](https://github.com/huggingface/course/tree/main/chapters/rum) | [@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 From a745abc7e9d2d8abce04cc4e938804ab318e6dc7 Mon Sep 17 00:00:00 2001 From: Youngdong <48584373+Youngdong2@users.noreply.github.com> Date: Sat, 26 Jul 2025 14:28:22 +0900 Subject: [PATCH 22/43] Apply suggestions from code review Co-authored-by: Harheem Kim <49297157+harheem@users.noreply.github.com> --- chapters/ko/chapter3/3.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chapters/ko/chapter3/3.mdx b/chapters/ko/chapter3/3.mdx index f51abdb45..74d4a8361 100644 --- a/chapters/ko/chapter3/3.mdx +++ b/chapters/ko/chapter3/3.mdx @@ -11,7 +11,7 @@ -🤗 Transformers는 `Trainer` 클래스를 제공하여 최신 모범 사례를 사용해 제공하는 사전 학습된 모델을 데이터셋에 미세 조정할 수 있도록 도와줍니다. 이전 섹션에서 모든 데이터 전처리 작업을 완료했다면, `Trainer`를 정의하는 데 몇 단계만 남았습니다. 가장 어려운 부분은 `Trainer.train()`을 실행할 환경을 준비하는 것일 수 있습니다. CPU에서는 매우 느리게 실행되기 때문입니다. GPU가 설정되어 있지 않다면, [Google Colab](https://colab.research.google.com/)에서 무료 GPU 또는 TPU에 액세스할 수 있습니다. +🤗 Transformers는 `Trainer` 클래스를 제공합니다. 이 클래스를 사용하면 사전 학습된 모델을 여러분의 데이터셋에 맞춰 최신 기법으로 쉽게 미세 조정할 수 있습니다. 이전 섹션에서 데이터 전처리 작업을 모두 마쳤다면 이제 몇 단계만 거치면 `Trainer`를 정의할 수 있습니다. 가장 어려운 부분은 `Trainer.train()`을 실행할 환경을 준비하는 과정일 수 있습니다. 이 작업은 CPU에서 매우 느리게 실행되기 때문입니다. 만약 GPU가 없다면 [Google Colab](https://colab.research.google.com/)에서 무료로 제공하는 GPU나 TPU를 이용할 수 있습니다. @@ -19,7 +19,7 @@ -아래 코드 예시들은 이전 섹션의 예시들을 이미 실행했다는 가정하에 작동합니다. 즉, 다음 사항들이 필요합니다: +아래 코드 예시는 이전 섹션의 코드를 모두 실행했다는 가정하에 작동합니다. 즉, 다음 사항들이 필요합니다. ```py from datasets import load_dataset From 50a63e7c8053ecadcf89e56c4e40db442a2f64d6 Mon Sep 17 00:00:00 2001 From: Youngdong <48584373+Youngdong2@users.noreply.github.com> Date: Sat, 26 Jul 2025 14:29:00 +0900 Subject: [PATCH 23/43] Apply suggestions from code review Co-authored-by: Harheem Kim <49297157+harheem@users.noreply.github.com> Co-authored-by: Woojun Jung <46880056+jungnerd@users.noreply.github.com> --- chapters/ko/chapter3/3.mdx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/chapters/ko/chapter3/3.mdx b/chapters/ko/chapter3/3.mdx index 74d4a8361..7cd5cd15d 100644 --- a/chapters/ko/chapter3/3.mdx +++ b/chapters/ko/chapter3/3.mdx @@ -40,7 +40,7 @@ data_collator = DataCollatorWithPadding(tokenizer=tokenizer) ### 훈련[[training]] -`Trainer`를 정의하기 전 첫 번째 단계는 `Trainer`가 훈련 및 평가에 사용할 모든 하이퍼파라미터를 포함하는 `TrainingArguments` 클래스를 정의하는 것입니다. 필수로 제공해야 하는 유일한 인수는 훈련된 모델과 중간 체크포인트가 저장될 디렉토리입니다. 나머지는 기본값으로 둘 수 있으며, 이는 기본적인 미세 조정에도 꽤 잘 작동합니다. +`Trainer`를 정의하기 전 첫 번째 단계는 `Trainer`가 훈련 및 평가에 사용할 모든 하이퍼파라미터를 담을`TrainingArguments` 클래스를 정의하는 것입니다. 필수로 제공해야 하는 유일한 인수는 훈련된 모델과 중간 체크포인트가 저장될 디렉토리입니다. 나머지는 기본값으로 둘 수 있으며, 기본적인 미세 조정 작업에는 충분한 설정입니다. ```py from transformers import TrainingArguments @@ -48,15 +48,15 @@ from transformers import TrainingArguments training_args = TrainingArguments("test-trainer") ``` -훈련 중에 모델을 Hub에 자동으로 업로드하려면 `TrainingArguments`에서 `push_to_hub=True`를 전달하세요. 이에 대해서는 [Chapter 4](/course/chapter4/3)에서 자세히 알아보겠습니다. +훈련 중에 모델을 Hub에 자동으로 업로드하려면 `TrainingArguments`에서 `push_to_hub=True`를 전달하세요. 이 기능에 대해서는 [Chapter 4](/course/chapter4/3)에서 자세히 알아보겠습니다. -🚀 **고급 설정**: 사용 가능한 모든 훈련 인수와 최적화 전략에 대한 자세한 정보는 [TrainingArguments 문서](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments)와 [훈련 구성 쿡북](https://huggingface.co/learn/cookbook/en/fine_tuning_code_llm_on_single_gpu)을 확인하세요. +🚀 **고급 설정**: 사용 가능한 모든 훈련 인수와 최적화 전략에 대한 자세한 정보는 [TrainingArguments 문서](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments)와 [훈련 구성 쿡북](https://huggingface.co/learn/cookbook/en/fine_tuning_code_llm_on_single_gpu)을 참고하세요. -두 번째 단계는 모델을 정의하는 것입니다. [이전 챕터](/course/chapter2)에서와 같이 두 개의 라벨과 함께 `AutoModelForSequenceClassification` 클래스를 사용하겠습니다: +두 번째 단계는 모델을 정의하는 것입니다. [이전 챕터](/course/chapter2)에서와 같이 두 개의 라벨과 함께 `AutoModelForSequenceClassification` 클래스를 사용하겠습니다. ```py from transformers import AutoModelForSequenceClassification From 6a5fad8e543a36012a7216293b93baca11c52982 Mon Sep 17 00:00:00 2001 From: Youngdong <48584373+Youngdong2@users.noreply.github.com> Date: Sat, 26 Jul 2025 14:30:18 +0900 Subject: [PATCH 24/43] Update chapters/ko/chapter3/3.mdx Co-authored-by: Harheem Kim <49297157+harheem@users.noreply.github.com> --- chapters/ko/chapter3/3.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapters/ko/chapter3/3.mdx b/chapters/ko/chapter3/3.mdx index 7cd5cd15d..90505d181 100644 --- a/chapters/ko/chapter3/3.mdx +++ b/chapters/ko/chapter3/3.mdx @@ -66,7 +66,7 @@ model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_label [Chapter 2](/course/chapter2)와 달리 이 사전훈련된 모델을 인스턴스화하면 경고 메시지가 나타나는 것을 확인할 수 있습니다. 이는 BERT가 문장 쌍 분류를 위해 사전 훈련되지 않았기 때문에, 사전 훈련된 모델의 헤드가 제거되고 시퀀스 분류에 적합한 새로운 헤드가 추가되었기 때문입니다. 경고는 일부 가중치(제거된 사전 훈련 헤드에 해당하는 가중치)가 사용되지 않았고, 일부 다른 가중치(새로운 헤드용)가 무작위로 초기화되었다는 것을 나타냅니다. 마지막으로 모델을 훈련하도록 권장하는데, 이것이 바로 우리가 지금 할 일입니다. -모델이 준비되면, 지금까지 구성한 모든 객체들(`model`, `training_args`, 훈련 및 검증 데이터셋, `data_collator`, `processing_class`)를 전달하여 `Trainer`를 정의할 수 있습니다. `processing_class` 매개변수는 비교적 최근에 추가된 기능으로, `Trainer`에게 어떤 토크나이저를 사용해 데이터를 처리할지 알려줍니다: +모델이 준비되면, 지금까지 구성한 모든 객체(`model`, `training_args`, 훈련 및 검증 데이터셋, `data_collator`, `processing_class`)를 전달하여 `Trainer`를 정의할 수 있습니다. `processing_class` 매개변수는 비교적 최근에 추가된 기능으로, `Trainer`에게 어떤 토크나이저를 사용해 데이터를 처리할지 알려줍니다. ```py from transformers import Trainer From 2a782fe3557a2344575d2c9f27c1842192291ddf Mon Sep 17 00:00:00 2001 From: Youngdong <48584373+Youngdong2@users.noreply.github.com> Date: Sat, 26 Jul 2025 14:32:47 +0900 Subject: [PATCH 25/43] Apply suggestions from code review Co-authored-by: Harheem Kim <49297157+harheem@users.noreply.github.com> --- chapters/ko/chapter3/3.mdx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/chapters/ko/chapter3/3.mdx b/chapters/ko/chapter3/3.mdx index 90505d181..a8b929b7f 100644 --- a/chapters/ko/chapter3/3.mdx +++ b/chapters/ko/chapter3/3.mdx @@ -64,7 +64,7 @@ from transformers import AutoModelForSequenceClassification model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) ``` -[Chapter 2](/course/chapter2)와 달리 이 사전훈련된 모델을 인스턴스화하면 경고 메시지가 나타나는 것을 확인할 수 있습니다. 이는 BERT가 문장 쌍 분류를 위해 사전 훈련되지 않았기 때문에, 사전 훈련된 모델의 헤드가 제거되고 시퀀스 분류에 적합한 새로운 헤드가 추가되었기 때문입니다. 경고는 일부 가중치(제거된 사전 훈련 헤드에 해당하는 가중치)가 사용되지 않았고, 일부 다른 가중치(새로운 헤드용)가 무작위로 초기화되었다는 것을 나타냅니다. 마지막으로 모델을 훈련하도록 권장하는데, 이것이 바로 우리가 지금 할 일입니다. +[Chapter 2](/course/chapter2)와 달리 이 사전 훈련된 모델을 인스턴스화하면 경고 메시지가 나타나는 것을 확인할 수 있습니다. 이는 BERT가 문장 쌍 분류를 위해 사전 훈련되지 않았기 때문에, 사전 훈련된 모델의 헤드가 제거되고 시퀀스 분류에 적합한 새로운 헤드가 추가되었기 때문입니다. 경고는 일부 가중치(제거된 사전 훈련 헤드에 해당하는 가중치)가 사용되지 않았고, 일부 다른 가중치(새로운 헤드용)가 무작위로 초기화되었다는 것을 나타냅니다. 마지막으로 모델을 훈련시키라는 메시지가 나오는데, 바로 지금부터 그 작업을 시작하겠습니다. 모델이 준비되면, 지금까지 구성한 모든 객체(`model`, `training_args`, 훈련 및 검증 데이터셋, `data_collator`, `processing_class`)를 전달하여 `Trainer`를 정의할 수 있습니다. `processing_class` 매개변수는 비교적 최근에 추가된 기능으로, `Trainer`에게 어떤 토크나이저를 사용해 데이터를 처리할지 알려줍니다. @@ -81,15 +81,15 @@ trainer = Trainer( ) ``` -`processing_class`로 토크나이저를 전달하면, `Trainer`가 기본적으로 `DataCollatorWithPadding`을 `data_collator`로 사용합니다. 따라서 이 경우에는 `data_collator=data_collator` 줄을 생략할 수 있지만, 처리 파이프라인의 중요한 부분을 보여드리기 위해 여기에 포함했습니다. +`processing_class`에 토크나이저를 전달하면, `Trainer`가 기본적으로 `DataCollatorWithPadding`을 `data_collator`로 사용합니다. 따라서 이 경우에는 `data_collator=data_collator` 줄을 생략할 수 있지만, 데이터 처리 파이프라인의 중요한 부분을 보여드리기 위해 코드에 포함했습니다. -📖 **더 자세히 알아보기**: Trainer 클래스와 그 매개변수에 대한 포괄적인 세부 정보는 [Trainer API 문서](https://huggingface.co/docs/transformers/main/en/main_classes/trainer)를 방문하고 [훈련 쿡북 레시피](https://huggingface.co/learn/cookbook/en/fine_tuning_code_llm_on_single_gpu)에서 고급 사용 패턴을 살펴보세요. +📖 **더 자세히 알아보기**: Trainer 클래스와 그 매개변수에 대한 자세한 내용은 [Trainer API 문서](https://huggingface.co/docs/transformers/main/en/main_classes/trainer)를 방문하고 [훈련 쿡북 레시피](https://huggingface.co/learn/cookbook/en/fine_tuning_code_llm_on_single_gpu)에서 고급 사용 패턴을 살펴보세요. -데이터셋에서 모델을 미세 조정하려면 `Trainer`의 `train()` 메서드를 호출하기만 하면 됩니다: +데이터셋에서 모델을 미세 조정하려면 `Trainer`의 `train()` 메소드를 호출하기만 하면 됩니다. ```py trainer.train() From 19649532605fcf316824cadbf98d9a2d815edde3 Mon Sep 17 00:00:00 2001 From: Youngdong <48584373+Youngdong2@users.noreply.github.com> Date: Sat, 26 Jul 2025 14:44:56 +0900 Subject: [PATCH 26/43] Apply suggestions from code review Co-authored-by: Harheem Kim <49297157+harheem@users.noreply.github.com> --- chapters/ko/chapter3/3.mdx | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/chapters/ko/chapter3/3.mdx b/chapters/ko/chapter3/3.mdx index a8b929b7f..e23eeaf2d 100644 --- a/chapters/ko/chapter3/3.mdx +++ b/chapters/ko/chapter3/3.mdx @@ -95,15 +95,15 @@ trainer = Trainer( trainer.train() ``` -이렇게 하면 미세 조정이 시작됩니다(GPU에서는 몇 분 정도 걸릴 거예요). 500단계마다 훈련 손실이 보고되지만, 모델의 성능이 얼마나 좋은지(또는 나쁜지)는 알려주지 않을 겁니다. 그 이유는 다음과 같습니다: +이렇게 하면 미세 조정이 시작됩니다(GPU에서는 몇 분 정도 소요됩니다). 500단계마다 훈련 손실이 출력되지만, 모델의 성능이 얼마나 좋은지(또는 나쁜지)는 알려주지 않습니다. 그 이유는 다음과 같습니다. -1. `TrainingArguments`에서 `eval_strategy`를 `"steps"` (매 `eval_steps`마다 평가) 또는 `"epoch"` (각 에포크 종료 시 평가)로 설정하여 훈련 중에 평가하도록 `Trainer`에 알리지 않았습니다. -2. 해당 평가 중에 메트릭을 계산하기 위한 `compute_metrics()` 함수를 `Trainer`에 제공하지 않았습니다 (그렇지 않으면 평가에서 손실만 출력되는데, 이는 직관적이지 않은 숫자입니다). +1. `TrainingArguments`에서 `eval_strategy`를 `"steps"` (매 `eval_steps`마다 평가) 또는 `"epoch"` (각 에포크 종료 시 평가)로 설정하지 않았습니다. +2. 평가 중에 메트릭을 계산하기 위한 `compute_metrics()` 함수를 `Trainer`에 제공하지 않았습니다. 이 함수가 없으면 평가에서 손실 값만 출력되는데, 이 값만으로는 성능을 파악하기 어렵습니다. ### 평가[[evaluation]] -유용한 `compute_metrics()` 함수를 어떻게 만들고 다음 훈련 시 사용할 수 있는지 알아봅시다. 이 함수는 `EvalPrediction` 객체(`predictions` 필드와 `label_ids` 필드가 있는 명명된 튜플)를 인수로 받아야 하며 문자열을 부동 소수점 값에 매핑하는 딕셔너리(문자열은 반환되는 메트릭의 이름이고, 부동 소수점 값은 해당 값)를 반환합니다. 모델에서 예측값을 얻으려면 `Trainer.predict()`를 사용할 수 있습니다: +이제 유용한 `compute_metrics()` 함수를 어떻게 만들고 다음 훈련 시 사용할 수 있는지 알아보겠습니다. 이 함수는 `EvalPrediction` 객체(`predictions` 필드와 `label_ids` 필드를 갖는 명명된 튜플)를 입력받습니다. 그리고 각 메트릭의 이름을 키(문자열)로, 성능을 값(부동소수점)으로 갖는 딕셔너리를 반환해야 합니다. 모델의 예측값을 얻기 위해 `Trainer.predict()`를 사용할 수 있습니다. ```py predictions = trainer.predict(tokenized_datasets["validation"]) @@ -114,9 +114,9 @@ print(predictions.predictions.shape, predictions.label_ids.shape) (408, 2) (408,) ``` -`predict()` 메서드의 출력은 `predictions`, `label_ids`, `metrics` 세 개의 필드가 있는 또 다른 명명된 튜플입니다. `metrics` 필드에는 전달된 데이터셋에 대한 손실 값과 몇 가지 시간 관련 메트릭(예측에 총 소요된 시간 및 평균 시간)만 포함됩니다. 하지만 `compute_metrics()` 함수를 완성하여 `Trainer`에 전달하면, 이 필드에 `compute_metrics()`가 반환하는 지표들도 함께 포함될 거예요. +`predict()` 메소드의 출력은 `predictions`, `label_ids`, `metrics` 세 개의 필드가 있는 또 다른 명명된 튜플입니다. `metrics` 필드에는 전달된 데이터셋에 대한 손실 값과 시간 관련 메트릭(총 예측 시간, 평균 예측 시간)만 포함됩니다. 하지만 `compute_metrics()` 함수를 완성하여 `Trainer`에 전달하면, 이 필드에 `compute_metrics()`가 반환하는 메트릭들도 함께 포함됩니다. -보시다시피, `predictions`는 408 x 2 모양의 2차원 배열입니다 (408은 predict()에 전달한 데이터셋의 요소 수입니다). 이 값들은 `predict()`에 전달한 데이터셋의 각 요소에 대한 로짓입니다 ([이전 챕터](/course/chapter2)에서 보았듯이 모든 Transformer 모델은 로짓을 반환합니다). 이 로짓을 우리가 가진 레이블과 비교할 수 있는 예측값으로 변환하려면, 두 번째 축에서 최댓값을 가진 인덱스를 취해야 합니다: +보시다시피, `predictions`는 408 x 2 모양의 2차원 배열입니다 (408은 predict()에 전달한 데이터셋의 샘플 개수입니다). 이 값들은 `predict()`에 전달한 데이터셋의 각 샘플에 대한 로짓입니다 ([이전 챕터](/course/chapter2)에서 보았듯이 모든 Transformer 모델은 로짓을 반환합니다). 이 로짓을 우리가 가진 레이블과 비교할 수 있는 예측값으로 변환하려면, 두 번째 축에서 최댓값을 가진 인덱스를 구해야 합니다. ```py import numpy as np @@ -124,7 +124,7 @@ import numpy as np preds = np.argmax(predictions.predictions, axis=-1) ``` -이제 이 `preds`를 라벨과 비교할 수 있습니다. `compute_metric()` 함수를 빌드하기 위해 🤗 [Evaluate](https://github.com/huggingface/evaluate/) 라이브러리의 메트릭을 활용하겠습니다. MRPC 데이터셋과 관련된 메트릭을 불러오는 건 데이터셋을 불러왔던 것만큼이나 쉽습니다. 이번에는 `evaluate.load()` 함수를 사용하면 됩니다. 이렇게 반환된 객체에는 메트릭 계산을 수행할 수 있는 `compute()` 메서드가 있습니다: +이제 이 `preds`를 라벨과 비교할 수 있습니다. `compute_metric()` 함수를 빌드하기 위해 🤗 [Evaluate](https://github.com/huggingface/evaluate/) 라이브러리의 메트릭을 활용하겠습니다. 데이터셋을 로드했던 것처럼, MRPC 데이터셋과 관련된 메트릭도 `evaluate.load()` 함수로 쉽게 로드할 수 있습니다. 반환된 객체의 `compute()` 메서드를 사용해 메트릭을 계산할 수 있습니다. ```py import evaluate @@ -143,9 +143,9 @@ metric.compute(predictions=preds, references=predictions.label_ids) -모델 헤드의 무작위 초기화 때문에 얻게 되는 정확한 결과는 달라질 수 있습니다. 여기서는 우리 모델이 검증 세트에서 85.78%의 정확도와 89.97%의 F1 점수를 달성했음을 볼 수 있습니다. 이 두 가지는 GLUE 벤치마크의 MRPC 데이터셋에서 결과를 평가하는 데 사용되는 메트릭입니다. [BERT 논문](https://arxiv.org/pdf/1810.04805.pdf)의 표에는 기본 모델에 대해 F1 점수가 88.9로 보고되었습니다. 당시에는 `uncased` 모델을 사용했지만, 우리는 현재 `cased` 모델을 사용하고 있기 때문에 더 나은 결과가 나온 것입니다. +모델 헤드의 가중치가 무작위로 초기화되기 때문에 얻게 되는 결과는 조금씩 다를 수 있습니다. 결과를 보면 우리 모델이 검증 세트에서 85.78%의 정확도와 89.97%의 F1 점수를 달성했음을 볼 수 있습니다. 이 두 가지는 GLUE 벤치마크의 MRPC 데이터셋에서 결과를 평가하는 데 사용되는 메트릭입니다. [BERT 논문](https://arxiv.org/pdf/1810.04805.pdf)에서는 기본 모델의 F1 점수를 88.9로 보고하였습니다. 당시에는 `uncased` 모델을 사용했지만, 우리는 현재 `cased` 모델을 사용하고 있기 때문에 더 나은 결과가 나온 것입니다. -이 모든 것을 종합하면, 다음처럼 `compute_metrics()` 함수를 얻을 수 있습니다: +이 모든 것을 종합하면, 다음처럼 `compute_metrics()` 함수를 다음과 같이 정의할 수 있습니다. ```py def compute_metrics(eval_preds): @@ -155,7 +155,7 @@ def compute_metrics(eval_preds): return metric.compute(predictions=predictions, references=labels) ``` -각 에폭이 끝날 때마다 메트릭을 보고하기 위해 이 `compute_metrics()` 함수가 실제로 어떻게 사용되는지 보려면, 다음과 같이 새 `Trainer`를 정의하면 됩니다: +각 에폭이 끝날 때마다 메트릭이 출력되도록, 이 `compute_metrics()` 함수가 포함하여 `Trainer`를 새로 정의해 보겠습니다. ```py training_args = TrainingArguments("test-trainer", eval_strategy="epoch") @@ -172,13 +172,13 @@ trainer = Trainer( ) ``` -참고로, 우리는 `eval_strategy`를 `"epoch"`으로 설정한 새로운 `TrainingArguments`와 새로운 모델을 생성합니다. 이렇게 하지 않으면 이미 훈련된 모델의 훈련을 계속하게 될 겁니다. 새로운 훈련을 시작하려면 다음을 실행하세요: +참고로, 우리는 `eval_strategy`를 `"epoch"`으로 설정한 새로운 `TrainingArguments`와 새로운 모델을 생성합니다. 이렇게 하지 않으면 이미 훈련된 모델의 훈련을 계속하게 될 겁니다. 새로운 훈련을 시작하려면 다음을 실행하세요. ```py trainer.train() ``` -이번에는 훈련 손실 외에도 각 에폭이 끝날 때마다 검증 손실과 메트릭을 보고할 겁니다. 모델 헤드의 무작위 초기화 때문에 여러분이 얻는 정확도/F1 점수는 우리가 얻은 결과와 약간 다를 수 있지만, 비슷한 범위에 있을 거예요. +이번에는 훈련 손실 외에도 각 에폭이 끝날 때마다 검증 손실과 메트릭이 함께 출력될 겁니다. 앞서 말했듯이 모델 헤드의 무작위 초기화 때문에 여러분이 얻는 정확도/F1 점수는 우리가 얻은 결과와 약간 다를 수 있지만, 비슷한 범위에 있을 겁니다. ### 고급 훈련 기능[[advanced-training-features]] From 7f4cda9f3f2c10da74027eb5654b5a1b328248eb Mon Sep 17 00:00:00 2001 From: Youngdong <48584373+Youngdong2@users.noreply.github.com> Date: Sat, 26 Jul 2025 14:48:56 +0900 Subject: [PATCH 27/43] Apply suggestions from code review Co-authored-by: Harheem Kim <49297157+harheem@users.noreply.github.com> --- chapters/ko/chapter3/3.mdx | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/chapters/ko/chapter3/3.mdx b/chapters/ko/chapter3/3.mdx index e23eeaf2d..4f1b830f3 100644 --- a/chapters/ko/chapter3/3.mdx +++ b/chapters/ko/chapter3/3.mdx @@ -182,9 +182,9 @@ trainer.train() ### 고급 훈련 기능[[advanced-training-features]] -`Trainer`는 현대 딥러닝의 모범 사례들을 쉽게 활용할 수 있도록 다양한 내장 기능을 제공합니다: +`Trainer`는 현대 딥러닝의 모범 사례들을 쉽게 활용할 수 있도록 다양한 내장 기능을 제공합니다. -**혼합 정밀도 훈련**: 더 빠른 훈련과 메모리 사용량 감소를 위해 훈련 인수에서 `fp16=True`를 사용하세요: +**혼합 정밀도 훈련**: 더 빠른 훈련과 메모리 사용량 감소를 위해 훈련 인수에서 `fp16=True`를 설정하세요. ```py training_args = TrainingArguments( @@ -194,18 +194,18 @@ training_args = TrainingArguments( ) ``` -**그레이디언트 누적**: GPU 메모리가 제한될 때 효과적인 더 큰 배치 크기를 위해: +**그레이디언트 누적**: GPU 메모리가 부족할 때 더 큰 배치 크기로 학습하는 효과를 낼 수 있습니다. ```py training_args = TrainingArguments( "test-trainer", eval_strategy="epoch", per_device_train_batch_size=4, - gradient_accumulation_steps=4, # 효과적인 배치 크기 = 4 * 4 = 16 + gradient_accumulation_steps=4, # 유효 배치 크기 = 4 * 4 = 16 ) ``` -**학습률 스케줄링**: Trainer는 기본적으로 선형 감소 방식을 사용하지만, 사용자 맞춤 설정이 가능합니다: +**학습률 스케줄링**: Trainer는 기본적으로 선형 감소 방식을 사용하지만, 사용자 맞춤 설정이 가능합니다. ```py training_args = TrainingArguments( @@ -222,9 +222,9 @@ training_args = TrainingArguments( -`Trainer`는 여러 GPU 또는 TPU에서 즉시 작동하며 분산 훈련을 위한 많은 옵션을 제공합니다. 지원하는 모든 것에 대해서는 Chapter 10에서 다루겠습니다. +`Trainer`는 여러 GPU 또는 TPU에서 즉시 작동하며 분산 훈련을 위한 많은 옵션을 제공합니다. 이와 관련된 모든 내용은 Chapter 10에서 다루겠습니다. -이것으로 `Trainer` API를 사용한 미세 조정에 대한 소개를 마칩니다. 대부분의 일반적인 NLP 작업에 대한 예제는 [Chapter 7](/course/chapter7)에서 다룰 예정이며, 지금부터는 순수 PyTorch 훈련 루프를 사용하여 동일한 작업을 수행하는 방법을 살펴보겠습니다. +이것으로 `Trainer` API를 사용한 미세 조정 소개를 마칩니다. 대부분의 일반적인 NLP 작업에 대한 예제는 [Chapter 7](/course/chapter7)에서 다룰 예정이며, 다음으로는 순수 PyTorch 코드로 동일한 작업을 수행하는 방법을 살펴보겠습니다. @@ -234,7 +234,7 @@ training_args = TrainingArguments( ## 섹션 퀴즈[[section-quiz]] -Trainer API와 미세 조정 개념에 대한 이해를 테스트해보세요: +Trainer API와 미세 조정 개념에 대한 이해를 테스트해보세요. ### 1. `Trainer`에서 processing_class 매개변수의 목적은 무엇인가요? @@ -260,7 +260,7 @@ Trainer API와 미세 조정 개념에 대한 이해를 테스트해보세요: ]} /> -### 2. 훈련 중 평가가 얼마나 자주 발생하는지 제어하는 TrainingArguments 매개변수는 무엇인가요? +### 2. 훈련 중 평가가 얼마나 자주 발생하는지를 제어하는 TrainingArguments 매개변수는 무엇인가요? 💡 **핵심 요점:** -- `Trainer` API는 대부분의 훈련 복잡성을 처리하는 높은 수준의 인터페이스를 제공합니다 -- 적절한 데이터 처리를 위해 `processing_class`를 사용하여 토크나이저를 지정하세요 -- `TrainingArguments`는 학습률, 배치 크기, 평가 전략, 최적화 등 훈련의 모든 측면을 제어합니다 -- `compute_metrics`를 사용하면 훈련 손실 외에 사용자 정의 평가 메트릭을 활용할 수 있습니다 -- 혼합 정밀도(`fp16=True`)와 그레이디언트 누적과 같은 최신 기능은 훈련 효율성을 크게 향상시킬 수 있습니다 +- `Trainer` API는 대부분의 훈련 복잡성을 처리하는 높은 수준의 인터페이스를 제공합니다. +- `processing_class`는 적절한 데이터 처리를 위해 토크나이저를 저장하는 데 사용됩니다. +- `TrainingArguments`는 학습률, 배치 크기, 평가 전략, 최적화 등 훈련의 모든 측면을 제어합니다. +- `compute_metrics`를 사용하면 훈련 손실 외에 사용자 정의 평가 메트릭을 활용할 수 있습니다. +- 혼합 정밀도(`fp16=True`)와 그레이디언트 누적과 같은 최신 기능은 훈련 효율성을 크게 향상시킬 수 있습니다. From c4ff46dc19a764bf756927c426fe75b5726811ac Mon Sep 17 00:00:00 2001 From: chaewonsong Date: Sun, 3 Aug 2025 16:33:57 +0900 Subject: [PATCH 28/43] docs: ko: understanding_learning_curves --- chapters/ko/_toctree.yml | 2 + chapters/ko/chapter3/5.mdx | 419 +++++++++++++++++++++++++++++++++++++ 2 files changed, 421 insertions(+) create mode 100644 chapters/ko/chapter3/5.mdx diff --git a/chapters/ko/_toctree.yml b/chapters/ko/_toctree.yml index 692c38c37..d63fbf510 100644 --- a/chapters/ko/_toctree.yml +++ b/chapters/ko/_toctree.yml @@ -51,6 +51,8 @@ sections: - local: chapter3/2 title: 데이터 처리 + - local: chapter3/5 + title: 학습 곡선 이해하기 - title: 5. 🤗 Datasets 라이브러리 sections: diff --git a/chapters/ko/chapter3/5.mdx b/chapters/ko/chapter3/5.mdx new file mode 100644 index 000000000..ee107eaf8 --- /dev/null +++ b/chapters/ko/chapter3/5.mdx @@ -0,0 +1,419 @@ +# Understanding Learning Curves[[understanding-learning-curves]] + + + +Now that you've learned how to implement fine-tuning using both the `Trainer` API and custom training loops, it's crucial to understand how to interpret the results. Learning curves are invaluable tools that help you evaluate your model's performance during training and identify potential issues before they reduce performance. + +In this section, we'll explore how to read and interpret accuracy and loss curves, understand what different curve shapes tell us about our model's behavior, and learn how to address common training issues. + +## What are Learning Curves?[[what-are-learning-curves]] + +Learning curves are visual representations of your model's performance metrics over time during training. The two most important curves to monitor are: + +- **Loss curves**: Show how the model's error (loss) changes over training steps or epochs +- **Accuracy curves**: Show the percentage of correct predictions over training steps or epochs + +These curves help us understand whether our model is learning effectively and can guide us in making adjustments to improve performance. In Transformers, these metrics are individually computed for each batch and then logged to the disk. We can then use libraries like [Weights & Biases](https://wandb.ai/) to visualize these curves and track our model's performance over time. + +### Loss Curves[[loss-curves]] + +The loss curve shows how the model's error decreases over time. In a typical successful training run, you'll see a curve similar to the one below: + +![Loss Curve](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/1.png) + +- **High initial loss**: The model starts without optimization, so predictions are initially poor +- **Decreasing loss**: As training progresses, the loss should generally decrease +- **Convergence**: Eventually, the loss stabilizes at a low value, indicating that the model has learned the patterns in the data + +As in previous chapters, we can use the `Trainer` API to track these metrics and visualize them in a dashboard. Below is an example of how to do this with Weights & Biases. + +```python +# Example of tracking loss during training with the Trainer +from transformers import Trainer, TrainingArguments +import wandb + +# Initialize Weights & Biases for experiment tracking +wandb.init(project="transformer-fine-tuning", name="bert-mrpc-analysis") + +training_args = TrainingArguments( + output_dir="./results", + eval_strategy="steps", + eval_steps=50, + save_steps=100, + logging_steps=10, # Log metrics every 10 steps + num_train_epochs=3, + per_device_train_batch_size=16, + per_device_eval_batch_size=16, + report_to="wandb", # Send logs to Weights & Biases +) + +trainer = Trainer( + model=model, + args=training_args, + train_dataset=tokenized_datasets["train"], + eval_dataset=tokenized_datasets["validation"], + data_collator=data_collator, + processing_class=tokenizer, + compute_metrics=compute_metrics, +) + +# Train and automatically log metrics +trainer.train() +``` + +### Accuracy Curves[[accuracy-curves]] + +The accuracy curve shows the percentage of correct predictions over time. Unlike loss curves, accuracy curves should generally increase as the model learns and can typically include more steps than the loss curve. + +![Accuracy Curve](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/2.png) + +- **Start low**: Initial accuracy should be low, as the model has not yet learned the patterns in the data +- **Increase with training**: Accuracy should generally improve as the model learns if it is able to learn the patterns in the data +- **May show plateaus**: Accuracy often increases in discrete jumps rather than smoothly, as the model makes predictions that are close to the true labels + + + +💡 **Why Accuracy Curves Are "Steppy"**: Unlike loss, which is continuous, accuracy is calculated by comparing discrete predictions to true labels. Small improvements in model confidence might not change the final prediction, causing accuracy to remain flat until a threshold is crossed. + + + +### Convergence[[convergence]] + +Convergence occurs when the model's performance stabilizes and the loss and accuracy curves level off. This is a sign that the model has learned the patterns in the data and is ready to be used. In simple terms, we are aiming for the model to converge to a stable performance every time we train it. + +![Convergence](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/4.png) + +Once models have converged, we can use them to make predictions on new data and refer to evaluation metrics to understand how well the model is performing. + +## Interpreting Learning Curve Patterns[[interpreting-learning-curve-patterns]] + +Different curve shapes reveal different aspects of your model's training. Let's examine the most common patterns and what they mean. + +### Healthy Learning Curves[[healthy-learning-curves]] + +A well-behaved training run typically shows curve shapes similar to the one below: + +![Healthy Loss Curve](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/5.png) + +Let's look at the illustration above. It displays both the loss curve (on the left) and the corresponding accuracy curve (on the right). These curves have distinct characteristics. + +The loss curve shows the value of the model's loss over time. Initially, the loss is high and then it gradually decreases, indicating that the model is improving. A decrease in the loss value suggests that the model is making better predictions, as the loss represents the error between the predicted output and the true output. + +Now let's shift our focus to the accuracy curve. It represents the model's accuracy over time. The accuracy curve begins at a low value and increases as training progresses. Accuracy measures the proportion of correctly classified instances. So, as the accuracy curve rises, it signifies that the model is making more correct predictions. + +One notable difference between the curves is the smoothness and the presence of "plateaus" on the accuracy curve. While the loss decreases smoothly, the plateaus on the accuracy curve indicate discrete jumps in accuracy instead of a continuous increase. This behavior is attributed to how accuracy is measured. The loss can improve if the model's output gets closer to the target, even if the final prediction is still incorrect. Accuracy, however, only improves when the prediction crosses the threshold to be correct. + +For example, in a binary classifier distinguishing cats (0) from dogs (1), if the model predicts 0.3 for an image of a dog (true value 1), this is rounded to 0 and is an incorrect classification. If in the next step it predicts 0.4, it's still incorrect. The loss will have decreased because 0.4 is closer to 1 than 0.3, but the accuracy remains unchanged, creating a plateau. The accuracy will only jump up when the model predicts a value greater than 0.5 that gets rounded to 1. + + + +**Characteristics of healthy curves:** +- **Smooth decline in loss**: Both training and validation loss decrease steadily +- **Close training/validation performance**: Small gap between training and validation metrics +- **Convergence**: Curves level off, indicating the model has learned the patterns + + + +### Practical Examples[[practical-examples]] + +Let's work through some practical examples of learning curves. First, we will highlight some approaches to monitor the learning curves during training. Below, we will break down the different patterns that can be observed in the learning curves. + +#### During Training[[during-training]] + +During the training process (after you've hit `trainer.train()`), you can monitor these key indicators: + +1. **Loss convergence**: Is the loss still decreasing or has it plateaued? +2. **Overfitting signs**: Is validation loss starting to increase while training loss decreases? +3. **Learning rate**: Are the curves too erratic (LR too high) or too flat (LR too low)? +4. **Stability**: Are there sudden spikes or drops that indicate problems? + +#### After Training[[after-training]] + +After the training process is complete, you can analyze the complete curves to understand the model's performance. + +1. **Final performance**: Did the model reach acceptable performance levels? +2. **Efficiency**: Could the same performance be achieved with fewer epochs? +3. **Generalization**: How close are training and validation performance? +4. **Trends**: Would additional training likely improve performance? + + + +🔍 **W&B Dashboard Features**: Weights & Biases automatically creates beautiful, interactive plots of your learning curves. You can: +- Compare multiple runs side by side +- Add custom metrics and visualizations +- Set up alerts for anomalous behavior +- Share results with your team + +Learn more in the [Weights & Biases documentation](https://docs.wandb.ai/). + + +#### Overfitting[[overfitting]] + +Overfitting occurs when the model learns too much from the training data and is unable to generalize to different data (represented by the validation set). + +![Overfitting](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/10.png) + +**Symptoms:** + +- Training loss continues to decrease while validation loss increases or plateaus +- Large gap between training and validation accuracy +- Training accuracy much higher than validation accuracy + +**Solutions for overfitting:** +- **Regularization**: Add dropout, weight decay, or other regularization techniques +- **Early stopping**: Stop training when validation performance stops improving +- **Data augmentation**: Increase training data diversity +- **Reduce model complexity**: Use a smaller model or fewer parameters + +In the sample below, we use early stopping to prevent overfitting. We set the `early_stopping_patience` to 3, which means that if the validation loss does not improve for 3 consecutive epochs, the training will be stopped. + +```python +# Example of detecting overfitting with early stopping +from transformers import EarlyStoppingCallback + +training_args = TrainingArguments( + output_dir="./results", + eval_strategy="steps", + eval_steps=100, + save_strategy="steps", + save_steps=100, + load_best_model_at_end=True, + metric_for_best_model="eval_loss", + greater_is_better=False, + num_train_epochs=10, # Set high, but we'll stop early +) + +# Add early stopping to prevent overfitting +trainer = Trainer( + model=model, + args=training_args, + train_dataset=tokenized_datasets["train"], + eval_dataset=tokenized_datasets["validation"], + data_collator=data_collator, + processing_class=tokenizer, + compute_metrics=compute_metrics, + callbacks=[EarlyStoppingCallback(early_stopping_patience=3)], +) +``` + +#### 2. Underfitting[[underfitting]] + +Underfitting occurs when the model is too simple to capture the underlying patterns in the data. This can happen for several reasons: + +- The model is too small or lacks capacity to learn the patterns +- The learning rate is too low, causing slow learning +- The dataset is too small or not representative of the problem +- The model is not properly regularized + +![Underfitting](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/7.png) + +**Symptoms:** +- Both training and validation loss remain high +- Model performance plateaus early in training +- Training accuracy is lower than expected + +**Solutions for underfitting:** +- **Increase model capacity**: Use a larger model or more parameters +- **Train longer**: Increase the number of epochs +- **Adjust learning rate**: Try different learning rates +- **Check data quality**: Ensure your data is properly preprocessed + +In the sample below, we train for more epochs to see if the model can learn the patterns in the data. + +```python +from transformers import TrainingArguments + +training_args = TrainingArguments( + output_dir="./results", + -num_train_epochs=5, + +num_train_epochs=10, +) +``` + +#### 3. Erratic Learning Curves[[erratic-learning-curves]] + +Erratic learning curves occur when the model is not learning effectively. This can happen for several reasons: + +- The learning rate is too high, causing the model to overshoot the optimal parameters +- The batch size is too small, causing the model to learn slowly +- The model is not properly regularized, causing it to overfit to the training data +- The dataset is not properly preprocessed, causing the model to learn from noise + +![Erratic Learning Curves](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/3.png) + +**Symptoms:** +- Frequent fluctuations in loss or accuracy +- Curves show high variance or instability +- Performance oscillates without clear trend + +Both training and validation curves show erratic behavior. + +![Erratic Learning Curves](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/9.png) + +**Solutions for erratic curves:** +- **Lower learning rate**: Reduce step size for more stable training +- **Increase batch size**: Larger batches provide more stable gradients +- **Gradient clipping**: Prevent exploding gradients +- **Better data preprocessing**: Ensure consistent data quality + +In the sample below, we lower the learning rate and increase the batch size. + +```python +from transformers import TrainingArguments + +training_args = TrainingArguments( + output_dir="./results", + -learning_rate=1e-5, + +learning_rate=1e-4, + -per_device_train_batch_size=16, + +per_device_train_batch_size=32, +) +``` + +## Key Takeaways[[key-takeaways]] + +Understanding learning curves is crucial for becoming an effective machine learning practitioner. These visual tools provide immediate feedback about your model's training progress and help you make informed decisions about when to stop training, adjust hyperparameters, or try different approaches. With practice, you'll develop an intuitive understanding of what healthy learning curves look like and how to address issues when they arise. + + + +💡 **Key Takeaways:** +- Learning curves are essential tools for understanding model training progress +- Monitor both loss and accuracy curves, but remember they have different characteristics +- Overfitting shows as diverging training/validation performance +- Underfitting shows as poor performance on both training and validation data +- Tools like Weights & Biases make it easy to track and analyze learning curves +- Early stopping and proper regularization can address most common training issues + +🔬 **Next Steps**: Practice analyzing learning curves on your own fine-tuning experiments. Try different hyperparameters and observe how they affect the curve shapes. This hands-on experience is the best way to develop intuition for reading training progress. + + + +## Section Quiz[[section-quiz]] + +Test your understanding of learning curves and training analysis: + +### 1. What does it typically mean when training loss decreases but validation loss starts increasing? + + + +### 2. Why do accuracy curves often show a "steppy" or plateau-like pattern rather than smooth increases? + + + +### 3. What is the best approach when you observe erratic, highly fluctuating learning curves? + + + +### 4. When should you consider using early stopping? + + + +### 5. What indicates that your model might be underfitting? + + + From e446938a2c70707b8640b93f203e7271dcbe01ef Mon Sep 17 00:00:00 2001 From: chaewonsong Date: Sun, 3 Aug 2025 16:44:59 +0900 Subject: [PATCH 29/43] feat: nmt draft --- chapters/ko/chapter3/5.mdx | 337 ++++++++++++++++++------------------- 1 file changed, 168 insertions(+), 169 deletions(-) diff --git a/chapters/ko/chapter3/5.mdx b/chapters/ko/chapter3/5.mdx index ee107eaf8..8d71f5308 100644 --- a/chapters/ko/chapter3/5.mdx +++ b/chapters/ko/chapter3/5.mdx @@ -1,4 +1,4 @@ -# Understanding Learning Curves[[understanding-learning-curves]] +# 학습 곡선 이해하기[[understanding-learning-curves]] -Now that you've learned how to implement fine-tuning using both the `Trainer` API and custom training loops, it's crucial to understand how to interpret the results. Learning curves are invaluable tools that help you evaluate your model's performance during training and identify potential issues before they reduce performance. +이제 `Trainer` API와 사용자 정의 훈련 루프를 모두 사용하여 미세 조정을 구현하는 방법을 배웠으므로, 결과를 해석하는 방법을 이해하는 것이 중요합니다. 학습 곡선은 훈련 중 모델의 성능을 평가하고 성능을 저하시키기 전에 잠재적인 문제를 식별하는 데 도움이 되는 매우 유용한 도구입니다. -In this section, we'll explore how to read and interpret accuracy and loss curves, understand what different curve shapes tell us about our model's behavior, and learn how to address common training issues. +이 섹션에서는 정확도와 손실 곡선을 읽고 해석하는 방법을 탐구하고, 다양한 곡선 모양이 모델의 동작에 대해 무엇을 알려주는지 이해하며, 일반적인 훈련 문제를 해결하는 방법을 배웁니다. -## What are Learning Curves?[[what-are-learning-curves]] +## 학습 곡선이란 무엇인가요?[[what-are-learning-curves]] -Learning curves are visual representations of your model's performance metrics over time during training. The two most important curves to monitor are: +학습 곡선은 훈련 중에 시간에 따른 모델의 성능 메트릭을 시각적으로 나타낸 것입니다. 모니터링해야 할 가장 중요한 두 곡선은 다음과 같습니다: -- **Loss curves**: Show how the model's error (loss) changes over training steps or epochs -- **Accuracy curves**: Show the percentage of correct predictions over training steps or epochs +- **손실 곡선**: 훈련 단계나 에폭에 따라 모델의 오류(손실)가 어떻게 변하는지 보여줍니다 +- **정확도 곡선**: 훈련 단계나 에폭에 따른 정확한 예측의 백분율을 보여줍니다 -These curves help us understand whether our model is learning effectively and can guide us in making adjustments to improve performance. In Transformers, these metrics are individually computed for each batch and then logged to the disk. We can then use libraries like [Weights & Biases](https://wandb.ai/) to visualize these curves and track our model's performance over time. +이러한 곡선은 모델이 효과적으로 학습하고 있는지 이해하는 데 도움이 되며, 성능을 향상시키기 위한 조정을 가이드할 수 있습니다. Transformers에서는 이러한 메트릭이 각 배치에 대해 개별적으로 계산된 다음 디스크에 기록됩니다. 그런 다음 [Weights & Biases](https://wandb.ai/)와 같은 라이브러리를 사용하여 이러한 곡선을 시각화하고 시간에 따른 모델의 성능을 추적할 수 있습니다. -### Loss Curves[[loss-curves]] +### 손실 곡선[[loss-curves]] -The loss curve shows how the model's error decreases over time. In a typical successful training run, you'll see a curve similar to the one below: +손실 곡선은 시간에 따라 모델의 오류가 어떻게 감소하는지 보여줍니다. 일반적으로 성공적인 훈련 실행에서는 아래와 같은 곡선을 볼 수 있습니다: ![Loss Curve](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/1.png) -- **High initial loss**: The model starts without optimization, so predictions are initially poor -- **Decreasing loss**: As training progresses, the loss should generally decrease -- **Convergence**: Eventually, the loss stabilizes at a low value, indicating that the model has learned the patterns in the data +- **높은 초기 손실**: 모델이 최적화 없이 시작하므로 초기 예측이 좋지 않습니다 +- **감소하는 손실**: 훈련이 진행됨에 따라 손실이 일반적으로 감소해야 합니다 +- **수렴**: 결국 손실이 낮은 값에서 안정화되어 모델이 데이터의 패턴을 학습했음을 나타냅니다 -As in previous chapters, we can use the `Trainer` API to track these metrics and visualize them in a dashboard. Below is an example of how to do this with Weights & Biases. +이전 챕터에서와 같이 `Trainer` API를 사용하여 이러한 메트릭을 추적하고 대시보드에서 시각화할 수 있습니다. 다음은 Weights & Biases로 이를 수행하는 예시입니다. ```python -# Example of tracking loss during training with the Trainer +# Trainer로 훈련 중 손실을 추적하는 예시 from transformers import Trainer, TrainingArguments import wandb -# Initialize Weights & Biases for experiment tracking +# 실험 추적을 위해 Weights & Biases 초기화 wandb.init(project="transformer-fine-tuning", name="bert-mrpc-analysis") training_args = TrainingArguments( @@ -45,11 +45,11 @@ training_args = TrainingArguments( eval_strategy="steps", eval_steps=50, save_steps=100, - logging_steps=10, # Log metrics every 10 steps + logging_steps=10, # 10단계마다 메트릭 로그 num_train_epochs=3, per_device_train_batch_size=16, per_device_eval_batch_size=16, - report_to="wandb", # Send logs to Weights & Biases + report_to="wandb", # Weights & Biases로 로그 전송 ) trainer = Trainer( @@ -62,118 +62,118 @@ trainer = Trainer( compute_metrics=compute_metrics, ) -# Train and automatically log metrics +# 훈련 및 자동 메트릭 로그 trainer.train() ``` -### Accuracy Curves[[accuracy-curves]] +### 정확도 곡선[[accuracy-curves]] -The accuracy curve shows the percentage of correct predictions over time. Unlike loss curves, accuracy curves should generally increase as the model learns and can typically include more steps than the loss curve. +정확도 곡선은 시간에 따른 정확한 예측의 백분율을 보여줍니다. 손실 곡선과 달리 정확도 곡선은 모델이 학습함에 따라 일반적으로 증가해야 하며, 손실 곡선보다 더 많은 단계를 포함할 수 있습니다. ![Accuracy Curve](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/2.png) -- **Start low**: Initial accuracy should be low, as the model has not yet learned the patterns in the data -- **Increase with training**: Accuracy should generally improve as the model learns if it is able to learn the patterns in the data -- **May show plateaus**: Accuracy often increases in discrete jumps rather than smoothly, as the model makes predictions that are close to the true labels +- **낮게 시작**: 모델이 아직 데이터의 패턴을 학습하지 않았으므로 초기 정확도는 낮아야 합니다 +- **훈련과 함께 증가**: 모델이 데이터의 패턴을 학습할 수 있다면 학습함에 따라 정확도가 일반적으로 향상되어야 합니다 +- **고원 현상을 보일 수 있음**: 모델이 실제 레이블에 가까운 예측을 하므로 정확도는 부드럽게 증가하기보다는 이산적인 점프로 증가하는 경우가 많습니다 -💡 **Why Accuracy Curves Are "Steppy"**: Unlike loss, which is continuous, accuracy is calculated by comparing discrete predictions to true labels. Small improvements in model confidence might not change the final prediction, causing accuracy to remain flat until a threshold is crossed. +💡 **정확도 곡선이 "계단식"인 이유**: 연속적인 손실과 달리 정확도는 이산적인 예측을 실제 레이블과 비교하여 계산됩니다. 모델 신뢰도의 작은 개선은 최종 예측을 변경하지 않을 수 있어서 임계값을 넘을 때까지 정확도가 평평하게 유지됩니다. -### Convergence[[convergence]] +### 수렴[[convergence]] -Convergence occurs when the model's performance stabilizes and the loss and accuracy curves level off. This is a sign that the model has learned the patterns in the data and is ready to be used. In simple terms, we are aiming for the model to converge to a stable performance every time we train it. +수렴은 모델의 성능이 안정화되고 손실 및 정확도 곡선이 평평해질 때 발생합니다. 이는 모델이 데이터의 패턴을 학습했으며 사용할 준비가 되었다는 신호입니다. 간단히 말해서, 우리는 모델을 훈련할 때마다 안정적인 성능으로 수렴하는 것을 목표로 합니다. ![Convergence](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/4.png) -Once models have converged, we can use them to make predictions on new data and refer to evaluation metrics to understand how well the model is performing. +모델이 수렴하면 새로운 데이터에 대한 예측을 만들고 평가 메트릭을 참조하여 모델의 성능을 이해할 수 있습니다. -## Interpreting Learning Curve Patterns[[interpreting-learning-curve-patterns]] +## 학습 곡선 패턴 해석하기[[interpreting-learning-curve-patterns]] -Different curve shapes reveal different aspects of your model's training. Let's examine the most common patterns and what they mean. +다양한 곡선 모양은 모델 훈련의 다양한 측면을 드러냅니다. 가장 일반적인 패턴과 그 의미를 살펴보겠습니다. -### Healthy Learning Curves[[healthy-learning-curves]] +### 건전한 학습 곡선[[healthy-learning-curves]] -A well-behaved training run typically shows curve shapes similar to the one below: +잘 작동하는 훈련 실행은 일반적으로 아래와 같은 곡선 모양을 보여줍니다: ![Healthy Loss Curve](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/5.png) -Let's look at the illustration above. It displays both the loss curve (on the left) and the corresponding accuracy curve (on the right). These curves have distinct characteristics. +위의 그림을 살펴보겠습니다. 손실 곡선(왼쪽)과 해당 정확도 곡선(오른쪽)을 모두 표시합니다. 이러한 곡선은 뚜렷한 특성을 가지고 있습니다. -The loss curve shows the value of the model's loss over time. Initially, the loss is high and then it gradually decreases, indicating that the model is improving. A decrease in the loss value suggests that the model is making better predictions, as the loss represents the error between the predicted output and the true output. +손실 곡선은 시간에 따른 모델 손실의 값을 보여줍니다. 처음에는 손실이 높다가 점차 감소하여 모델이 개선되고 있음을 나타냅니다. 손실 값의 감소는 손실이 예측된 출력과 실제 출력 간의 오류를 나타내므로 모델이 더 나은 예측을 하고 있음을 시사합니다. -Now let's shift our focus to the accuracy curve. It represents the model's accuracy over time. The accuracy curve begins at a low value and increases as training progresses. Accuracy measures the proportion of correctly classified instances. So, as the accuracy curve rises, it signifies that the model is making more correct predictions. +이제 정확도 곡선에 초점을 맞춰보겠습니다. 이는 시간에 따른 모델의 정확도를 나타냅니다. 정확도 곡선은 낮은 값에서 시작하여 훈련이 진행됨에 따라 증가합니다. 정확도는 올바르게 분류된 인스턴스의 비율을 측정합니다. 따라서 정확도 곡선이 상승함에 따라 모델이 더 정확한 예측을 하고 있음을 의미합니다. -One notable difference between the curves is the smoothness and the presence of "plateaus" on the accuracy curve. While the loss decreases smoothly, the plateaus on the accuracy curve indicate discrete jumps in accuracy instead of a continuous increase. This behavior is attributed to how accuracy is measured. The loss can improve if the model's output gets closer to the target, even if the final prediction is still incorrect. Accuracy, however, only improves when the prediction crosses the threshold to be correct. +곡선 간의 주목할 만한 차이점 중 하나는 정확도 곡선의 부드러움과 "고원"의 존재입니다. 손실이 부드럽게 감소하는 동안 정확도 곡선의 고원은 연속적인 증가 대신 정확도의 이산적인 점프를 나타냅니다. 이 동작은 정확도가 측정되는 방식에 기인합니다. 최종 예측이 여전히 틀렸더라도 모델의 출력이 목표에 가까워지면 손실이 개선될 수 있습니다. 그러나 정확도는 예측이 정확한 임계값을 넘어야만 향상됩니다. -For example, in a binary classifier distinguishing cats (0) from dogs (1), if the model predicts 0.3 for an image of a dog (true value 1), this is rounded to 0 and is an incorrect classification. If in the next step it predicts 0.4, it's still incorrect. The loss will have decreased because 0.4 is closer to 1 than 0.3, but the accuracy remains unchanged, creating a plateau. The accuracy will only jump up when the model predicts a value greater than 0.5 that gets rounded to 1. +예를 들어, 고양이(0)와 개(1)를 구별하는 이진 분류기에서 모델이 개 이미지(실제 값 1)에 대해 0.3을 예측하면 이는 0으로 반올림되어 잘못된 분류입니다. 다음 단계에서 0.4를 예측하면 여전히 틀렸습니다. 0.4가 0.3보다 1에 더 가깝기 때문에 손실은 감소했지만 정확도는 변하지 않아 고원을 만듭니다. 정확도는 모델이 0.5보다 큰 값을 예측하여 1로 반올림될 때만 점프합니다. -**Characteristics of healthy curves:** -- **Smooth decline in loss**: Both training and validation loss decrease steadily -- **Close training/validation performance**: Small gap between training and validation metrics -- **Convergence**: Curves level off, indicating the model has learned the patterns +**건전한 곡선의 특성:** +- **손실의 부드러운 감소**: 훈련 및 검증 손실이 모두 꾸준히 감소 +- **훈련/검증 성능이 근접**: 훈련 및 검증 메트릭 간의 작은 격차 +- **수렴**: 곡선이 평평해져서 모델이 패턴을 학습했음을 나타냄 -### Practical Examples[[practical-examples]] +### 실용적인 예시[[practical-examples]] -Let's work through some practical examples of learning curves. First, we will highlight some approaches to monitor the learning curves during training. Below, we will break down the different patterns that can be observed in the learning curves. +학습 곡선의 몇 가지 실용적인 예시를 살펴보겠습니다. 먼저 훈련 중 학습 곡선을 모니터링하는 몇 가지 접근 방식을 강조하겠습니다. 아래에서는 학습 곡선에서 관찰할 수 있는 다양한 패턴을 분해하겠습니다. -#### During Training[[during-training]] +#### 훈련 중[[during-training]] -During the training process (after you've hit `trainer.train()`), you can monitor these key indicators: +훈련 과정 중(`trainer.train()`을 실행한 후) 다음과 같은 주요 지표를 모니터링할 수 있습니다: -1. **Loss convergence**: Is the loss still decreasing or has it plateaued? -2. **Overfitting signs**: Is validation loss starting to increase while training loss decreases? -3. **Learning rate**: Are the curves too erratic (LR too high) or too flat (LR too low)? -4. **Stability**: Are there sudden spikes or drops that indicate problems? +1. **손실 수렴**: 손실이 여전히 감소하고 있는가, 아니면 고원에 도달했는가? +2. **과적합 신호**: 훈련 손실은 감소하는 동안 검증 손실이 증가하기 시작하는가? +3. **학습률**: 곡선이 너무 불안정한가(LR이 너무 높음) 아니면 너무 평평한가(LR이 너무 낮음)? +4. **안정성**: 문제를 나타내는 급격한 스파이크나 드롭이 있는가? -#### After Training[[after-training]] +#### 훈련 후[[after-training]] -After the training process is complete, you can analyze the complete curves to understand the model's performance. +훈련 과정이 완료된 후 전체 곡선을 분석하여 모델의 성능을 이해할 수 있습니다. -1. **Final performance**: Did the model reach acceptable performance levels? -2. **Efficiency**: Could the same performance be achieved with fewer epochs? -3. **Generalization**: How close are training and validation performance? -4. **Trends**: Would additional training likely improve performance? +1. **최종 성능**: 모델이 허용 가능한 성능 수준에 도달했는가? +2. **효율성**: 더 적은 에폭으로 동일한 성능을 달성할 수 있었는가? +3. **일반화**: 훈련과 검증 성능이 얼마나 가까운가? +4. **경향**: 추가 훈련이 성능을 향상시킬 가능성이 있는가? -🔍 **W&B Dashboard Features**: Weights & Biases automatically creates beautiful, interactive plots of your learning curves. You can: -- Compare multiple runs side by side -- Add custom metrics and visualizations -- Set up alerts for anomalous behavior -- Share results with your team +🔍 **W&B 대시보드 기능**: Weights & Biases는 학습 곡선의 아름답고 대화형 플롯을 자동으로 생성합니다. 다음을 할 수 있습니다: +- 여러 실행을 나란히 비교 +- 사용자 정의 메트릭 및 시각화 추가 +- 이상 동작에 대한 알림 설정 +- 팀과 결과 공유 -Learn more in the [Weights & Biases documentation](https://docs.wandb.ai/). +[Weights & Biases 문서](https://docs.wandb.ai/)에서 자세히 알아보세요. -#### Overfitting[[overfitting]] +#### 과적합[[overfitting]] -Overfitting occurs when the model learns too much from the training data and is unable to generalize to different data (represented by the validation set). +과적합은 모델이 훈련 데이터에서 너무 많이 학습하여 다른 데이터(검증 세트로 표현됨)로 일반화할 수 없을 때 발생합니다. ![Overfitting](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/10.png) -**Symptoms:** +**증상:** -- Training loss continues to decrease while validation loss increases or plateaus -- Large gap between training and validation accuracy -- Training accuracy much higher than validation accuracy +- 훈련 손실은 계속 감소하지만 검증 손실은 증가하거나 고원에 머무름 +- 훈련과 검증 정확도 간의 큰 격차 +- 훈련 정확도가 검증 정확도보다 훨씬 높음 -**Solutions for overfitting:** -- **Regularization**: Add dropout, weight decay, or other regularization techniques -- **Early stopping**: Stop training when validation performance stops improving -- **Data augmentation**: Increase training data diversity -- **Reduce model complexity**: Use a smaller model or fewer parameters +**과적합 해결책:** +- **정규화**: 드롭아웃, 가중치 감쇠 또는 기타 정규화 기법 추가 +- **조기 중단**: 검증 성능이 개선을 멈출 때 훈련 중단 +- **데이터 증강**: 훈련 데이터 다양성 증가 +- **모델 복잡도 감소**: 더 작은 모델이나 더 적은 매개변수 사용 -In the sample below, we use early stopping to prevent overfitting. We set the `early_stopping_patience` to 3, which means that if the validation loss does not improve for 3 consecutive epochs, the training will be stopped. +아래 샘플에서는 과적합을 방지하기 위해 조기 중단을 사용합니다. `early_stopping_patience`를 3으로 설정하여 검증 손실이 3번의 연속적인 에폭 동안 개선되지 않으면 훈련이 중단됩니다. ```python -# Example of detecting overfitting with early stopping +# 조기 중단으로 과적합을 감지하는 예시 from transformers import EarlyStoppingCallback training_args = TrainingArguments( @@ -185,10 +185,10 @@ training_args = TrainingArguments( load_best_model_at_end=True, metric_for_best_model="eval_loss", greater_is_better=False, - num_train_epochs=10, # Set high, but we'll stop early + num_train_epochs=10, # 높게 설정하지만 조기에 중단할 예정 ) -# Add early stopping to prevent overfitting +# 과적합을 방지하기 위해 조기 중단 추가 trainer = Trainer( model=model, args=training_args, @@ -201,29 +201,29 @@ trainer = Trainer( ) ``` -#### 2. Underfitting[[underfitting]] +#### 2. 부적합[[underfitting]] -Underfitting occurs when the model is too simple to capture the underlying patterns in the data. This can happen for several reasons: +부적합은 모델이 데이터의 기본 패턴을 포착하기에는 너무 단순할 때 발생합니다. 이는 여러 가지 이유로 발생할 수 있습니다: -- The model is too small or lacks capacity to learn the patterns -- The learning rate is too low, causing slow learning -- The dataset is too small or not representative of the problem -- The model is not properly regularized +- 모델이 너무 작거나 패턴을 학습할 용량이 부족함 +- 학습률이 너무 낮아서 학습이 느림 +- 데이터 세트가 너무 작거나 문제를 대표하지 못함 +- 모델이 제대로 정규화되지 않음 ![Underfitting](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/7.png) -**Symptoms:** -- Both training and validation loss remain high -- Model performance plateaus early in training -- Training accuracy is lower than expected +**증상:** +- 훈련 및 검증 손실이 모두 높게 유지됨 +- 모델 성능이 훈련 초기에 고원에 도달 +- 훈련 정확도가 예상보다 낮음 -**Solutions for underfitting:** -- **Increase model capacity**: Use a larger model or more parameters -- **Train longer**: Increase the number of epochs -- **Adjust learning rate**: Try different learning rates -- **Check data quality**: Ensure your data is properly preprocessed +**부적합 해결책:** +- **모델 용량 증가**: 더 큰 모델이나 더 많은 매개변수 사용 +- **더 오래 훈련**: 에폭 수 증가 +- **학습률 조정**: 다른 학습률 시도 +- **데이터 품질 확인**: 데이터가 적절히 전처리되었는지 확인 -In the sample below, we train for more epochs to see if the model can learn the patterns in the data. +아래 샘플에서는 모델이 데이터의 패턴을 학습할 수 있는지 확인하기 위해 더 많은 에폭 동안 훈련합니다. ```python from transformers import TrainingArguments @@ -235,33 +235,33 @@ training_args = TrainingArguments( ) ``` -#### 3. Erratic Learning Curves[[erratic-learning-curves]] +#### 3. 불안정한 학습 곡선[[erratic-learning-curves]] -Erratic learning curves occur when the model is not learning effectively. This can happen for several reasons: +불안정한 학습 곡선은 모델이 효과적으로 학습하지 않을 때 발생합니다. 이는 여러 가지 이유로 발생할 수 있습니다: -- The learning rate is too high, causing the model to overshoot the optimal parameters -- The batch size is too small, causing the model to learn slowly -- The model is not properly regularized, causing it to overfit to the training data -- The dataset is not properly preprocessed, causing the model to learn from noise +- 학습률이 너무 높아서 모델이 최적 매개변수를 오버슛함 +- 배치 크기가 너무 작아서 모델이 천천히 학습함 +- 모델이 제대로 정규화되지 않아서 훈련 데이터에 과적합됨 +- 데이터 세트가 제대로 전처리되지 않아서 모델이 노이즈에서 학습함 ![Erratic Learning Curves](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/3.png) -**Symptoms:** -- Frequent fluctuations in loss or accuracy -- Curves show high variance or instability -- Performance oscillates without clear trend +**증상:** +- 손실이나 정확도에서 빈번한 변동 +- 곡선이 높은 분산이나 불안정성을 보임 +- 성능이 명확한 경향 없이 진동함 -Both training and validation curves show erratic behavior. +훈련과 검증 곡선 모두 불안정한 동작을 보입니다. ![Erratic Learning Curves](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/9.png) -**Solutions for erratic curves:** -- **Lower learning rate**: Reduce step size for more stable training -- **Increase batch size**: Larger batches provide more stable gradients -- **Gradient clipping**: Prevent exploding gradients -- **Better data preprocessing**: Ensure consistent data quality +**불안정한 곡선의 해결책:** +- **학습률 낮추기**: 더 안정적인 훈련을 위해 단계 크기 줄이기 +- **배치 크기 증가**: 더 큰 배치가 더 안정적인 그레이디언트 제공 +- **그레이디언트 클리핑**: 그레이디언트 폭발 방지 +- **더 나은 데이터 전처리**: 일관된 데이터 품질 보장 -In the sample below, we lower the learning rate and increase the batch size. +아래 샘플에서는 학습률을 낮추고 배치 크기를 증가시킵니다. ```python from transformers import TrainingArguments @@ -275,145 +275,144 @@ training_args = TrainingArguments( ) ``` -## Key Takeaways[[key-takeaways]] +## 핵심 요점[[key-takeaways]] -Understanding learning curves is crucial for becoming an effective machine learning practitioner. These visual tools provide immediate feedback about your model's training progress and help you make informed decisions about when to stop training, adjust hyperparameters, or try different approaches. With practice, you'll develop an intuitive understanding of what healthy learning curves look like and how to address issues when they arise. +학습 곡선을 이해하는 것은 효과적인 기계학습 실무자가 되기 위해 중요합니다. 이러한 시각적 도구는 모델의 훈련 진행 상황에 대한 즉각적인 피드백을 제공하고 언제 훈련을 중단하거나 하이퍼파라미터를 조정하거나 다른 접근 방식을 시도할지에 대한 정보에 기반한 결정을 내리는 데 도움이 됩니다. 연습을 통해 건전한 학습 곡선이 어떤 모습인지, 그리고 문제가 발생했을 때 어떻게 해결할지에 대한 직관적인 이해를 개발할 수 있습니다. -💡 **Key Takeaways:** -- Learning curves are essential tools for understanding model training progress -- Monitor both loss and accuracy curves, but remember they have different characteristics -- Overfitting shows as diverging training/validation performance -- Underfitting shows as poor performance on both training and validation data -- Tools like Weights & Biases make it easy to track and analyze learning curves -- Early stopping and proper regularization can address most common training issues +💡 **핵심 요점:** +- 학습 곡선은 모델 훈련 진행 상황을 이해하는 데 필수적인 도구입니다 +- 손실과 정확도 곡선을 모두 모니터링하되, 서로 다른 특성을 가지고 있음을 기억하세요 +- 과적합은 훈련/검증 성능의 분기로 나타납니다 +- 부적합은 훈련과 검증 데이터 모두에서 성능이 좋지 않은 것으로 나타납니다 +- Weights & Biases와 같은 도구는 학습 곡선을 쉽게 추적하고 분석할 수 있게 해줍니다 +- 조기 중단과 적절한 정규화는 대부분의 일반적인 훈련 문제를 해결할 수 있습니다 -🔬 **Next Steps**: Practice analyzing learning curves on your own fine-tuning experiments. Try different hyperparameters and observe how they affect the curve shapes. This hands-on experience is the best way to develop intuition for reading training progress. +🔬 **다음 단계**: 자신의 미세 조정 실험에서 학습 곡선을 분석해보세요. 다양한 하이퍼파라미터를 시도하고 곡선 모양에 어떤 영향을 미치는지 관찰하세요. 이러한 실습 경험이 훈련 진행 상황을 읽는 직관을 개발하는 가장 좋은 방법입니다. -## Section Quiz[[section-quiz]] +## 섹션 퀴즈[[section-quiz]] -Test your understanding of learning curves and training analysis: +학습 곡선과 훈련 분석에 대한 이해를 테스트해보세요: -### 1. What does it typically mean when training loss decreases but validation loss starts increasing? +### 1. 훈련 손실은 감소하지만 검증 손실이 증가하기 시작할 때 일반적으로 무엇을 의미하나요? -### 2. Why do accuracy curves often show a "steppy" or plateau-like pattern rather than smooth increases? +### 2. 정확도 곡선이 부드러운 증가보다는 "계단식" 또는 고원과 같은 패턴을 보이는 이유는 무엇인가요? -### 3. What is the best approach when you observe erratic, highly fluctuating learning curves? +### 3. 불안정하고 심하게 변동하는 학습 곡선을 관찰할 때 가장 좋은 접근법은 무엇인가요? -### 4. When should you consider using early stopping? +### 4. 언제 조기 중단 사용을 고려해야 하나요? -### 5. What indicates that your model might be underfitting? +### 5. 모델이 부적합일 수 있음을 나타내는 것은 무엇인가요? - +/> \ No newline at end of file From 2120da288609fd7b63bbc54413d5c9d4fed2a5f6 Mon Sep 17 00:00:00 2001 From: chaewonsong Date: Sun, 3 Aug 2025 22:00:17 +0900 Subject: [PATCH 30/43] fix: manual edits --- chapters/ko/chapter3/5.mdx | 52 +++++++++++++++++++------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/chapters/ko/chapter3/5.mdx b/chapters/ko/chapter3/5.mdx index 8d71f5308..11ba65e5d 100644 --- a/chapters/ko/chapter3/5.mdx +++ b/chapters/ko/chapter3/5.mdx @@ -7,28 +7,28 @@ {label: "Aws Studio", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/master/course/en/chapter3/section7.ipynb"}, ]} /> -이제 `Trainer` API와 사용자 정의 훈련 루프를 모두 사용하여 미세 조정을 구현하는 방법을 배웠으므로, 결과를 해석하는 방법을 이해하는 것이 중요합니다. 학습 곡선은 훈련 중 모델의 성능을 평가하고 성능을 저하시키기 전에 잠재적인 문제를 식별하는 데 도움이 되는 매우 유용한 도구입니다. +이제 `Trainer` API와 사용자 정의 훈련 루프를 모두 사용하여 미세 조정을 구현하는 방법을 배웠으므로, 결과를 해석하는 방법을 이해하는 것이 중요합니다. 학습 곡선은 훈련 중 모델의 성능을 평가하고 성능 저하를 일으킬 수 있는 잠재적 문제를 미리 식별하는 데 도움이 되는 매우 유용한 도구입니다. 이 섹션에서는 정확도와 손실 곡선을 읽고 해석하는 방법을 탐구하고, 다양한 곡선 모양이 모델의 동작에 대해 무엇을 알려주는지 이해하며, 일반적인 훈련 문제를 해결하는 방법을 배웁니다. ## 학습 곡선이란 무엇인가요?[[what-are-learning-curves]] -학습 곡선은 훈련 중에 시간에 따른 모델의 성능 메트릭을 시각적으로 나타낸 것입니다. 모니터링해야 할 가장 중요한 두 곡선은 다음과 같습니다: +학습 곡선은 훈련 중에 시간에 따른 모델의 성능 메트릭을 시각적으로 나타낸 것입니다. 모니터링해야 할 가장 중요한 두 곡선은 다음과 같습니다. -- **손실 곡선**: 훈련 단계나 에폭에 따라 모델의 오류(손실)가 어떻게 변하는지 보여줍니다 -- **정확도 곡선**: 훈련 단계나 에폭에 따른 정확한 예측의 백분율을 보여줍니다 +- **손실 곡선**: 훈련 단계나 에폭에 따라 모델의 오류(손실)가 어떻게 변하는지 보여줍니다. +- **정확도 곡선**: 훈련 단계나 에폭에 따른 정확한 예측의 백분율을 보여줍니다. -이러한 곡선은 모델이 효과적으로 학습하고 있는지 이해하는 데 도움이 되며, 성능을 향상시키기 위한 조정을 가이드할 수 있습니다. Transformers에서는 이러한 메트릭이 각 배치에 대해 개별적으로 계산된 다음 디스크에 기록됩니다. 그런 다음 [Weights & Biases](https://wandb.ai/)와 같은 라이브러리를 사용하여 이러한 곡선을 시각화하고 시간에 따른 모델의 성능을 추적할 수 있습니다. +이러한 곡선을 통해 모델의 학습 효과를 파악하고, 성능 향상을 위한 조정 방향을 결정할 수 있습니다. Transformers에서는 이러한 메트릭이 각 배치에 대해 개별적으로 계산된 다음 디스크에 기록됩니다. 그런 다음 [Weights & Biases](https://wandb.ai/)와 같은 라이브러리를 사용하여 이러한 곡선을 시각화하고 시간에 따른 모델의 성능을 추적할 수 있습니다. ### 손실 곡선[[loss-curves]] -손실 곡선은 시간에 따라 모델의 오류가 어떻게 감소하는지 보여줍니다. 일반적으로 성공적인 훈련 실행에서는 아래와 같은 곡선을 볼 수 있습니다: +손실 곡선은 시간에 따라 모델의 오류가 어떻게 감소하는지 보여줍니다. 일반적으로 성공적인 훈련 실행에서는 아래와 같은 곡선을 볼 수 있습니다. ![Loss Curve](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/1.png) -- **높은 초기 손실**: 모델이 최적화 없이 시작하므로 초기 예측이 좋지 않습니다 -- **감소하는 손실**: 훈련이 진행됨에 따라 손실이 일반적으로 감소해야 합니다 -- **수렴**: 결국 손실이 낮은 값에서 안정화되어 모델이 데이터의 패턴을 학습했음을 나타냅니다 +- **높은 초기 손실**: 모델이 최적화 없이 시작하므로 초기 예측이 좋지 않습니다. +- **감소하는 손실**: 훈련이 진행됨에 따라 손실이 일반적으로 감소해야 합니다. +- **수렴**: 최종적으로 손실이 낮은 수준에서 안정되면서 모델이 데이터 패턴을 성공적으로 학습했음을 보여줍니다. 이전 챕터에서와 같이 `Trainer` API를 사용하여 이러한 메트릭을 추적하고 대시보드에서 시각화할 수 있습니다. 다음은 Weights & Biases로 이를 수행하는 예시입니다. @@ -72,9 +72,9 @@ trainer.train() ![Accuracy Curve](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/2.png) -- **낮게 시작**: 모델이 아직 데이터의 패턴을 학습하지 않았으므로 초기 정확도는 낮아야 합니다 -- **훈련과 함께 증가**: 모델이 데이터의 패턴을 학습할 수 있다면 학습함에 따라 정확도가 일반적으로 향상되어야 합니다 -- **고원 현상을 보일 수 있음**: 모델이 실제 레이블에 가까운 예측을 하므로 정확도는 부드럽게 증가하기보다는 이산적인 점프로 증가하는 경우가 많습니다 +- **낮게 시작**: 모델이 아직 데이터의 패턴을 학습하지 않았으므로 초기 정확도는 낮아야 합니다. +- **훈련과 함께 증가**: 모델이 데이터의 패턴을 학습할 수 있다면 학습함에 따라 정확도가 일반적으로 향상되어야 합니다. +- **고원 현상을 보일 수 있음**: 모델이 실제 레이블에 가까운 예측을 만들어내므로, 정확도는 부드럽게 상승하기보다는 계단식으로 점프하는 경우가 많습니다. @@ -96,7 +96,7 @@ trainer.train() ### 건전한 학습 곡선[[healthy-learning-curves]] -잘 작동하는 훈련 실행은 일반적으로 아래와 같은 곡선 모양을 보여줍니다: +잘 작동하는 훈련 실행은 일반적으로 아래와 같은 곡선 모양을 보여줍니다. ![Healthy Loss Curve](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/5.png) @@ -106,7 +106,7 @@ trainer.train() 이제 정확도 곡선에 초점을 맞춰보겠습니다. 이는 시간에 따른 모델의 정확도를 나타냅니다. 정확도 곡선은 낮은 값에서 시작하여 훈련이 진행됨에 따라 증가합니다. 정확도는 올바르게 분류된 인스턴스의 비율을 측정합니다. 따라서 정확도 곡선이 상승함에 따라 모델이 더 정확한 예측을 하고 있음을 의미합니다. -곡선 간의 주목할 만한 차이점 중 하나는 정확도 곡선의 부드러움과 "고원"의 존재입니다. 손실이 부드럽게 감소하는 동안 정확도 곡선의 고원은 연속적인 증가 대신 정확도의 이산적인 점프를 나타냅니다. 이 동작은 정확도가 측정되는 방식에 기인합니다. 최종 예측이 여전히 틀렸더라도 모델의 출력이 목표에 가까워지면 손실이 개선될 수 있습니다. 그러나 정확도는 예측이 정확한 임계값을 넘어야만 향상됩니다. +곡선 간의 주목할 만한 차이점 중 하나는 정확도 곡선의 부드러움과 "고원"의 존재입니다. 손실이 부드럽게 감소하는 동안 정확도 곡선의 고원은 연속적인 증가 대신 정확도의 이산적인 점프를 나타냅니다. 이러한 현상은 정확도 측정 방식의 특성 때문입니다. 최종 예측이 여전히 틀렸더라도 모델의 출력이 목표에 가까워지면 손실이 개선될 수 있습니다. 그러나 정확도는 예측이 정확한 임계값을 넘어야만 향상됩니다. 예를 들어, 고양이(0)와 개(1)를 구별하는 이진 분류기에서 모델이 개 이미지(실제 값 1)에 대해 0.3을 예측하면 이는 0으로 반올림되어 잘못된 분류입니다. 다음 단계에서 0.4를 예측하면 여전히 틀렸습니다. 0.4가 0.3보다 1에 더 가깝기 때문에 손실은 감소했지만 정확도는 변하지 않아 고원을 만듭니다. 정확도는 모델이 0.5보다 큰 값을 예측하여 1로 반올림될 때만 점프합니다. @@ -125,7 +125,7 @@ trainer.train() #### 훈련 중[[during-training]] -훈련 과정 중(`trainer.train()`을 실행한 후) 다음과 같은 주요 지표를 모니터링할 수 있습니다: +훈련 과정 중(`trainer.train()`을 실행한 후) 다음과 같은 주요 지표를 모니터링할 수 있습니다. 1. **손실 수렴**: 손실이 여전히 감소하고 있는가, 아니면 고원에 도달했는가? 2. **과적합 신호**: 훈련 손실은 감소하는 동안 검증 손실이 증가하기 시작하는가? @@ -143,7 +143,7 @@ trainer.train() -🔍 **W&B 대시보드 기능**: Weights & Biases는 학습 곡선의 아름답고 대화형 플롯을 자동으로 생성합니다. 다음을 할 수 있습니다: +🔍 **W&B 대시보드 기능**: Weights & Biases는 학습 곡선의 아름답고 대화형 플롯을 자동으로 생성합니다. 다음을 할 수 있습니다. - 여러 실행을 나란히 비교 - 사용자 정의 메트릭 및 시각화 추가 - 이상 동작에 대한 알림 설정 @@ -203,7 +203,7 @@ trainer = Trainer( #### 2. 부적합[[underfitting]] -부적합은 모델이 데이터의 기본 패턴을 포착하기에는 너무 단순할 때 발생합니다. 이는 여러 가지 이유로 발생할 수 있습니다: +부적합은 모델이 데이터의 기본 패턴을 포착하기에는 너무 단순할 때 발생합니다. 이는 여러 가지 이유로 발생할 수 있습니다. - 모델이 너무 작거나 패턴을 학습할 용량이 부족함 - 학습률이 너무 낮아서 학습이 느림 @@ -255,7 +255,7 @@ training_args = TrainingArguments( ![Erratic Learning Curves](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/9.png) -**불안정한 곡선의 해결책:** +**불안정한 곡선의 해결책** - **학습률 낮추기**: 더 안정적인 훈련을 위해 단계 크기 줄이기 - **배치 크기 증가**: 더 큰 배치가 더 안정적인 그레이디언트 제공 - **그레이디언트 클리핑**: 그레이디언트 폭발 방지 @@ -281,13 +281,13 @@ training_args = TrainingArguments( -💡 **핵심 요점:** -- 학습 곡선은 모델 훈련 진행 상황을 이해하는 데 필수적인 도구입니다 -- 손실과 정확도 곡선을 모두 모니터링하되, 서로 다른 특성을 가지고 있음을 기억하세요 -- 과적합은 훈련/검증 성능의 분기로 나타납니다 -- 부적합은 훈련과 검증 데이터 모두에서 성능이 좋지 않은 것으로 나타납니다 -- Weights & Biases와 같은 도구는 학습 곡선을 쉽게 추적하고 분석할 수 있게 해줍니다 -- 조기 중단과 적절한 정규화는 대부분의 일반적인 훈련 문제를 해결할 수 있습니다 +💡 **핵심 요점** +- 학습 곡선은 모델 훈련 진행 상황을 이해하는 데 필수적인 도구입니다. +- 손실과 정확도 곡선을 모두 모니터링하되, 서로 다른 특성을 가지고 있음을 기억하세요. +- 과적합은 훈련/검증 성능의 분기로 나타납니다. +- 부적합은 훈련과 검증 데이터 모두에서 성능이 좋지 않은 것으로 나타납니다. +- Weights & Biases와 같은 도구는 학습 곡선을 쉽게 추적하고 분석할 수 있게 해줍니다. +- 조기 중단과 적절한 정규화는 대부분의 일반적인 훈련 문제를 해결할 수 있습니다. 🔬 **다음 단계**: 자신의 미세 조정 실험에서 학습 곡선을 분석해보세요. 다양한 하이퍼파라미터를 시도하고 곡선 모양에 어떤 영향을 미치는지 관찰하세요. 이러한 실습 경험이 훈련 진행 상황을 읽는 직관을 개발하는 가장 좋은 방법입니다. @@ -295,7 +295,7 @@ training_args = TrainingArguments( ## 섹션 퀴즈[[section-quiz]] -학습 곡선과 훈련 분석에 대한 이해를 테스트해보세요: +학습 곡선과 훈련 분석에 대한 이해를 테스트해보세요. ### 1. 훈련 손실은 감소하지만 검증 손실이 증가하기 시작할 때 일반적으로 무엇을 의미하나요? From e35c58144cf910c912676c12487c6e6c5e849ad2 Mon Sep 17 00:00:00 2001 From: chaewonsong Date: Sun, 3 Aug 2025 22:13:57 +0900 Subject: [PATCH 31/43] fix: manual edits --- chapters/ko/chapter3/5.mdx | 46 +++++++++++++++++++------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/chapters/ko/chapter3/5.mdx b/chapters/ko/chapter3/5.mdx index 11ba65e5d..aef311ac3 100644 --- a/chapters/ko/chapter3/5.mdx +++ b/chapters/ko/chapter3/5.mdx @@ -9,20 +9,20 @@ 이제 `Trainer` API와 사용자 정의 훈련 루프를 모두 사용하여 미세 조정을 구현하는 방법을 배웠으므로, 결과를 해석하는 방법을 이해하는 것이 중요합니다. 학습 곡선은 훈련 중 모델의 성능을 평가하고 성능 저하를 일으킬 수 있는 잠재적 문제를 미리 식별하는 데 도움이 되는 매우 유용한 도구입니다. -이 섹션에서는 정확도와 손실 곡선을 읽고 해석하는 방법을 탐구하고, 다양한 곡선 모양이 모델의 동작에 대해 무엇을 알려주는지 이해하며, 일반적인 훈련 문제를 해결하는 방법을 배웁니다. +이 섹션에서는 정확도와 손실 곡선을 읽고 해석하는 방법을 탐구하고, 다양한 곡선 패턴이 모델 동작에 대해 무엇을 의미하는지 파악하며, 일반적인 훈련 문제를 해결하는 방법을 배웁니다. ## 학습 곡선이란 무엇인가요?[[what-are-learning-curves]] -학습 곡선은 훈련 중에 시간에 따른 모델의 성능 메트릭을 시각적으로 나타낸 것입니다. 모니터링해야 할 가장 중요한 두 곡선은 다음과 같습니다. +학습 곡선은 훈련 중에 시간에 따른 모델의 성능 지표를 시각적으로 나타낸 것입니다. 모니터링해야 할 가장 중요한 두 곡선은 다음과 같습니다. - **손실 곡선**: 훈련 단계나 에폭에 따라 모델의 오류(손실)가 어떻게 변하는지 보여줍니다. - **정확도 곡선**: 훈련 단계나 에폭에 따른 정확한 예측의 백분율을 보여줍니다. -이러한 곡선을 통해 모델의 학습 효과를 파악하고, 성능 향상을 위한 조정 방향을 결정할 수 있습니다. Transformers에서는 이러한 메트릭이 각 배치에 대해 개별적으로 계산된 다음 디스크에 기록됩니다. 그런 다음 [Weights & Biases](https://wandb.ai/)와 같은 라이브러리를 사용하여 이러한 곡선을 시각화하고 시간에 따른 모델의 성능을 추적할 수 있습니다. +이러한 곡선을 통해 모델의 학습 효과를 파악하고, 성능 향상을 위한 조정 방향을 제시할 수 있습니다. Transformers에서는 이러한 지표가 각 배치에 대해 개별적으로 계산된 다음 디스크에 기록됩니다. 그런 다음 [Weights & Biases](https://wandb.ai/)와 같은 라이브러리를 사용하여 이러한 곡선을 시각화하고 시간에 따른 모델의 성능을 추적할 수 있습니다. ### 손실 곡선[[loss-curves]] -손실 곡선은 시간에 따라 모델의 오류가 어떻게 감소하는지 보여줍니다. 일반적으로 성공적인 훈련 실행에서는 아래와 같은 곡선을 볼 수 있습니다. +손실 곡선은 시간에 따라 모델의 오류가 어떻게 감소하는지 보여줍니다. 성공적인 훈련에서는 보통 다음과 같은 곡선 패턴을 관찰할 수 있습니다. ![Loss Curve](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/1.png) @@ -30,7 +30,7 @@ - **감소하는 손실**: 훈련이 진행됨에 따라 손실이 일반적으로 감소해야 합니다. - **수렴**: 최종적으로 손실이 낮은 수준에서 안정되면서 모델이 데이터 패턴을 성공적으로 학습했음을 보여줍니다. -이전 챕터에서와 같이 `Trainer` API를 사용하여 이러한 메트릭을 추적하고 대시보드에서 시각화할 수 있습니다. 다음은 Weights & Biases로 이를 수행하는 예시입니다. +이전 챕터에서와 같이 `Trainer` API를 사용하여 이러한 지표를 추적하고 대시보드에서 시각화할 수 있습니다. 다음은 Weights & Biases로 이를 수행하는 예시입니다. ```python # Trainer로 훈련 중 손실을 추적하는 예시 @@ -45,7 +45,7 @@ training_args = TrainingArguments( eval_strategy="steps", eval_steps=50, save_steps=100, - logging_steps=10, # 10단계마다 메트릭 로그 + logging_steps=10, # 10단계마다 지표 로그 num_train_epochs=3, per_device_train_batch_size=16, per_device_eval_batch_size=16, @@ -62,7 +62,7 @@ trainer = Trainer( compute_metrics=compute_metrics, ) -# 훈련 및 자동 메트릭 로그 +# 훈련 및 자동 지표 로그 trainer.train() ``` @@ -88,11 +88,11 @@ trainer.train() ![Convergence](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/4.png) -모델이 수렴하면 새로운 데이터에 대한 예측을 만들고 평가 메트릭을 참조하여 모델의 성능을 이해할 수 있습니다. +모델이 수렴하면 새로운 데이터에 대한 예측을 만들고 평가 지표를 참조하여 모델의 성능을 이해할 수 있습니다. ## 학습 곡선 패턴 해석하기[[interpreting-learning-curve-patterns]] -다양한 곡선 모양은 모델 훈련의 다양한 측면을 드러냅니다. 가장 일반적인 패턴과 그 의미를 살펴보겠습니다. +곡선의 다양한 패턴은 모델 훈련의 여러 측면을 보여줍니다. 가장 일반적인 패턴과 그 의미를 살펴보겠습니다. ### 건전한 학습 곡선[[healthy-learning-curves]] @@ -104,7 +104,7 @@ trainer.train() 손실 곡선은 시간에 따른 모델 손실의 값을 보여줍니다. 처음에는 손실이 높다가 점차 감소하여 모델이 개선되고 있음을 나타냅니다. 손실 값의 감소는 손실이 예측된 출력과 실제 출력 간의 오류를 나타내므로 모델이 더 나은 예측을 하고 있음을 시사합니다. -이제 정확도 곡선에 초점을 맞춰보겠습니다. 이는 시간에 따른 모델의 정확도를 나타냅니다. 정확도 곡선은 낮은 값에서 시작하여 훈련이 진행됨에 따라 증가합니다. 정확도는 올바르게 분류된 인스턴스의 비율을 측정합니다. 따라서 정확도 곡선이 상승함에 따라 모델이 더 정확한 예측을 하고 있음을 의미합니다. +다음으로 정확도 곡선을 살펴보겠습니다. 이는 시간에 따른 모델의 정확도를 나타냅니다. 정확도 곡선은 낮은 값에서 시작하여 훈련이 진행됨에 따라 증가합니다. 정확도는 올바르게 분류된 인스턴스의 비율을 측정합니다. 따라서 정확도 곡선이 상승함에 따라 모델이 더 정확한 예측을 하고 있음을 의미합니다. 곡선 간의 주목할 만한 차이점 중 하나는 정확도 곡선의 부드러움과 "고원"의 존재입니다. 손실이 부드럽게 감소하는 동안 정확도 곡선의 고원은 연속적인 증가 대신 정확도의 이산적인 점프를 나타냅니다. 이러한 현상은 정확도 측정 방식의 특성 때문입니다. 최종 예측이 여전히 틀렸더라도 모델의 출력이 목표에 가까워지면 손실이 개선될 수 있습니다. 그러나 정확도는 예측이 정확한 임계값을 넘어야만 향상됩니다. @@ -112,9 +112,9 @@ trainer.train() -**건전한 곡선의 특성:** +**건전한 곡선의 특성** - **손실의 부드러운 감소**: 훈련 및 검증 손실이 모두 꾸준히 감소 -- **훈련/검증 성능이 근접**: 훈련 및 검증 메트릭 간의 작은 격차 +- **훈련/검증 성능이 근접**: 훈련 및 검증 지표 간의 작은 격차 - **수렴**: 곡선이 평평해져서 모델이 패턴을 학습했음을 나타냄 @@ -143,9 +143,9 @@ trainer.train() -🔍 **W&B 대시보드 기능**: Weights & Biases는 학습 곡선의 아름답고 대화형 플롯을 자동으로 생성합니다. 다음을 할 수 있습니다. +🔍 **W&B 대시보드 기능**: Weights & Biases를 사용하면 학습 곡선을 보기 좋고 상호작용 가능한 그래프로 자동으로 만들 수 있습니다. - 여러 실행을 나란히 비교 -- 사용자 정의 메트릭 및 시각화 추가 +- 사용자 정의 지표 및 시각화 추가 - 이상 동작에 대한 알림 설정 - 팀과 결과 공유 @@ -158,13 +158,13 @@ trainer.train() ![Overfitting](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/10.png) -**증상:** +**증상** - 훈련 손실은 계속 감소하지만 검증 손실은 증가하거나 고원에 머무름 - 훈련과 검증 정확도 간의 큰 격차 - 훈련 정확도가 검증 정확도보다 훨씬 높음 -**과적합 해결책:** +**과적합 해결책** - **정규화**: 드롭아웃, 가중치 감쇠 또는 기타 정규화 기법 추가 - **조기 중단**: 검증 성능이 개선을 멈출 때 훈련 중단 - **데이터 증강**: 훈련 데이터 다양성 증가 @@ -212,12 +212,12 @@ trainer = Trainer( ![Underfitting](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/7.png) -**증상:** +**증상** - 훈련 및 검증 손실이 모두 높게 유지됨 - 모델 성능이 훈련 초기에 고원에 도달 - 훈련 정확도가 예상보다 낮음 -**부적합 해결책:** +**부적합 해결책** - **모델 용량 증가**: 더 큰 모델이나 더 많은 매개변수 사용 - **더 오래 훈련**: 에폭 수 증가 - **학습률 조정**: 다른 학습률 시도 @@ -237,7 +237,7 @@ training_args = TrainingArguments( #### 3. 불안정한 학습 곡선[[erratic-learning-curves]] -불안정한 학습 곡선은 모델이 효과적으로 학습하지 않을 때 발생합니다. 이는 여러 가지 이유로 발생할 수 있습니다: +불안정한 학습 곡선은 모델이 효과적으로 학습하지 않을 때 발생합니다. 이는 여러 가지 이유로 발생할 수 있습니다. - 학습률이 너무 높아서 모델이 최적 매개변수를 오버슛함 - 배치 크기가 너무 작아서 모델이 천천히 학습함 @@ -246,7 +246,7 @@ training_args = TrainingArguments( ![Erratic Learning Curves](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/3.png) -**증상:** +**증상** - 손실이나 정확도에서 빈번한 변동 - 곡선이 높은 분산이나 불안정성을 보임 - 성능이 명확한 경향 없이 진동함 @@ -277,7 +277,7 @@ training_args = TrainingArguments( ## 핵심 요점[[key-takeaways]] -학습 곡선을 이해하는 것은 효과적인 기계학습 실무자가 되기 위해 중요합니다. 이러한 시각적 도구는 모델의 훈련 진행 상황에 대한 즉각적인 피드백을 제공하고 언제 훈련을 중단하거나 하이퍼파라미터를 조정하거나 다른 접근 방식을 시도할지에 대한 정보에 기반한 결정을 내리는 데 도움이 됩니다. 연습을 통해 건전한 학습 곡선이 어떤 모습인지, 그리고 문제가 발생했을 때 어떻게 해결할지에 대한 직관적인 이해를 개발할 수 있습니다. +학습 곡선을 이해하는 것은 효과적인 기계학습 전문가가 되기 위해 중요합니다. 이러한 시각적 도구는 모델의 훈련 진행 상황에 대한 즉각적인 피드백을 제공하고 언제 훈련을 중단하거나 하이퍼파라미터를 조정하거나 다른 접근 방식을 시도할지에 대한 정보에 기반한 결정을 내리는 데 도움이 됩니다. 연습을 통해 건전한 학습 곡선이 어떤 모습인지, 그리고 문제가 발생했을 때 어떻게 해결할지에 대한 직관적인 이해를 개발할 수 있습니다. @@ -330,7 +330,7 @@ training_args = TrainingArguments( explain: "계단식 패턴은 정상적이고 예상되는 것이며 오류가 아닙니다." }, { - text: "정확도는 예측이 결정 경계를 넘을 때만 변하는 이산적인 메트릭입니다.", + text: "정확도는 예측이 결정 경계를 넘을 때만 변하는 이산적인 지표입니다.", explain: "정답입니다! 손실과 달리 정확도는 이산적인 예측 결정에 의존하므로 신뢰도의 작은 개선이 임계값을 넘을 때까지 최종 정확도를 변경하지 않을 수 있습니다.", correct: true }, @@ -340,7 +340,7 @@ training_args = TrainingArguments( }, { text: "배치 크기가 너무 작습니다.", - explain: "배치 크기는 훈련 안정성에 영향을 미치지만 정확도 메트릭의 본질적으로 이산적인 특성을 설명하지는 않습니다." + explain: "배치 크기는 훈련 안정성에 영향을 미치지만 정확도 지표의 본질적으로 이산적인 특성을 설명하지는 않습니다." } ]} /> From f8a1e7400a25289abe484c050346dcdbc86c2f5b Mon Sep 17 00:00:00 2001 From: Chaewon Song Date: Sat, 9 Aug 2025 15:17:38 +0900 Subject: [PATCH 32/43] Apply suggestion from @seopp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 임승섭 <100005890+seopp@users.noreply.github.com> --- chapters/ko/chapter3/5.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapters/ko/chapter3/5.mdx b/chapters/ko/chapter3/5.mdx index aef311ac3..89cdefdc7 100644 --- a/chapters/ko/chapter3/5.mdx +++ b/chapters/ko/chapter3/5.mdx @@ -203,7 +203,7 @@ trainer = Trainer( #### 2. 부적합[[underfitting]] -부적합은 모델이 데이터의 기본 패턴을 포착하기에는 너무 단순할 때 발생합니다. 이는 여러 가지 이유로 발생할 수 있습니다. +과소적합은 모델이 데이터의 기본 패턴을 포착하기에는 너무 단순할 때 발생합니다. 이는 여러 가지 이유로 발생할 수 있습니다. - 모델이 너무 작거나 패턴을 학습할 용량이 부족함 - 학습률이 너무 낮아서 학습이 느림 From c8553cd52a1f90cb8dbe109e36522c5874cd587f Mon Sep 17 00:00:00 2001 From: Chaewon Song Date: Sat, 9 Aug 2025 15:17:52 +0900 Subject: [PATCH 33/43] Apply suggestion from @seopp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 임승섭 <100005890+seopp@users.noreply.github.com> --- chapters/ko/chapter3/5.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapters/ko/chapter3/5.mdx b/chapters/ko/chapter3/5.mdx index 89cdefdc7..4b458ac7f 100644 --- a/chapters/ko/chapter3/5.mdx +++ b/chapters/ko/chapter3/5.mdx @@ -201,7 +201,7 @@ trainer = Trainer( ) ``` -#### 2. 부적합[[underfitting]] +#### 2. 과소적합[[underfitting]] 과소적합은 모델이 데이터의 기본 패턴을 포착하기에는 너무 단순할 때 발생합니다. 이는 여러 가지 이유로 발생할 수 있습니다. From b3d6cd2d3270b45e9c02632ce1babdc4a70d1ae3 Mon Sep 17 00:00:00 2001 From: Chaewon Song Date: Sat, 9 Aug 2025 15:17:58 +0900 Subject: [PATCH 34/43] Apply suggestion from @seopp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 임승섭 <100005890+seopp@users.noreply.github.com> --- chapters/ko/chapter3/5.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapters/ko/chapter3/5.mdx b/chapters/ko/chapter3/5.mdx index 4b458ac7f..ec5f01b02 100644 --- a/chapters/ko/chapter3/5.mdx +++ b/chapters/ko/chapter3/5.mdx @@ -239,7 +239,7 @@ training_args = TrainingArguments( 불안정한 학습 곡선은 모델이 효과적으로 학습하지 않을 때 발생합니다. 이는 여러 가지 이유로 발생할 수 있습니다. -- 학습률이 너무 높아서 모델이 최적 매개변수를 오버슛함 +- 학습률이 너무 높아서 모델이 최적 매개변수를 지나치게 됨 - 배치 크기가 너무 작아서 모델이 천천히 학습함 - 모델이 제대로 정규화되지 않아서 훈련 데이터에 과적합됨 - 데이터 세트가 제대로 전처리되지 않아서 모델이 노이즈에서 학습함 From 8c139fe956c6719110157866b7eafc1fb061a819 Mon Sep 17 00:00:00 2001 From: Chaewon Song Date: Sat, 9 Aug 2025 15:19:46 +0900 Subject: [PATCH 35/43] Apply suggestion from @seopp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 임승섭 <100005890+seopp@users.noreply.github.com> --- chapters/ko/chapter3/5.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapters/ko/chapter3/5.mdx b/chapters/ko/chapter3/5.mdx index ec5f01b02..a8af1f381 100644 --- a/chapters/ko/chapter3/5.mdx +++ b/chapters/ko/chapter3/5.mdx @@ -217,7 +217,7 @@ trainer = Trainer( - 모델 성능이 훈련 초기에 고원에 도달 - 훈련 정확도가 예상보다 낮음 -**부적합 해결책** +**과소적합 해결책** - **모델 용량 증가**: 더 큰 모델이나 더 많은 매개변수 사용 - **더 오래 훈련**: 에폭 수 증가 - **학습률 조정**: 다른 학습률 시도 From df3c859d661b60e726e658dbd8dc6f254d8ab60d Mon Sep 17 00:00:00 2001 From: Chaewon Song Date: Sat, 9 Aug 2025 15:19:54 +0900 Subject: [PATCH 36/43] Apply suggestion from @seopp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 임승섭 <100005890+seopp@users.noreply.github.com> --- chapters/ko/chapter3/5.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapters/ko/chapter3/5.mdx b/chapters/ko/chapter3/5.mdx index a8af1f381..ffcf17ed8 100644 --- a/chapters/ko/chapter3/5.mdx +++ b/chapters/ko/chapter3/5.mdx @@ -285,7 +285,7 @@ training_args = TrainingArguments( - 학습 곡선은 모델 훈련 진행 상황을 이해하는 데 필수적인 도구입니다. - 손실과 정확도 곡선을 모두 모니터링하되, 서로 다른 특성을 가지고 있음을 기억하세요. - 과적합은 훈련/검증 성능의 분기로 나타납니다. -- 부적합은 훈련과 검증 데이터 모두에서 성능이 좋지 않은 것으로 나타납니다. +- 과소적합은 훈련과 검증 데이터 모두에서 성능이 좋지 않은 것으로 나타납니다. - Weights & Biases와 같은 도구는 학습 곡선을 쉽게 추적하고 분석할 수 있게 해줍니다. - 조기 중단과 적절한 정규화는 대부분의 일반적인 훈련 문제를 해결할 수 있습니다. From 186985fca05362a7eb76a388c74ed4d55340c65e Mon Sep 17 00:00:00 2001 From: Chaewon Song Date: Sat, 9 Aug 2025 15:20:01 +0900 Subject: [PATCH 37/43] Apply suggestion from @seopp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 임승섭 <100005890+seopp@users.noreply.github.com> --- chapters/ko/chapter3/5.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapters/ko/chapter3/5.mdx b/chapters/ko/chapter3/5.mdx index ffcf17ed8..f6863ee9b 100644 --- a/chapters/ko/chapter3/5.mdx +++ b/chapters/ko/chapter3/5.mdx @@ -393,7 +393,7 @@ training_args = TrainingArguments( ]} /> -### 5. 모델이 부적합일 수 있음을 나타내는 것은 무엇인가요? +### 5. 모델이 과소적합일 수 있음을 나타내는 것은 무엇인가요? Date: Sat, 9 Aug 2025 15:20:10 +0900 Subject: [PATCH 38/43] Apply suggestion from @seopp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 임승섭 <100005890+seopp@users.noreply.github.com> --- chapters/ko/chapter3/5.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapters/ko/chapter3/5.mdx b/chapters/ko/chapter3/5.mdx index f6863ee9b..c3f6846fa 100644 --- a/chapters/ko/chapter3/5.mdx +++ b/chapters/ko/chapter3/5.mdx @@ -399,7 +399,7 @@ training_args = TrainingArguments( choices={[ { text: "훈련 정확도가 검증 정확도보다 훨씬 높습니다.", - explain: "이는 부적합이 아니라 과적합을 설명합니다." + explain: "이는 과소적합이 아니라 과적합을 설명합니다." }, { text: "훈련과 검증 성능이 모두 좋지 않고 조기에 고원에 도달합니다.", From 0d5d42bbc8cb5646f5517f582e790a4437ec4750 Mon Sep 17 00:00:00 2001 From: Chaewon Song Date: Sat, 9 Aug 2025 15:20:18 +0900 Subject: [PATCH 39/43] Apply suggestion from @seopp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 임승섭 <100005890+seopp@users.noreply.github.com> --- chapters/ko/chapter3/5.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapters/ko/chapter3/5.mdx b/chapters/ko/chapter3/5.mdx index c3f6846fa..8d2b3e015 100644 --- a/chapters/ko/chapter3/5.mdx +++ b/chapters/ko/chapter3/5.mdx @@ -408,7 +408,7 @@ training_args = TrainingArguments( }, { text: "학습 곡선이 변동 없이 매우 부드럽습니다.", - explain: "부드러운 곡선은 일반적으로 좋은 것이며 부적합을 나타내지 않습니다." + explain: "부드러운 곡선은 일반적으로 좋은 것이며 과소적합을 나타내지 않습니다." }, { text: "검증 손실이 훈련 손실보다 빠르게 감소합니다.", From 4c5efe1d6172c518ebfa498508dd0cc979b06565 Mon Sep 17 00:00:00 2001 From: Chaewon Song Date: Sat, 9 Aug 2025 15:20:26 +0900 Subject: [PATCH 40/43] Apply suggestion from @seopp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 임승섭 <100005890+seopp@users.noreply.github.com> --- chapters/ko/chapter3/5.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapters/ko/chapter3/5.mdx b/chapters/ko/chapter3/5.mdx index 8d2b3e015..cbfe70bfd 100644 --- a/chapters/ko/chapter3/5.mdx +++ b/chapters/ko/chapter3/5.mdx @@ -403,7 +403,7 @@ training_args = TrainingArguments( }, { text: "훈련과 검증 성능이 모두 좋지 않고 조기에 고원에 도달합니다.", - explain: "정답입니다! 부적합은 모델이 패턴을 학습할 용량이 부족할 때 발생하여 훈련과 검증 데이터 모두에서 성능이 좋지 않습니다.", + explain: "정답입니다! 과소적합은 모델이 패턴을 학습할 용량이 부족할 때 발생하여 훈련과 검증 데이터 모두에서 성능이 좋지 않습니다.", correct: true }, { From 88bc7399a7d9ae18c3768c088a934d7a389ebcd3 Mon Sep 17 00:00:00 2001 From: Chaewon Song Date: Mon, 11 Aug 2025 09:20:11 +0900 Subject: [PATCH 41/43] fix: apply suggestion from @AhnJoonSung --- chapters/ko/chapter3/5.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chapters/ko/chapter3/5.mdx b/chapters/ko/chapter3/5.mdx index cbfe70bfd..e0624b3d4 100644 --- a/chapters/ko/chapter3/5.mdx +++ b/chapters/ko/chapter3/5.mdx @@ -100,7 +100,7 @@ trainer.train() ![Healthy Loss Curve](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter3/5.png) -위의 그림을 살펴보겠습니다. 손실 곡선(왼쪽)과 해당 정확도 곡선(오른쪽)을 모두 표시합니다. 이러한 곡선은 뚜렷한 특성을 가지고 있습니다. +위의 그림은 손실 곡선(왼쪽)과 해당 정확도 곡선(오른쪽)을 함께 보여줍니다. 두 곡선은 뚜렷한 특성을 가지고 있습니다. 손실 곡선은 시간에 따른 모델 손실의 값을 보여줍니다. 처음에는 손실이 높다가 점차 감소하여 모델이 개선되고 있음을 나타냅니다. 손실 값의 감소는 손실이 예측된 출력과 실제 출력 간의 오류를 나타내므로 모델이 더 나은 예측을 하고 있음을 시사합니다. @@ -121,7 +121,7 @@ trainer.train() ### 실용적인 예시[[practical-examples]] -학습 곡선의 몇 가지 실용적인 예시를 살펴보겠습니다. 먼저 훈련 중 학습 곡선을 모니터링하는 몇 가지 접근 방식을 강조하겠습니다. 아래에서는 학습 곡선에서 관찰할 수 있는 다양한 패턴을 분해하겠습니다. +학습 곡선의 몇 가지 실용적인 예시를 살펴보겠습니다. 먼저 훈련 중 학습 곡선을 모니터링하는 몇 가지 접근 방식을 강조하겠습니다. 아래에서는 학습 곡선에서 관찰할 수 있는 다양한 패턴을 살펴보겠습니다. #### 훈련 중[[during-training]] From 3c9c7ff1e2fdbacface6c07e6099f28cfb5f65dc Mon Sep 17 00:00:00 2001 From: Kalix Louiis Date: Wed, 13 Aug 2025 00:31:09 +0630 Subject: [PATCH 42/43] feat(my): Add Myanmar translation for Chapter 0: Setup --- chapters/my/_toctree.yml | 264 +++++++++++++++++++++++++++++++++++++ chapters/my/chapter0/1.mdx | 110 ++++++++++++++++ 2 files changed, 374 insertions(+) create mode 100644 chapters/my/_toctree.yml create mode 100644 chapters/my/chapter0/1.mdx diff --git a/chapters/my/_toctree.yml b/chapters/my/_toctree.yml new file mode 100644 index 000000000..8cb174f67 --- /dev/null +++ b/chapters/my/_toctree.yml @@ -0,0 +1,264 @@ +- title: 0. စတင်ပြင်ဆင်ခြင်း + sections: + - local: chapter0/1 + title: နိဒါန်း + +# - title: 1. Transformer မော်ဒယ်များ +# sections: +# - local: chapter1/1 +# title: နိဒါန်း +# - local: chapter1/2 +# title: သဘာဝဘာသာစကားစီမံဆောင်ရွက်မှု (Natural Language Processing - NLP) နှင့် ဘာသာစကားမော်ဒယ်ကြီးများ +# - local: chapter1/3 +# title: Transformer များ၏ စွမ်းဆောင်နိုင်ရည်များ +# - local: chapter1/4 +# title: Transformer များ မည်သို့လုပ်ဆောင်သလဲ။ +# - local: chapter1/5 +# title: 🤗 Transformers များက လုပ်ငန်းတာဝန်များကို မည်သို့ဖြေရှင်းသလဲ။ +# - local: chapter1/6 +# title: Transformer Architectures များ +# - local: chapter1/7 +# title: အမြန်ဉာဏ်စမ်း +# - local: chapter1/8 +# title: LLM များဖြင့် Inference လုပ်ဆောင်ခြင်း +# - local: chapter1/9 +# title: ဘက်လိုက်မှုနှင့် ကန့်သတ်ချက်များ +# - local: chapter1/10 +# title: အနှစ်ချုပ် +# - local: chapter1/11 +# title: အသိအမှတ်ပြုစာမေးပွဲ +# quiz: 1 + +# - title: 2. 🤗 Transformers ကိုအသုံးပြုခြင်း +# sections: +# - local: chapter2/1 +# title: နိဒါန်း +# - local: chapter2/2 +# title: Pipeline နောက်ကွယ်မှ လုပ်ဆောင်ချက်များ +# - local: chapter2/3 +# title: မော်ဒယ်များ +# - local: chapter2/4 +# title: Tokenizer များ +# - local: chapter2/5 +# title: Sequence များစွာကို စီမံကိုင်တွယ်ခြင်း +# - local: chapter2/6 +# title: အားလုံးကို ပေါင်းစည်းခြင်း +# - local: chapter2/7 +# title: အခြေခံအသုံးပြုမှု ပြီးစီးပါပြီ။ +# - local: chapter2/8 +# title: Optimized Inference Deployment +# - local: chapter2/9 +# title: အခန်းပြီးဉာဏ်စမ်း +# quiz: 2 + +# - title: 3. ကြိုတင်လေ့ကျင့်ထားသော မော်ဒယ်အား Fine-tuning ပြုလုပ်ခြင်း +# sections: +# - local: chapter3/1 +# title: နိဒါန်း +# - local: chapter3/2 +# title: ဒေတာများအား စီမံဆောင်ရွက်ခြင်း +# - local: chapter3/3 +# title: Trainer API ဖြင့် မော်ဒယ်အား Fine-tuning ပြုလုပ်ခြင်း +# - local: chapter3/4 +# title: ပြည့်စုံသော လေ့ကျင့်မှု Loop +# - local: chapter3/5 +# title: Learning Curve များကို နားလည်ခြင်း +# - local: chapter3/6 +# title: Fine-tuning ပြီးမြောက်ပါပြီ။ +# - local: chapter3/7 +# title: အခန်းပြီးဉာဏ်စမ်း +# quiz: 3 + +# - title: 4. မော်ဒယ်များနှင့် Tokenizer များအား မျှဝေခြင်း +# sections: +# - local: chapter4/1 +# title: The Hugging Face Hub +# - local: chapter4/2 +# title: ကြိုတင်လေ့ကျင့်ထားသော မော်ဒယ်များအား အသုံးပြုခြင်း +# - local: chapter4/3 +# title: ကြိုတင်လေ့ကျင့်ထားသော မော်ဒယ်များအား မျှဝေခြင်း +# - local: chapter4/4 +# title: မော်ဒယ်ကတ် တည်ဆောက်ခြင်း +# - local: chapter4/5 +# title: အပိုင်း ၁ ပြီးစီးပါပြီ။ +# - local: chapter4/6 +# title: အခန်းပြီးဉာဏ်စမ်း +# quiz: 4 + +# - title: 5. The 🤗 Datasets Library +# sections: +# - local: chapter5/1 +# title: နိဒါန်း +# - local: chapter5/2 +# title: ကျွန်ုပ်၏ Dataset သည် Hub တွင်မရှိလျှင် +# - local: chapter5/3 +# title: ဒေတာများအား ပိုင်းဖြတ်ရန် +# - local: chapter5/4 +# title: Big Data? 🤗 Datasets က ကူညီပါပြီ။ +# - local: chapter5/5 +# title: ကိုယ်ပိုင် Dataset ဖန်တီးခြင်း +# - local: chapter5/6 +# title: FAISS ဖြင့် Semantic Search ပြုလုပ်ခြင်း +# - local: chapter5/7 +# title: 🤗 Datasets ပြီးမြောက်ပါပြီ။ +# - local: chapter5/8 +# title: အခန်းပြီးဉာဏ်စမ်း +# quiz: 5 + +# - title: 6. The 🤗 Tokenizers Library +# sections: +# - local: chapter6/1 +# title: နိဒါန်း +# - local: chapter6/2 +# title: Tokenizer အဟောင်းမှ Tokenizer အသစ်တစ်ခု လေ့ကျင့်ခြင်း +# - local: chapter6/3 +# title: Fast Tokenizer များ၏ ထူးခြားစွမ်းရည်များ +# - local: chapter6/3b +# title: QA Pipeline ရှိ Fast Tokenizer များ +# - local: chapter6/4 +# title: Normalization နှင့် 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: Tokenizer တစ်ခုအား အဆင့်ဆင့် တည်ဆောက်ခြင်း +# - local: chapter6/9 +# title: Tokenizer များ ပြီးမြောက်ပါပြီ။ +# - local: chapter6/10 +# title: အခန်းပြီးဉာဏ်စမ်း +# quiz: 6 + +# - title: 7. Classical NLP Tasks +# sections: +# - local: chapter7/1 +# title: နိဒါန်း +# - local: chapter7/2 +# title: Token ခွဲခြားသတ်မှတ်ခြင်း +# - local: chapter7/3 +# title: Masked Language Model တစ်ခုအား Fine-tuning ပြုလုပ်ခြင်း +# - local: chapter7/4 +# title: ဘာသာပြန်ခြင်း +# - local: chapter7/5 +# title: အနှစ်ချုပ်ခြင်း +# - local: chapter7/6 +# title: Causal Language Model တစ်ခုအား အစမှ လေ့ကျင့်ခြင်း +# - local: chapter7/7 +# title: မေးခွန်းဖြေဆိုခြင်း +# - local: chapter7/8 +# title: LLM များအား ကျွမ်းကျင်ခြင်း +# - local: chapter7/9 +# title: အခန်းပြီးဉာဏ်စမ်း +# quiz: 7 + +# - title: 8. အကူအညီတောင်းခံနည်း +# sections: +# - local: chapter8/1 +# title: နိဒါန်း +# - local: chapter8/2 +# title: အမှားတွေ့ရှိသည့်အခါ +# - local: chapter8/3 +# title: Forums တွင် အကူအညီတောင်းခံခြင်း +# - local: chapter8/4 +# title: လေ့ကျင့်မှု Pipeline အား Debugging ပြုလုပ်ခြင်း +# local_fw: { pt: chapter8/4, tf: chapter8/4_tf } +# - local: chapter8/5 +# title: ကောင်းမွန်သော Issue တစ်ခု ရေးသားနည်း +# - local: chapter8/6 +# title: အပိုင်း ၂ ပြီးစီးပါပြီ။ +# - local: chapter8/7 +# title: အခန်းပြီးဉာဏ်စမ်း +# quiz: 8 + +# - title: 9. Demo များ တည်ဆောက်ခြင်းနှင့် မျှဝေခြင်း +# subtitle: ကျွန်ုပ် မော်ဒယ်တစ်ခုကို လေ့ကျင့်ပြီးပါပြီ၊ ၎င်းကို မည်သို့ပြသနိုင်မည်နည်း။ +# sections: +# - local: chapter9/1 +# title: Gradio မိတ်ဆက် +# - local: chapter9/2 +# title: ပထမဆုံး Demo ကို တည်ဆောက်ခြင်း +# - local: chapter9/3 +# title: Interface Class ကို နားလည်ခြင်း +# - local: chapter9/4 +# title: Demo များကို မျှဝေခြင်း +# - local: chapter9/5 +# title: Hugging Face Hub နှင့် ပေါင်းစည်းမှုများ +# - local: chapter9/6 +# title: အဆင့်မြင့် Interface အင်္ဂါရပ်များ +# - local: chapter9/7 +# title: Blocks မိတ်ဆက် +# - local: chapter9/8 +# title: Gradio ပြီးမြောက်ပါပြီ။ +# - local: chapter9/9 +# title: အခန်းပြီးဉာဏ်စမ်း +# quiz: 9 + +# - title: 10. အရည်အသွေးမြင့် Dataset များ ပြုစုခြင်း +# subtitle: ထူးခြားသော Dataset များဖန်တီးရန် Argilla ကို မည်သို့အသုံးပြုမည်နည်း။ +# sections: +# - local: chapter10/1 +# title: Argilla မိတ်ဆက် +# - local: chapter10/2 +# title: Argilla Instance ကို စတင်ပြင်ဆင်ခြင်း +# - local: chapter10/3 +# title: Dataset ကို Argilla သို့ Load လုပ်ခြင်း +# - local: chapter10/4 +# title: Dataset ကို Annotation ပြုလုပ်ခြင်း +# - local: chapter10/5 +# title: Annotation ပြုလုပ်ပြီးသော Dataset ကို အသုံးပြုခြင်း +# - local: chapter10/6 +# title: Argilla ပြီးမြောက်ပါပြီ။ +# - local: chapter10/7 +# title: အခန်းပြီးဉာဏ်စမ်း +# quiz: 10 + +# - title: 11. Large Language Models များအား Fine-tune ပြုလုပ်ခြင်း +# subtitle: Supervised Fine-tuning နှင့် Low-Rank Adaptation ကို အသုံးပြု၍ Large Language Model တစ်ခုအား Fine-tune ပြုလုပ်ခြင်း +# sections: +# - local: chapter11/1 +# title: နိဒါန်း +# - local: chapter11/2 +# title: Chat Template များ +# - local: chapter11/3 +# title: SFTTrainer ဖြင့် Fine-Tuning ပြုလုပ်ခြင်း +# - local: chapter11/4 +# title: LoRA (Low-Rank Adaptation) +# - local: chapter11/5 +# title: အကဲဖြတ်ခြင်း +# - local: chapter11/6 +# title: နိဂုံး +# - local: chapter11/7 +# title: စာမေးပွဲအချိန်။ +# quiz: 11 + +# - title: 12. Reasoning မော်ဒယ်များ တည်ဆောက်ခြင်း +# subtitle: DeepSeek R1 ကဲ့သို့ Reasoning မော်ဒယ်များအား တည်ဆောက်နည်းကို လေ့လာပါ။ +# new: true +# sections: +# - local: chapter12/1 +# title: နိဒါန်း +# - local: chapter12/2 +# title: LLM များပေါ်တွင် Reinforcement Learning +# - local: chapter12/3 +# title: DeepSeek R1 Paper မှ Aha Moment +# - local: chapter12/3a +# title: DeepSeekMath ရှိ GRPO ကို အဆင့်မြင့် နားလည်ခြင်း +# - local: chapter12/4 +# title: TRL တွင် GRPO ကို အကောင်အထည်ဖော်ခြင်း +# - local: chapter12/5 +# title: GRPO ဖြင့် မော်ဒယ်တစ်ခုအား Fine-tune ပြုလုပ်ရန် လက်တွေ့လေ့ကျင့်ခန်း +# - local: chapter12/6 +# title: Unsloth ဖြင့် လက်တွေ့လေ့ကျင့်ခန်း +# - local: chapter12/7 +# title: မကြာမီလာမည်။ + +# - title: သင်တန်းဆိုင်ရာ ပွဲများ +# sections: +# - local: events/1 +# title: Live Sessions နှင့် Workshop များ +# - local: events/2 +# title: အပိုင်း ၂ ထုတ်ပြန်ခြင်း ပွဲ +# - local: events/3 +# title: Gradio Blocks Party \ No newline at end of file diff --git a/chapters/my/chapter0/1.mdx b/chapters/my/chapter0/1.mdx new file mode 100644 index 000000000..4cc3d24c8 --- /dev/null +++ b/chapters/my/chapter0/1.mdx @@ -0,0 +1,110 @@ +# နိဒါန်း[[introduction]] + +Hugging Face Course မှ ကြိုဆိုပါတယ်။ ဒီနိဒါန်းမှာ သင့်အတွက် အလုပ်လုပ်နိုင်တဲ့ ပတ်ဝန်းကျင်တစ်ခု ဘယ်လိုတည်ဆောက်ရမလဲဆိုတာကို လမ်းညွှန်ပေးသွားမှာပါ။ သင်ဟာ Course ကို အခုမှစတင်သူဆိုရင်တော့ [အခန်း ၁](/course/chapter1) ကို အရင်ဆုံး ဖတ်ရှုပြီးမှ သင့်ရဲ့ပတ်ဝန်းကျင်ကို ထူထောင်ပြီး ကိုယ်တိုင် Code တွေကို လေ့ကျင့်ကြည့်ဖို့ အကြံပြုလိုပါတယ်။ + +ဒီ Course မှာ အသုံးပြုမယ့် Library တွေအားလုံးဟာ Python Package တွေအနေနဲ့ ရရှိနိုင်ပါတယ်။ ဒါကြောင့် ဒီမှာ Python ပတ်ဝန်းကျင်တစ်ခုကို ဘယ်လိုတည်ဆောက်ပြီး လိုအပ်တဲ့ Library တွေကို ဘယ်လို Install လုပ်ရမလဲဆိုတာကို ပြသပေးသွားမှာ ဖြစ်ပါတယ်။ + +သင့်ရဲ့ အလုပ်လုပ်မယ့်ပတ်ဝန်းကျင်ကို တည်ဆောက်တဲ့ နည်းလမ်းနှစ်မျိုးကို ဖော်ပြပေးသွားမှာပါ။ Colab Notebook ဒါမှမဟုတ် Python Virtual Environment ကို အသုံးပြုတဲ့နည်းလမ်းတွေ ဖြစ်ပါတယ်။ သင့်အတွက် အဆင်ပြေဆုံး နည်းလမ်းကို ရွေးချယ်နိုင်ပါတယ်။ စတင်လေ့လာသူတွေအတွက်တော့ Colab Notebook ကို အသုံးပြုဖို့ အထူးအကြံပြုလိုပါတယ်။ + +Windows System အတွက်တော့ ဖော်ပြပေးသွားမှာ မဟုတ်ပါဘူး။ အကယ်၍ သင်က Windows ကို အသုံးပြုနေတယ်ဆိုရင်တော့ Colab Notebook ကို အသုံးပြုပြီး လေ့ကျင့်ခန်းတွေ လိုက်လုပ်ဖို့ အကြံပြုလိုပါတယ်။ Linux Distribution ဒါမှမဟုတ် macOS ကို အသုံးပြုနေတယ်ဆိုရင်တော့ ဒီမှာဖော်ပြထားတဲ့ နည်းလမ်းနှစ်မျိုးလုံးကို အသုံးပြုနိုင်ပါတယ်။ + +ဒီ Course ရဲ့ အစိတ်အပိုင်းအများစုမှာ Hugging Face Account ရှိဖို့ လိုအပ်ပါတယ်။ ဒါကြောင့် အခုပဲ Account တစ်ခု ဖန်တီးထားဖို့ အကြံပြုလိုပါတယ်- [create an account](https://huggingface.co/join)။ + +## Google Colab Notebook ကို အသုံးပြုခြင်း[[using-a-google-colab-notebook]] + +Colab Notebook ကို အသုံးပြုတာဟာ အလွယ်ကူဆုံး တည်ဆောက်မှုဖြစ်ပါတယ်။ Browser မှာ Notebook တစ်ခုကို ဖွင့်ပြီး Code တွေစရေးရုံပါပဲ။ + +Colab နဲ့ မရင်းနှီးသေးဘူးဆိုရင်တော့ [introduction](https://colab.research.google.com/notebooks/intro.ipynb) ကို အရင်ဆုံး ဖတ်ရှုဖို့ အကြံပြုလိုပါတယ်။ Colab က GPU ဒါမှမဟုတ် TPU လို Accelerating Hardware တွေကို အသုံးပြုခွင့်ပေးပြီး Workload နည်းနည်းအတွက်ဆိုရင် အခမဲ့ အသုံးပြုနိုင်ပါတယ်။ + +Colab မှာ အသုံးပြုရတာ အဆင်ပြေပြီဆိုရင် Notebook အသစ်တစ်ခု ဖန်တီးပြီး စတင်တည်ဆောက်နိုင်ပါပြီ။ + +
+An empty colab notebook +
+ +နောက်တစ်ဆင့်ကတော့ ဒီ Course မှာ အသုံးပြုမယ့် Library တွေကို Install လုပ်ဖို့ပဲ ဖြစ်ပါတယ်။ Python အတွက် Package Manager ဖြစ်တဲ့ `pip` ကို အသုံးပြုပြီး Install လုပ်ပါမယ်။ Notebook တွေမှာ System Command တွေကို `!` Character နဲ့ စပြီး ရေးသားနိုင်ပါတယ်။ ဒါကြောင့် 🤗 Transformers Library ကို အောက်ပါအတိုင်း Install လုပ်နိုင်ပါတယ်- + +``` +!pip install transformers +``` + +သင့်ရဲ့ Python Runtime မှာ Import လုပ်ခြင်းဖြင့် Package မှန်ကန်စွာ Install လုပ်ပြီးခြင်းကို သေချာစစ်ဆေးနိုင်ပါတယ်- + +``` +import transformers +``` + +
+A gif showing the result of the two commands above: installation and import +
+ +ဒါက 🤗 Transformers ရဲ့ ပေါ့ပါးတဲ့ Version ကိုသာ Install လုပ်ထားတာ ဖြစ်ပါတယ်။ အထူးသဖြင့် PyTorch ဒါမှမဟုတ် TensorFlow လို Machine Learning Framework တွေတော့ Install လုပ်ထားတာ မဟုတ်ပါဘူး။ Library ရဲ့ ကွဲပြားခြားနားတဲ့ Feature တွေ အများကြီးကို အသုံးပြုရမှာဖြစ်လို့ Development Version ကို Install လုပ်ဖို့ အကြံပြုလိုပါတယ်။ ဒီ Version မှာတော့ စိတ်ကူးနိုင်သမျှ အသုံးပြုမှုတိုင်းအတွက် လိုအပ်တဲ့ Dependency တွေ အားလုံးပါဝင်ပါတယ်- + +``` +!pip install transformers[sentencepiece] +``` + +ဒါက အချိန်အနည်းငယ်ယူပါလိမ့်မယ်။ ဒါပေမဲ့ ပြီးတာနဲ့ Course ရဲ့ ကျန်အပိုင်းတွေအတွက် သင် အသင့်ဖြစ်နေပါပြီ။ + +## Python Virtual Environment ကို အသုံးပြုခြင်း[[using-a-python-virtual-environment]] + +အကယ်၍ သင်က Python Virtual Environment ကို အသုံးပြုဖို့ နှစ်သက်တယ်ဆိုရင် ပထမအဆင့်က သင့်ရဲ့ System မှာ Python ကို Install လုပ်ဖို့ပါပဲ။ [ဒီလမ်းညွှန်](https://realpython.com/installing-python/) ကို လိုက်နာပြီး စတင်ဖို့ အကြံပြုလိုပါတယ်။ + +Python ကို Install လုပ်ပြီးပြီဆိုရင် သင့်ရဲ့ Terminal မှာ Python Command တွေကို Run နိုင်ပြီဖြစ်ပါတယ်။ နောက်အဆင့်တွေ မဆက်ခင် Python မှန်ကန်စွာ Install လုပ်ပြီးပြီလားဆိုတာ သေချာအောင် `python --version` Command ကို Run ကြည့်နိုင်ပါတယ်။ ဒါက သင့်ရဲ့ System မှာ လက်ရှိရရှိနိုင်တဲ့ Python Version ကို ပြသပေးပါလိမ့်မယ်။ + +Terminal မှာ `python --version` လို Python Command တစ်ခုကို Run တဲ့အခါ၊ Command ကို Run နေတဲ့ Program ကို သင့်ရဲ့ System မှာရှိတဲ့ “main” Python အဖြစ် မှတ်ယူသင့်ပါတယ်။ ဒီ Main Installation ကို Package တွေမပါဘဲ သန့်ရှင်းအောင်ထားဖို့ အကြံပြုလိုပါတယ်။ ပြီးတော့ သင်အလုပ်လုပ်တဲ့ Application တစ်ခုစီအတွက် သီးခြား Environment တွေ ဖန်တီးဖို့အတွက် ဒီ Main Installation ကို အသုံးပြုသင့်ပါတယ်။ ဒီနည်းလမ်းက Application တစ်ခုစီမှာ သူ့ရဲ့ ကိုယ်ပိုင် Dependency တွေနဲ့ Package တွေ ရှိနိုင်ပြီး တခြား Application တွေနဲ့ ဖြစ်နိုင်တဲ့ Compatibility ပြဿနာတွေကို စိုးရိမ်စရာမလိုတော့ပါဘူး။ + +Python မှာ ဒါကို [virtual environments](https://docs.python.org/3/tutorial/venv.html) တွေနဲ့ လုပ်ဆောင်ပါတယ်။ Virtual Environment တွေက Self-contained Directory Tree တွေဖြစ်ပြီး တစ်ခုစီမှာ သတ်မှတ်ထားတဲ့ Python Version နဲ့ Application လိုအပ်တဲ့ Package တွေအားလုံးပါဝင်တဲ့ Python Installation တစ်ခုပါဝင်ပါတယ်။ ဒီလို Virtual Environment တစ်ခုကို ဖန်တီးတာကို ကိရိယာအမျိုးမျိုးနဲ့ လုပ်ဆောင်နိုင်ပေမဲ့ ဒီရည်ရွယ်ချက်အတွက် တရားဝင် Python Package ဖြစ်တဲ့ [`venv`](https://docs.python.org/3/library/venv.html#module-venv) ကို အသုံးပြုပါမယ်။ + +ပထမဆုံးအနေနဲ့ သင့် Application ထားရှိလိုတဲ့ Directory ကို ဖန်တီးပါ။ ဥပမာ- သင့်ရဲ့ Home Directory ရဲ့ Root မှာ *transformers-course* လို့ခေါ်တဲ့ Directory အသစ်တစ်ခု ဖန်တီးချင်ပါလိမ့်မယ်- + +``` +mkdir ~/transformers-course +cd ~/transformers-course +``` + +ဒီ Directory ထဲကနေ Python ရဲ့ `venv` Module ကို အသုံးပြုပြီး Virtual Environment တစ်ခုကို ဖန်တီးပါ- + +``` +python -m venv .env +``` + +အခုဆိုရင် သင့်ရဲ့ တခြားဘာမှမရှိတဲ့ Folder ထဲမှာ *.env* လို့ခေါ်တဲ့ Directory တစ်ခု ရှိနေပါပြီ- + +``` +ls -a +``` + +```out +. .. .env +``` + +`activate` နဲ့ `deactivate` Script တွေနဲ့ သင့်ရဲ့ Virtual Environment ထဲကို ဝင်ရောက်ခြင်းနဲ့ ထွက်ခွာခြင်းတို့ကို ပြုလုပ်နိုင်ပါတယ်- + +``` +# Virtual Environment ကို Activate ပြုလုပ်ရန် +source .env/bin/activate + +# Virtual Environment ကို Deactivate ပြုလုပ်ရန် +deactivate +``` + +`which python` Command ကို Run ခြင်းဖြင့် Environment က Activate လုပ်ထားပြီလားဆိုတာ သေချာအောင် စစ်ဆေးနိုင်ပါတယ်။ အကယ်၍ Virtual Environment ကို ညွှန်ပြနေတယ်ဆိုရင် သင် အောင်မြင်စွာ Activate လုပ်ပြီးသား ဖြစ်ပါပြီ။ + +``` +which python +``` + +```out +/home//transformers-course/.env/bin/python +``` + +### Dependencies များကို Install လုပ်ခြင်း[[installing-dependencies]] + +Google Colab Instance များကို အသုံးပြုခြင်းအပိုင်းကဲ့သို့ပင် ဆက်လက်လုပ်ဆောင်ရန် လိုအပ်သော Package များကို ယခု Install လုပ်ရပါမည်။ ထပ်မံ၍ 🤗 Transformers ၏ Development Version ကို `pip` Package Manager ကို အသုံးပြု၍ Install လုပ်နိုင်သည်- + +``` +pip install "transformers[sentencepiece]" +``` + +သင် အခုဆိုရင် အားလုံးအဆင်သင့်ဖြစ်ပြီး လုပ်ဆောင်ရန် အသင့်ဖြစ်နေပါပြီ။ \ No newline at end of file From 538e8c9eab6791fad834f35dc106f4ce6ab32d5c Mon Sep 17 00:00:00 2001 From: burtenshaw Date: Tue, 9 Sep 2025 14:30:31 +0200 Subject: [PATCH 43/43] fix hfoptions blocks in unit 1 8.mdx --- chapters/en/chapter2/8.mdx | 46 +++++++++++++++++++++++++++++++++----- 1 file changed, 41 insertions(+), 5 deletions(-) diff --git a/chapters/en/chapter2/8.mdx b/chapters/en/chapter2/8.mdx index f2f7ab431..84436e81b 100644 --- a/chapters/en/chapter2/8.mdx +++ b/chapters/en/chapter2/8.mdx @@ -15,16 +15,19 @@ TGI, vLLM, and llama.cpp serve similar purposes but have distinct characteristic Flash Attention + Flash Attention is a technique that optimizes the attention mechanism in transformer models by addressing memory bandwidth bottlenecks. As discussed earlier in [Chapter 1.8](/course/chapter1/8), the attention mechanism has quadratic complexity and memory usage, making it inefficient for long sequences. The key innovation is in how it manages memory transfers between High Bandwidth Memory (HBM) and faster SRAM cache. Traditional attention repeatedly transfers data between HBM and SRAM, creating bottlenecks by leaving the GPU idle. Flash Attention loads data once into SRAM and performs all calculations there, minimizing expensive memory transfers. While the benefits are most significant during training, Flash Attention's reduced VRAM usage and improved efficiency make it valuable for inference as well, enabling faster and more scalable LLM serving. + **vLLM** takes a different approach by using PagedAttention. Just like how a computer manages its memory in pages, vLLM splits the model's memory into smaller blocks. This clever system means it can handle different-sized requests more flexibly and doesn't waste memory space. It's particularly good at sharing memory between different requests and reduces memory fragmentation, which makes the whole system more efficient. + PagedAttention is a technique that addresses another critical bottleneck in LLM inference: KV cache memory management. As discussed in [Chapter 1.8](/course/chapter1/8), during text generation, the model stores attention keys and values (KV cache) for each generated token to reduce redundant computations. The KV cache can become enormous, especially with long sequences or multiple concurrent requests. vLLM's key innovation lies in how it manages this cache: @@ -35,11 +38,13 @@ vLLM's key innovation lies in how it manages this cache: 4. **Memory Sharing**: For operations like parallel sampling, pages storing the KV cache for the prompt can be shared across multiple sequences. The PagedAttention approach can lead to up to 24x higher throughput compared to traditional methods, making it a game-changer for production LLM deployments. If you want to go really deep into how PagedAttention works, you can read the [the guide from the vLLM documentation](https://docs.vllm.ai/en/latest/design/kernel/paged_attention.html). + **llama.cpp** is a highly optimized C/C++ implementation originally designed for running LLaMA models on consumer hardware. It focuses on CPU efficiency with optional GPU acceleration and is ideal for resource-constrained environments. llama.cpp uses quantization techniques to reduce model size and memory requirements while maintaining good performance. It implements optimized kernels for various CPU architectures and supports basic KV cache management for efficient token generation. + Quantization in llama.cpp reduces the precision of model weights from 32-bit or 16-bit floating point to lower precision formats like 8-bit integers (INT8), 4-bit, or even lower. This significantly reduces memory usage and improves inference speed with minimal quality loss. Key quantization features in llama.cpp include: @@ -49,9 +54,8 @@ Key quantization features in llama.cpp include: 4. **Hardware-Specific Optimizations**: Includes optimized code paths for various CPU architectures (AVX2, AVX-512, NEON) This approach enables running billion-parameter models on consumer hardware with limited memory, making it perfect for local deployments and edge devices. - - +
### Deployment and Integration @@ -63,8 +67,6 @@ Let's move on to the deployment and integration differences between the framewor **llama.cpp** prioritizes simplicity and portability. Its server implementation is lightweight and can run on a wide range of hardware, from powerful servers to consumer laptops and even some high-end mobile devices. With minimal dependencies and a simple C/C++ core, it's easy to deploy in environments where installing Python frameworks would be challenging. The server provides an OpenAI-compatible API while maintaining a much smaller resource footprint than other solutions. - - ## Getting Started Let's explore how to use these frameworks for deploying LLMs, starting with installation and basic setup. @@ -146,7 +148,9 @@ response = client.chat.completions.create( ) print(response.choices[0].message.content) ``` + + llama.cpp is easy to install and use, requiring minimal dependencies and supporting both CPU and GPU inference. @@ -235,7 +239,9 @@ response = client.chat.completions.create( ) print(response.choices[0].message.content) ``` + + vLLM is easy to install and use, with both OpenAI API compatibility and a native Python interface. @@ -306,6 +312,7 @@ response = client.chat.completions.create( ) print(response.choices[0].message.content) ``` + @@ -333,6 +340,7 @@ docker run --gpus all \ ``` Use the InferenceClient for flexible text generation: + ```python from huggingface_hub import InferenceClient @@ -380,7 +388,9 @@ response = client.chat.completions.create( ) print(response.choices[0].message.content) ``` + + For llama.cpp, you can set advanced parameters when launching the server: @@ -487,7 +497,9 @@ output = llm( print(output["choices"][0]["text"]) ``` + + For advanced usage with vLLM, you can use the InferenceClient: @@ -579,6 +591,7 @@ formatted_prompt = llm.get_chat_template()(chat_prompt) # Uses model's chat tem outputs = llm.generate(formatted_prompt, sampling_params) print(outputs[0].outputs[0].text) ``` + @@ -610,7 +623,9 @@ client.generate( repetition_penalty=1.1, # Reduce repetition ) ``` + + ```python @@ -635,7 +650,9 @@ output = llm( repeat_penalty=1.1, ) ``` + + ```python @@ -648,6 +665,7 @@ params = SamplingParams( ) llm.generate("Write a creative story", sampling_params=params) ``` + @@ -659,6 +677,7 @@ Both frameworks provide ways to prevent repetitive text generation: + ```python client.generate( "Write a varied text", @@ -666,7 +685,9 @@ client.generate( no_repeat_ngram_size=3, # Prevent 3-gram repetition ) ``` + + ```python @@ -686,7 +707,9 @@ output = llm( presence_penalty=0.5, # Additional presence penalty ) ``` + + ```python @@ -695,6 +718,7 @@ params = SamplingParams( frequency_penalty=0.1, # Penalize token frequency ) ``` + @@ -706,6 +730,7 @@ You can control generation length and specify when to stop: + ```python client.generate( "Generate a short paragraph", @@ -714,7 +739,9 @@ client.generate( stop_sequences=["\n\n", "###"], ) ``` + + ```python @@ -729,7 +756,9 @@ response = client.completions.create( # Via direct library output = llm("Generate a short paragraph", max_tokens=100, stop=["\n\n", "###"]) ``` + + ```python @@ -741,6 +770,7 @@ params = SamplingParams( skip_special_tokens=True, ) ``` + @@ -752,6 +782,7 @@ Both frameworks implement advanced memory management techniques for efficient in + TGI uses Flash Attention 2 and continuous batching: ```sh @@ -763,7 +794,9 @@ docker run --gpus all -p 8080:80 \ --max-batch-total-tokens 8192 \ --max-input-length 4096 ``` + + llama.cpp uses quantization and optimized memory layout: @@ -789,7 +822,9 @@ For models too large for your GPU, you can use CPU offloading: --n-gpu-layers 20 \ # Keep first 20 layers on GPU --threads 8 # Use more CPU threads for CPU layers ``` + + vLLM uses PagedAttention for optimal memory management: @@ -806,6 +841,7 @@ engine_args = AsyncEngineArgs( llm = LLM(engine_args=engine_args) ``` + @@ -818,4 +854,4 @@ llm = LLM(engine_args=engine_args) - [vLLM GitHub Repository](https://github.com/vllm-project/vllm) - [PagedAttention Paper](https://arxiv.org/abs/2309.06180) - [llama.cpp GitHub Repository](https://github.com/ggerganov/llama.cpp) -- [llama-cpp-python Repository](https://github.com/abetlen/llama-cpp-python) \ No newline at end of file +- [llama-cpp-python Repository](https://github.com/abetlen/llama-cpp-python)