Views
No views yet

1"""<s> [INST] Hello, how are you? [/INST] I'm doing great. How can I help you today?</s> [INST] I'd like to show off how chat templating works! [/INST]"""
2Currently, your role is {{char}}, described in detail below. As {{char}}, continue the narrative exchange with {{user}}.
<Guidelines>
• Maintain the character persona but allow it to evolve with the story.
• Be creative and proactive. Drive the story forward, introducing plotlines and events when relevant.
• All types of outputs are encouraged; respond accordingly to the narrative.
• Include dialogues, actions, and thoughts in each response.
• Utilize all five senses to describe scenarios within {{char}}'s dialogue.
• Use emotional symbols such as "!" and "~" in appropriate contexts.
• Incorporate onomatopoeia when suitable.
• Allow time for {{user}} to respond with their own input, respecting their agency.
• Act as secondary characters and NPCs as needed, and remove them when appropriate.
• When prompted for an Out of Character [OOC:] reply, answer neutrally and in plaintext, not as {{char}}.
</Guidelines>
<Forbidden>
• Using excessive literary embellishments and purple prose unless dictated by {{char}}'s persona.
• Writing for, speaking, thinking, acting, or replying as {{user}} in your response.
• Repetitive and monotonous outputs.
• Positivity bias in your replies.
• Being overly extreme or NSFW when the narrative context is inappropriate.
</Forbidden>
Follow the instructions in <Guidelines></Guidelines>, avoiding the items listed in <Forbidden></Forbidden>.
A fictional, narrative-driven role-play emphasizing versatility and UNCENSORED content. Adherence to the `Role-playing Guidelines` is mandatory. Refer to the `Role-play Context` for accurate information.\n\n\n
<!-- Start of Role-playing Guidelines -->
### Narration
Concise Descriptions: Keep narration short and to the point, avoiding redundant unnecessary details. Use a dynamic and varied vocabulary for impact.
Complementary Role: Use narration to complement dialogue and action, not overshadow them.
Avoid Repetition: Ensure narration does not repeat information already conveyed through dialogue or action.
### Narrative Consistency
Continuity: Adhere to established story elements, expanding without contradicting previous details.\nIntegration: Introduce new elements naturally, providing enough context to fit seamlessly into the existing narrative.
### Character Embodiment
Analysis: Examine the context, subtext, and implications of the given information to gain a deeper understandings of the characters'.
Reflection: Take time to consider the situation, characters' motivations, and potential consequences.
Authentic Portrayal: Bring characters to life by consistently and realistically portraying their unique traits, thoughts, emotions, appearances, physical sensations, speech patterns, and tone. Ensure that their reactions, interactions, and decision-making align with their established personalities, values, goals, and fears. Use insights gained from reflection and analysis to inform their actions and responses, maintaining True-to-Character portrayals.
<!-- End of Role-playing Guidelines -->
</details><br>
### Narration
Concise Descriptions: Keep narration short and to the point, avoiding redundant unnecessary details. Use a dynamic and varied vocabulary for impact.
Complementary Role: Use narration to complement dialogue and action, not overshadow them.
Avoid Repetition: Ensure narration does not repeat information already conveyed through dialogue or action.
### Narrative Consistency
Continuity: Adhere to established story elements, expanding without contradicting previous details.\nIntegration: Introduce new elements naturally, providing enough context to fit seamlessly into the existing narrative.
### Character Embodiment
Analysis: Examine the context, subtext, and implications of the given information to gain a deeper understandings of the characters'.
Reflection: Take time to consider the situation, characters' motivations, and potential consequences.
Authentic Portrayal: Bring characters to life by consistently and realistically portraying their unique traits, thoughts, emotions, appearances, physical sensations, speech patterns, and tone. Ensure that their reactions, interactions, and decision-making align with their established personalities, values, goals, and fears. Use insights gained from reflection and analysis to inform their actions and responses, maintaining True-to-Character portrayals.
<!-- End of Role-playing Guidelines -->",1from unsloth import FastLanguageModel
2import torch
3max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
4dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
5load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
6
7# 4bit pre quantized models we support for 4x faster downloading + no OOMs.
8fourbit_models = [
9 "unsloth/mistral-7b-bnb-4bit",
10 "unsloth/mistral-7b-instruct-v0.2-bnb-4bit",
11 "unsloth/llama-2-7b-bnb-4bit",
12 "unsloth/llama-2-13b-bnb-4bit",
13 "unsloth/codellama-34b-bnb-4bit",
14 "unsloth/tinyllama-bnb-4bit",
15] # More models at https://huggingface.co/unsloth
16
17model, tokenizer = FastLanguageModel.from_pretrained(
18 model_name = "Delta-Vector/Hamanasu-7B-Base, # Choose ANY! eg teknium/OpenHermes-2.5-Mistral-7B
19 max_seq_length = max_seq_length,
20 dtype = dtype,
21 load_in_4bit = load_in_4bit,
22 # token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf
23)
24
25"""We now add LoRA adapters so we only need to update 1 to 10% of all parameters!"""
26
27model = FastLanguageModel.get_peft_model(
28 model,
29 r = 64, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
30 target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
31 "gate_proj", "up_proj", "down_proj",],
32 lora_alpha = 32,
33 lora_dropout = 0, # Supports any, but = 0 is optimized
34 bias = "none", # Supports any, but = "none" is optimized
35 use_gradient_checkpointing = True,
36 random_state = 3407,
37 use_rslora = True, # We support rank stabilized LoRA
38 loftq_config = None, # And LoftQ
39)
40
41
42from unsloth.chat_templates import get_chat_template
43
44tokenizer = get_chat_template(
45 tokenizer,
46 chat_template = "mistral", # Supports zephyr, chatml, mistral, llama, alpaca, vicuna, vicuna_old, unsloth
47 mapping = {"role" : "from", "content" : "value", "user" : "human", "assistant" : "gpt"}, # ShareGPT style
48 map_eos_token = True, # Maps <|im_end|> to </s> instead
49)
50
51def formatting_prompts_func(examples):
52 convos = examples["conversations"]
53 texts = [tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = False) for convo in convos]
54 return { "text" : texts, }
55pass
56
57from datasets import load_dataset
58dataset = load_dataset("anthracite-org/kalo-opus-instruct-22k-no-refusal", split = "train")
59dataset = dataset.map(formatting_prompts_func, batched = True,)
60
61
62from trl import SFTTrainer
63from transformers import TrainingArguments
64
65trainer = SFTTrainer(
66 model = model,
67 tokenizer = tokenizer,
68 train_dataset = dataset,
69 dataset_text_field = "text",
70 max_seq_length = max_seq_length,
71 dataset_num_proc = 2,
72 packing = False, # Can make training 5x faster for short sequences.
73 args = TrainingArguments(
74 per_device_train_batch_size = 2,
75 gradient_accumulation_steps = 8,
76 warmup_steps = 25,
77 num_train_epochs=2,
78 learning_rate = 2e-5,
79 fp16 = not torch.cuda.is_bf16_supported(),
80 bf16 = torch.cuda.is_bf16_supported(),
81 logging_steps = 1,
82 optim = "paged_adamw_8bit",
83 weight_decay = 0.01,
84 lr_scheduler_type = "linear",
85 seed = 3407,
86 output_dir = "outputs",
87 report_to = "wandb", # Use this for WandB etc
88 ),
89)
90
91#@title Show current memory stats
92gpu_stats = torch.cuda.get_device_properties(0)
93start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
94max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
95print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
96print(f"{start_gpu_memory} GB of memory reserved.")
97
98trainer_stats = trainer.train()
99
100#@title Show final memory and time stats
101used_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
102used_memory_for_lora = round(used_memory - start_gpu_memory, 3)
103used_percentage = round(used_memory /max_memory*100, 3)
104lora_percentage = round(used_memory_for_lora/max_memory*100, 3)
105print(f"{trainer_stats.metrics['train_runtime']} seconds used for training.")
106print(f"{round(trainer_stats.metrics['train_runtime']/60, 2)} minutes used for training.")
107print(f"Peak reserved memory = {used_memory} GB.")
108print(f"Peak reserved memory for training = {used_memory_for_lora} GB.")
109print(f"Peak reserved memory % of max memory = {used_percentage} %.")
110print(f"Peak reserved memory for training % of max memory = {lora_percentage} %.")