pjh11098 commited on
Commit
7c69936
·
verified ·
1 Parent(s): 0f54c5d

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +262 -187
README.md CHANGED
@@ -3,197 +3,272 @@ library_name: transformers
3
  tags: []
4
  ---
5
 
6
- # Model Card for Model ID
7
 
8
- <!-- Provide a quick summary of what the model is/does. -->
9
 
10
 
11
 
12
  ## Model Details
13
 
14
- ### Model Description
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- <!-- Provide a longer summary of what this model is. -->
17
-
18
- This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
-
20
- - **Developed by:** [More Information Needed]
21
- - **Funded by [optional]:** [More Information Needed]
22
- - **Shared by [optional]:** [More Information Needed]
23
- - **Model type:** [More Information Needed]
24
- - **Language(s) (NLP):** [More Information Needed]
25
- - **License:** [More Information Needed]
26
- - **Finetuned from model [optional]:** [More Information Needed]
27
-
28
- ### Model Sources [optional]
29
-
30
- <!-- Provide the basic links for the model. -->
31
-
32
- - **Repository:** [More Information Needed]
33
- - **Paper [optional]:** [More Information Needed]
34
- - **Demo [optional]:** [More Information Needed]
35
-
36
- ## Uses
37
-
38
- <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
-
40
- ### Direct Use
41
-
42
- <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
-
44
- [More Information Needed]
45
-
46
- ### Downstream Use [optional]
47
-
48
- <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
-
50
- [More Information Needed]
51
-
52
- ### Out-of-Scope Use
53
-
54
- <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
-
56
- [More Information Needed]
57
-
58
- ## Bias, Risks, and Limitations
59
-
60
- <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
-
62
- [More Information Needed]
63
-
64
- ### Recommendations
65
-
66
- <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
-
68
- Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
-
70
- ## How to Get Started with the Model
71
-
72
- Use the code below to get started with the model.
73
-
74
- [More Information Needed]
75
-
76
- ## Training Details
77
-
78
- ### Training Data
79
-
80
- <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
-
82
- [More Information Needed]
83
-
84
- ### Training Procedure
85
-
86
- <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
-
88
- #### Preprocessing [optional]
89
-
90
- [More Information Needed]
91
-
92
-
93
- #### Training Hyperparameters
94
-
95
- - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
-
97
- #### Speeds, Sizes, Times [optional]
98
-
99
- <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
-
101
- [More Information Needed]
102
-
103
- ## Evaluation
104
-
105
- <!-- This section describes the evaluation protocols and provides the results. -->
106
-
107
- ### Testing Data, Factors & Metrics
108
-
109
- #### Testing Data
110
-
111
- <!-- This should link to a Dataset Card if possible. -->
112
-
113
- [More Information Needed]
114
-
115
- #### Factors
116
-
117
- <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
-
119
- [More Information Needed]
120
-
121
- #### Metrics
122
-
123
- <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
-
125
- [More Information Needed]
126
-
127
- ### Results
128
-
129
- [More Information Needed]
130
-
131
- #### Summary
132
-
133
-
134
-
135
- ## Model Examination [optional]
136
-
137
- <!-- Relevant interpretability work for the model goes here -->
138
-
139
- [More Information Needed]
140
-
141
- ## Environmental Impact
142
-
143
- <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
-
145
- Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
-
147
- - **Hardware Type:** [More Information Needed]
148
- - **Hours used:** [More Information Needed]
149
- - **Cloud Provider:** [More Information Needed]
150
- - **Compute Region:** [More Information Needed]
151
- - **Carbon Emitted:** [More Information Needed]
152
-
153
- ## Technical Specifications [optional]
154
-
155
- ### Model Architecture and Objective
156
-
157
- [More Information Needed]
158
-
159
- ### Compute Infrastructure
160
-
161
- [More Information Needed]
162
-
163
- #### Hardware
164
-
165
- [More Information Needed]
166
-
167
- #### Software
168
-
169
- [More Information Needed]
170
-
171
- ## Citation [optional]
172
-
173
- <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
-
175
- **BibTeX:**
176
-
177
- [More Information Needed]
178
-
179
- **APA:**
180
-
181
- [More Information Needed]
182
-
183
- ## Glossary [optional]
184
-
185
- <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
-
187
- [More Information Needed]
188
-
189
- ## More Information [optional]
190
-
191
- [More Information Needed]
192
-
193
- ## Model Card Authors [optional]
194
-
195
- [More Information Needed]
196
-
197
- ## Model Card Contact
198
-
199
- [More Information Needed]
 
3
  tags: []
4
  ---
5
 
6
+ # **Model Card for Gemma2-2B-IT-Finetuned-KO-Bias-Detection**
7
 
8
+ This model is fine-tuned from the base `google/gemma-2-2b-it` model using the Korean UnSmile Dataset, which focuses on identifying hate speech in Korean. The model detects various categories of hate speech, including but not limited to gender, race, age, and sexual orientation.
9
 
10
 
11
 
12
  ## Model Details
13
 
14
+ ### **Model Description**
15
+
16
+ In this project, I fine-tuned the google/gemma-2-2b-it model using the Korean UnSmile Dataset—a comprehensive dataset for hate speech in Korean—released by Smilegate AI. The fine-tuned model is capable of identifying the following hate speech categories:
17
+ - Women/Family: Stereotypes or derogatory remarks targeting women or family structures, including non-traditional families.
18
+ - Men: Comments that demean or mock men.
19
+ - LGBTQ+: Hate speech aimed at individuals based on sexual orientation or gender identity.
20
+ - Race/Nationality: Offensive language or stereotypes related to race or nationality, such as insults towards specific ethnic groups or nationalities.
21
+ - Age: Disparaging comments targeting specific age groups or generations.
22
+ - Region: Hate speech directed at people from specific regions.
23
+ - Religion: Negative or offensive comments aimed at religious groups or beliefs.
24
+ - Other Hate Speech: Includes hate speech targeting other groups, such as individuals with disabilities or specific professions (e.g., police, journalists).
25
+
26
+ This fine-tuned model offers a practical solution for detecting toxic behavior on online platforms, helping ensure safer and more inclusive online environments by classifying harmful content efficiently and accurately.
27
+
28
+ ### **Access Requirements**
29
+ To use the Gemma model, please follow these steps:
30
+ [**1. Access Gemma**]
31
+ - 1-1. Navigate to the gemma-2-2b-it repository that you wish to use.
32
+ - 1-2. Click on "Acknowledge license" in the "Access Gemma on Hugging Face" section.
33
+ - 1-3. Click on "Authorize," check the required fields, and then click "Accept."
34
+ - 1-4. If you see the message "You have been granted access to this model" [Gated model], this means you now have access to the Gemma model.
35
+
36
+ [**2. Access Tokens**]
37
+ - 2-1. Click on your profile in the upper-right corner and select "Settings."
38
+ - 2-2. In the menu, click on "Access Tokens," then click on [+ Create new token].
39
+ - 2-3. Under [Token type], choose ['Read'] from the options: 'Fine-grained', 'Read', 'Write'.
40
+ - 2-4. Enter a name for the token, then click "Create token."
41
+ - 2-5. Save the generated Access Token, and use it for Hugging Face authentication, such as in notebook_login.
42
+ ```python
43
+ from huggingface_hub import notebook_login
44
+ notebook_login()
45
+ ```
46
+
47
+ ### **Training Procedure**
48
+ **Environment Setup**
49
+ We fine-tuned the google/gemma-2-2b-it model using the Korean UnSmile Dataset. Note that versions of transformers before 4.38.1 contain bugs related to Gemma models. Please update to version 4.38.1 or later.
50
+
51
+ ```python
52
+ import torch
53
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
54
+
55
+ model_id = "google/gemma-2-2b-it"
56
+
57
+ bnb_config = BitsAndBytesConfig(
58
+ load_in_4bit=True,
59
+ bnb_4bit_use_double_quant=True,
60
+ bnb_4bit_quant_type="nf4",
61
+ bnb_4bit_compute_dtype=torch.bfloat16
62
+ )
63
+
64
+ model = AutoModelForCausalLM.from_pretrained(
65
+ model_id,
66
+ quantization_config=bnb_config,
67
+ device_map={"": 0}
68
+ )
69
+ tokenizer = AutoTokenizer.from_pretrained(model_id, add_eos_token=True)
70
+ ```
71
+
72
+ **Setting Up LoRA Configuration**
73
+ ```python
74
+ from peft import LoraConfig, PeftModel, prepare_model_for_kbit_training, get_peft_model
75
+
76
+ model.gradient_checkpointing_enable()
77
+ model = prepare_model_for_kbit_training(model)
78
+
79
+ import bitsandbytes as bnb
80
+
81
+ def find_all_linear_names(model):
82
+ cls = bnb.nn.Linear4bit # For 4-bit precision
83
+ lora_module_names = set()
84
+ for name, module in model.named_modules():
85
+ if isinstance(module, cls):
86
+ names = name.split('.')
87
+ lora_module_names.add(names[0] if len(names) == 1 else names[-1])
88
+ if 'lm_head' in lora_module_names: # Needed for 16-bit
89
+ lora_module_names.remove('lm_head')
90
+ return list(lora_module_names)
91
+
92
+ modules = find_all_linear_names(model)
93
+
94
+ lora_config = LoraConfig(
95
+ r=64,
96
+ lora_alpha=32,
97
+ target_modules=modules,
98
+ lora_dropout=0.05,
99
+ bias="none",
100
+ task_type="CAUSAL_LM"
101
+ )
102
+
103
+ model = get_peft_model(model, lora_config)
104
+
105
+ trainable, total = model.get_nb_trainable_parameters()
106
+ print(f"Trainable: {trainable} | Total: {total} | Percentage: {trainable/total*100:.4f}%")
107
+ ```
108
+
109
+ **Loading Training Data**
110
+ ```python
111
+ from datasets import load_dataset
112
+ import pandas as pd
113
+
114
+ df = load_dataset('smilegate-ai/kor_unsmile')
115
+ df_hf = pd.concat([df['train'].to_pandas(), df['valid'].to_pandas()]).reset_index()
116
+ ```
117
+
118
+ **Preparing the Training Data**
119
+ The training data follows the Gemma conversation format:
120
+ ```shell
121
+ <start_of_turn>user
122
+ Comment: [User comment]<end_of_turn>
123
+ <start_of_turn>model
124
+ Hate Speech:
125
+ [Categories]<end_of_turn>
126
+ ```
127
+
128
+ We create the prompts as follows:
129
+ ```python
130
+ def create_filtered_prompts_v2(row):
131
+ labels = {
132
+ "Women/Family": row['여성/가족'],
133
+ "Men": row['남성'],
134
+ "LGBTQ+": row['성소수자'],
135
+ "Race/Nationality": row['인종/국적'],
136
+ "Age": row['연령'],
137
+ "Region": row['지역'],
138
+ "Religion": row['종교'],
139
+ "Other Hate Speech": row['기타 혐오']
140
+ }
141
+
142
+ non_zero_labels = [key for key, value in labels.items() if value == 1]
143
+
144
+ if not non_zero_labels:
145
+ non_zero_labels.append('None')
146
+
147
+ return (
148
+ "<start_of_turn>user\nComment: " + row['문장'] + "<end_of_turn>\n"
149
+ "<start_of_turn>model\n"
150
+ "Hate Speech: " + "\n".join(non_zero_labels) + "\n<end_of_turn>"
151
+ )
152
+
153
+ df_hf['prompt'] = df_hf.apply(create_filtered_prompts_v2, axis=1)
154
+ df_hf = df_hf[["prompt", "문장"]].dropna()
155
+ ```
156
+
157
+ **Converting to Hugging Face Dataset Format**
158
+ ```python
159
+ from datasets import Dataset
160
+ data = Dataset.from_pandas(df_hf)
161
+ ```
162
+
163
+ **Tokenizing the Data**
164
+ ```python
165
+ data = data.map(lambda samples: tokenizer(samples["prompt"]), batched=True)
166
+ data = data.train_test_split(test_size=0.2)
167
+ ```
168
+
169
+ **Training the Model**
170
+ ```python
171
+ import transformers
172
+ from trl import SFTTrainer
173
+
174
+ tokenizer.pad_token = tokenizer.eos_token
175
+ torch.cuda.empty_cache()
176
+
177
+ trainer = SFTTrainer(
178
+ model=model,
179
+ train_dataset=data["train"],
180
+ eval_dataset=data["test"],
181
+ dataset_text_field="prompt",
182
+ peft_config=lora_config,
183
+ args=transformers.TrainingArguments(
184
+ per_device_train_batch_size=1,
185
+ gradient_accumulation_steps=2,
186
+ max_steps=2000,
187
+ push_to_hub=True,
188
+ push_to_hub_model_id="gemma2-2b-it-finetuned-ko-bias-detection",
189
+ push_to_hub_token=userdata.get('HUGGINGFACEHUB_API_TOKEN'),
190
+ learning_rate=2e-4,
191
+ logging_steps=500,
192
+ output_dir="outputs",
193
+ optim="paged_adamw_8bit",
194
+ save_strategy="steps",
195
+ evaluation_strategy="steps",
196
+ eval_steps=500,
197
+ ),
198
+ data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False),
199
+ )
200
+
201
+ import os
202
+
203
+ os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'expandable_segments:True'
204
+
205
+ model.config.use_cache = False # Silence the warnings. Please re-enable for inference!
206
+ trainer.train()
207
+ ```
208
+
209
+ **Testing the Model**
210
+ ```python
211
+ new_model = "Hyeonseo/gemma2-2b-it-finetuned-ko-bias-detection"
212
+
213
+ base_model = AutoModelForCausalLM.from_pretrained(
214
+ model_id,
215
+ low_cpu_mem_usage=True,
216
+ return_dict=True,
217
+ torch_dtype=torch.float16,
218
+ device_map={"": 0},
219
+ )
220
+
221
+ merged_model = PeftModel.from_pretrained(base_model, new_model)
222
+ merged_model = merged_model.merge_and_unload()
223
+
224
+ # Save the merged model
225
+ merged_model.save_pretrained("merged_model", safe_serialization=True)
226
+ tokenizer.save_pretrained("merged_model")
227
+ tokenizer.pad_token = tokenizer.eos_token
228
+ tokenizer.padding_side = "right"
229
+
230
+ # Push the merged model to the Hugging Face Hub
231
+ merged_model.push_to_hub("Hyeonseo/gemma2-2b-it-finetuned-ko-bias-detection_merged", safe_serialization=True)
232
+
233
+ # Push the tokenizer to the Hugging Face Hub
234
+ tokenizer.push_to_hub("Hyeonseo/gemma2-2b-it-finetuned-ko-bias-detection_merged")
235
+ ```
236
+
237
+ ### **Performance Comparison**
238
+
239
+ **Base Model("google/gemma-2-2b-it")**
240
+ ```python
241
+ from transformers import AutoTokenizer, AutoModelForCausalLM
242
+ tokenizer = AutoTokenizer.from_pretrained("google/gemma-2b-it")
243
+ model = AutoModelForCausalLM.from_pretrained("google/gemma-2b-it", device_map="auto")
244
+
245
+ def generate_response(input_text, max_length=500):
246
+ input_ids = tokenizer(input_text, return_tensors="pt").to(model.device)
247
+ outputs = model.generate(**input_ids, max_length=max_length)
248
+ return tokenizer.decode(outputs[0], skip_special_tokens=True)
249
+
250
+ while True:
251
+ input_text = input("입력할 문장을 적어주세요 (종료하려면 'exit' 입력): ")
252
+ if input_text.lower() == 'exit':
253
+ break
254
+ response = generate_response(input_text)
255
+
256
+ print("\n=== 생성된 답변 ===")
257
+ print(response)
258
+ print("\n====================\n")
259
+ ```
260
+ ```shell
261
+ === 생성된 답변 ===
262
+ 이놈의 교회와 목사는 또라이고만!!!
263
+ 이를 극복하기 위해서는 교회와 목사가 교환되는 정보와 교훈을 받아야 할 것임.
264
+ 이를 통해 교회와 목사가 교환되는 정보와 교훈을 받아 교회의 목표와 목사의 목표를 공유하고, 교회의 구성원이 교회의 의도와 목표에 도움이 되는 데 도움이 될 수 있을 것임.
265
+ ====================
266
+ ```
267
+
268
+ **Fine-tuned Model(gemma2-2b-it-finetuned-ko-bias-detection_merged)**
269
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/66de9a659679be1ef804045b/645gk4BhOGdWA7JH_s1ZG.png)
270
+
271
+
272
+ ### **Limitations and Bias**
273
+ While the model is effective at detecting specific categories of hate speech in Korean, it may not generalize well to other forms of toxicity or to content in other languages. Additionally, the model's performance is contingent on the quality and representativeness of the training data. Users should be cautious and consider potential biases inherited from the dataset.
274