Views
No views yet
1from transformers import AutoModelForCausalLM, AutoTokenizer
2from peft import PeftModel
3import torch
4
5base_model_id = "swiss-ai/Apertus-8B-Instruct-2509"
6adapter_id = "steephole5586/pwnednext"
7device = "cuda" if torch.cuda.is_available() else "cpu"
8
9tokenizer = AutoTokenizer.from_pretrained(base_model_id)
10base_model = AutoModelForCausalLM.from_pretrained(
11 base_model_id,
12 dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
13 device_map="auto"
14)
15
16model = PeftModel.from_pretrained(base_model, adapter_id)
17
18prompt = "What are the advantages of using AI?"
19inputs = tokenizer(prompt, return_tensors="pt").to(device)
20
21with torch.no_grad():
22 outputs = model.generate(
23 **inputs,
24 max_new_tokens=128,
25 temperature=0.7,
26 do_sample=True,
27 pad_token_id=tokenizer.eos_token_id
28 )
29
30print(tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True))1import torch
2import inspect
3from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
4from trl import SFTConfig
5from datasets import load_dataset
6from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
7from trl import SFTTrainer # SFTConfig already imported above
8
9# 1. Define model and dataset
10model_id = "./Apertus-8B-Instruct-2509" # Path to your cloned folder
11dataset_name = "timdettmers/openassistant-guanaco" # Replace with your own dataset
12
13# 2. Configure 4-bit quantization (Saves a lot of VRAM)
14bnb_config = BitsAndBytesConfig(
15 load_in_4bit=True,
16 bnb_4bit_quant_type="nf4",
17 bnb_4bit_compute_dtype=torch.float32,
18 bnb_4bit_use_double_quant=True
19)
20
21# 3. Load tokenizer and model
22tokenizer = AutoTokenizer.from_pretrained(model_id)
23tokenizer.pad_token = tokenizer.eos_token
24
25model = AutoModelForCausalLM.from_pretrained(
26 model_id,
27 quantization_config=bnb_config,
28 device_map="auto"
29)
30
31# Prepare the model for quantized training
32model = prepare_model_for_kbit_training(model)
33
34# 4. Configure LoRA (Only these weights will be updated)
35lora_config = LoraConfig(
36 r=16,
37 lora_alpha=32,
38 target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
39 lora_dropout=0.05,
40 bias="none",
41 task_type="CAUSAL_LM"
42)
43
44# 5. Load dataset
45dataset = load_dataset(dataset_name, split="train[:1000]") # Using the first 1000 examples as a test
46
47# 6. Define training parameters
48training_args = SFTConfig(
49 output_dir="./pwnednext",
50 per_device_train_batch_size=2,
51 gradient_accumulation_steps=4,
52 learning_rate=2e-4,
53 logging_steps=10,
54 max_steps=100, # Adjust as needed
55 bf16=False,
56 fp16=False,
57 optim="adamw_torch",
58 save_strategy="steps",
59 save_steps=50,
60 dataset_text_field="text",
61 max_length=512,
62)
63
64# 7. Start training
65trainer_kwargs = {
66 "model": model,
67 "train_dataset": dataset,
68 "peft_config": lora_config,
69 "args": training_args,
70}
71# The SFTTrainer constructor has changed in different versions of the trl library, so we check which parameters it accepts and pass the appropriate ones.
72sft_init_params = inspect.signature(SFTTrainer.__init__).parameters
73if "processing_class" in sft_init_params:
74 trainer_kwargs["processing_class"] = tokenizer
75elif "tokenizer" in sft_init_params:
76 trainer_kwargs["tokenizer"] = tokenizer
77
78trainer = SFTTrainer(**trainer_kwargs) # Initialize the trainer with the appropriate parameters based on its constructor signature
79
80print("Starting fine-tuning...")
81trainer.train()
82
83# 8. Store the trained LoRA weights
84trainer.model.save_pretrained("./apertus-lora-adapter")
85print("Training complete and adapter saved!")1@software{vonwerra2020trl,
2 title = {{TRL: Transformers Reinforcement Learning}},
3 author = {von Werra, Leandro and Belkada, Younes and Tunstall, Lewis and Beeching, Edward and Thrush, Tristan and Lambert, Nathan and Huang, Shengyi and Rasul, Kashif and Gallouédec, Quentin},
4 license = {Apache-2.0},
5 url = {https://github.com/huggingface/trl},
6 year = {2020}
7}