Views
No views yet
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.1from huggingface_hub import notebook_login
2notebook_login()1import torch
2from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
3
4model_id = "google/gemma-2-2b-it"
5
6bnb_config = BitsAndBytesConfig(
7 load_in_4bit=True,
8 bnb_4bit_use_double_quant=True,
9 bnb_4bit_quant_type="nf4",
10 bnb_4bit_compute_dtype=torch.bfloat16
11)
12
13model = AutoModelForCausalLM.from_pretrained(
14 model_id,
15 quantization_config=bnb_config,
16 device_map={"": 0}
17)
18tokenizer = AutoTokenizer.from_pretrained(model_id, add_eos_token=True)1from peft import LoraConfig, PeftModel, prepare_model_for_kbit_training, get_peft_model
2
3model.gradient_checkpointing_enable()
4model = prepare_model_for_kbit_training(model)
5
6import bitsandbytes as bnb
7
8def find_all_linear_names(model):
9 cls = bnb.nn.Linear4bit # For 4-bit precision
10 lora_module_names = set()
11 for name, module in model.named_modules():
12 if isinstance(module, cls):
13 names = name.split('.')
14 lora_module_names.add(names[0] if len(names) == 1 else names[-1])
15 if 'lm_head' in lora_module_names: # Needed for 16-bit
16 lora_module_names.remove('lm_head')
17 return list(lora_module_names)
18
19modules = find_all_linear_names(model)
20
21lora_config = LoraConfig(
22 r=64,
23 lora_alpha=32,
24 target_modules=modules,
25 lora_dropout=0.05,
26 bias="none",
27 task_type="CAUSAL_LM"
28)
29
30model = get_peft_model(model, lora_config)
31
32trainable, total = model.get_nb_trainable_parameters()
33print(f"Trainable: {trainable} | Total: {total} | Percentage: {trainable/total*100:.4f}%")1from datasets import load_dataset
2import pandas as pd
3
4df = load_dataset('smilegate-ai/kor_unsmile')
5df_hf = pd.concat([df['train'].to_pandas(), df['valid'].to_pandas()]).reset_index()1<start_of_turn>user
2Comment: [User comment]<end_of_turn>
3<start_of_turn>model
4Hate Speech:
5[Categories]<end_of_turn>1def create_filtered_prompts_v2(row):
2 labels = {
3 "Women/Family": row['여성/가족'],
4 "Men": row['남성'],
5 "LGBTQ+": row['성소수자'],
6 "Race/Nationality": row['인종/국적'],
7 "Age": row['연령'],
8 "Region": row['지역'],
9 "Religion": row['종교'],
10 "Other Hate Speech": row['기타 혐오']
11 }
12
13 non_zero_labels = [key for key, value in labels.items() if value == 1]
14
15 if not non_zero_labels:
16 non_zero_labels.append('None')
17
18 return (
19 "<start_of_turn>user\nComment: " + row['문장'] + "<end_of_turn>\n"
20 "<start_of_turn>model\n"
21 "Hate Speech: " + "\n".join(non_zero_labels) + "\n<end_of_turn>"
22 )
23
24df_hf['prompt'] = df_hf.apply(create_filtered_prompts_v2, axis=1)
25df_hf = df_hf[["prompt", "문장"]].dropna()1from datasets import Dataset
2data = Dataset.from_pandas(df_hf)1data = data.map(lambda samples: tokenizer(samples["prompt"]), batched=True)
2data = data.train_test_split(test_size=0.2)1import transformers
2from trl import SFTTrainer
3
4tokenizer.pad_token = tokenizer.eos_token
5torch.cuda.empty_cache()
6
7trainer = SFTTrainer(
8 model=model,
9 train_dataset=data["train"],
10 eval_dataset=data["test"],
11 dataset_text_field="prompt",
12 peft_config=lora_config,
13 args=transformers.TrainingArguments(
14 per_device_train_batch_size=1,
15 gradient_accumulation_steps=2,
16 max_steps=2000,
17 push_to_hub=True,
18 push_to_hub_model_id="gemma2-2b-it-finetuned-ko-bias-detection",
19 push_to_hub_token=userdata.get('HUGGINGFACEHUB_API_TOKEN'),
20 learning_rate=2e-4,
21 logging_steps=500,
22 output_dir="outputs",
23 optim="paged_adamw_8bit",
24 save_strategy="steps",
25 evaluation_strategy="steps",
26 eval_steps=500,
27 ),
28 data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False),
29)
30
31import os
32
33os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'expandable_segments:True'
34
35model.config.use_cache = False # Silence the warnings. Please re-enable for inference!
36trainer.train()1new_model = "Hyeonseo/gemma2-2b-it-finetuned-ko-bias-detection"
2
3base_model = AutoModelForCausalLM.from_pretrained(
4 model_id,
5 low_cpu_mem_usage=True,
6 return_dict=True,
7 torch_dtype=torch.float16,
8 device_map={"": 0},
9)
10
11merged_model = PeftModel.from_pretrained(base_model, new_model)
12merged_model = merged_model.merge_and_unload()
13
14# Save the merged model
15merged_model.save_pretrained("merged_model", safe_serialization=True)
16tokenizer.save_pretrained("merged_model")
17tokenizer.pad_token = tokenizer.eos_token
18tokenizer.padding_side = "right"
19
20# Push the merged model to the Hugging Face Hub
21merged_model.push_to_hub("Hyeonseo/gemma2-2b-it-finetuned-ko-bias-detection_merged", safe_serialization=True)
22
23# Push the tokenizer to the Hugging Face Hub
24tokenizer.push_to_hub("Hyeonseo/gemma2-2b-it-finetuned-ko-bias-detection_merged")1from transformers import AutoTokenizer, AutoModelForCausalLM
2tokenizer = AutoTokenizer.from_pretrained("google/gemma-2b-it")
3model = AutoModelForCausalLM.from_pretrained("google/gemma-2b-it", device_map="auto")
4
5def generate_response(input_text, max_length=500):
6 input_ids = tokenizer(input_text, return_tensors="pt").to(model.device)
7 outputs = model.generate(**input_ids, max_length=max_length)
8 return tokenizer.decode(outputs[0], skip_special_tokens=True)
9
10while True:
11 input_text = input("입력할 문장을 적어주세요 (종료하려면 'exit' 입력): ")
12 if input_text.lower() == 'exit':
13 break
14 response = generate_response(input_text)
15
16 print("\n=== 생성된 답변 ===")
17 print(response)
18 print("\n====================\n")1=== 생성된 답변 ===
2이놈의 교회와 목사는 또라이고만!!!
3이를 극복하기 위해서는 교회와 목사가 교환되는 정보와 교훈을 받아야 할 것임.
4이를 통해 교회와 목사가 교환되는 정보와 교훈을 받아 교회의 목표와 목사의 목표를 공유하고, 교회의 구성원이 교회의 의도와 목표에 도움이 되는 데 도움이 될 수 있을 것임.
5====================